72 lines
1.4 KiB
Java
72 lines
1.4 KiB
Java
import java.util.ArrayList;
|
|
import java.util.Scanner;
|
|
import java.io.FileInputStream;
|
|
import java.io.IOException;
|
|
/*
|
|
* Same as the lab str vs int, except the input comes from a file
|
|
* instead of the keyboard.
|
|
* Use NamesAndAges.txt for input
|
|
*/
|
|
|
|
public class main {
|
|
|
|
public static void main(String[] args) throws IOException {
|
|
FileInputStream fileByteStream = null; // File input stream
|
|
Scanner inFS = null; // Scanner object
|
|
|
|
String s = "";
|
|
ArrayList<String> userInputs = new ArrayList<String>();
|
|
String name;
|
|
int age;
|
|
|
|
//Get input
|
|
System.out.println("Opening file NamesAndAges.txt.");
|
|
fileByteStream = new FileInputStream("NamesAndAges.txt");
|
|
inFS = new Scanner(fileByteStream);
|
|
|
|
System.out.println("Reading in file and processing");
|
|
|
|
while(true){
|
|
|
|
//Get name or exit
|
|
s = inFS.next();
|
|
|
|
if (s.equals("-1")){
|
|
System.out.println();
|
|
break;
|
|
}
|
|
else{
|
|
name = s;
|
|
}
|
|
|
|
//Get age
|
|
|
|
try{
|
|
age = inFS.nextInt() +1;
|
|
}
|
|
catch(Exception e){
|
|
System.out.println("Age must be an Integer\n" +
|
|
"Setting age to 0 ");
|
|
age = 0;
|
|
|
|
}
|
|
//Finish line
|
|
inFS.nextLine();
|
|
|
|
//Add name plus new age to arr
|
|
userInputs.add(name + " " + Integer.toString(age));
|
|
|
|
System.out.println();
|
|
}
|
|
|
|
System.out.println("Closing scanner and printing out results ");
|
|
fileByteStream.close();
|
|
inFS.close();
|
|
|
|
for (String S:userInputs){
|
|
System.out.println(S);
|
|
}
|
|
}
|
|
}
|
|
|