Update java input/output/exceptions

This commit is contained in:
Logen Kain 2021-03-10 16:07:13 -05:00
parent aeb8c6c24f
commit 8f7143d6b4
3 changed files with 103 additions and 0 deletions

View File

@ -0,0 +1,5 @@
Lee 18
Lua 21
Mary Beth 19
Stu 33
-1

View File

@ -0,0 +1,4 @@
Lee 19
Lua 22
Mary 0
Stu 34

View File

@ -0,0 +1,94 @@
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
/*
* Same as the input one and the string vs int one, but now writting to a file
* instead of the screen.
*/
public class main {
public static ArrayList<String> getInput(Scanner scnr){
String s = "";
String name;
int age;
ArrayList<String> results = new ArrayList<String>();
while(true){
//Get name or exit
s = scnr.next();
if (s.equals("-1")){
System.out.println();
break;
}
else{
name = s;
}
//Get age
try{
age = scnr.nextInt() +1;
}
catch(Exception e){
System.out.println("Age must be an Integer\n" +
"Setting age to 0 ");
age = 0;
}
//Finish line
scnr.nextLine();
//Add name plus new age to arr
results.add(name + " " + Integer.toString(age));
System.out.println();
}
return results;
}
public static void main(String[] args) throws IOException {
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
ArrayList<String> userInputs = new ArrayList<String>();
//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");
userInputs = getInput(inFS);
System.out.println("Closing scanner and writing out results " +
"To NamesAndAgesUpdated.txt");
fileByteStream.close();
inFS.close();
//Write to file
FileOutputStream fileStream = null;
PrintWriter outFS = null;
fileStream = new FileOutputStream("NamesAndAgesUpdated.txt");
outFS = new PrintWriter(fileStream);
for (String S:userInputs){
outFS.println(S);
}
outFS.flush();
fileStream.close();
outFS.close();
}
}