Try/catch & saving an ArrayList using Scanner in Java - java

I don't understand how to code this properly. I've read all over the internet and my book and maybe I am over complicating this.
I am trying to save the arraylist to a .txt -Obviously when I press '1' to add(studentInfo) it is giving me the exception because apparently it is what I'm telling it to do.
What I want is to add() and if the file exist then to override it or to open it and save on it again.
I apologize if this sounds confusing. I am very confused myself.
case 1:
try{
addStudent(studentInfo);
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
break;
case 2:
removeStudent(studentInfo);
break;
case 3:
display(studentInfo);
break;
case 4:
load(studentInfo);
case 0:
System.out.println("Thank you for using the student database!");
System.exit(0);
}
}
}
//ADD
private void addStudent(ArrayList<Student> studentInfo) throws FileNotFoundException {
Scanner add = new Scanner(new File("students.txt"));
while(add.hasNext()){
System.out.println("\nEnter the student's name: ");
String name = add.nextLine();
System.out.println("\nEnter the student's last name: ");
String lastName = add.nextLine();
System.out.println("\nEnter the student's major: ");
String major = add.nextLine();
System.out.println("\nEnter the student's GPA: ");
String gpaNumber = add.nextLine();
double gpa = Double.parseDouble(gpaNumber);
System.out.println("\nEnter the student's UIN: ");
String uinNumber = add.nextLine();
int uin = Integer.parseInt(uinNumber);
System.out.println("\nEnter the student's NetID: ");
String idName = add.nextLine();
System.out.println("\nEnter the student's age: ");
String years = add.nextLine();
int age = Integer.parseInt(years);
System.out.println("\nEnter the student's gender: Female or Male ");
String gender = add.nextLine();
Student newStudent = new Student (name, lastName, major, gpa, uin, idName, age, gender);
if(studentInfo.size() <10){
studentInfo.add(newStudent);
System.out.println("Student information saved.");
System.out.println();
}
else{
System.out.println("Database is full");
}
}
add.close();
}

My understanding is that you are trying to construct a new student object, input a student's information, and then write all of the students' information to a file.
new File(students.txt) is how you can tell Java how to work with an existing file, it can't create one, and that's what is causing your error. You can create a students.txt file if you'd like to see how your code will perform after that error is resolved.
Scanner is an input handler, not a document writer. So when your add Scanner is constructed using a File object, it's actually going to be reading already existing information in that file. It won't allow you to write to the file.
Furthermore, when you are using nextLine(), it is iterating through lines in the file, not writing (or accepting) your input.
I recommend reading up on Java File I/O. There are a lot of materials online and here on Stack Overflow. If this is a homework assignment, be careful not to use anything "cutting edge" if your teacher wants you to go by the book.

Related

Java scanner input mismatch when using space in input

I am using the scanner in java and am trying to enter a space in my input for option 2 (removing a user from my hashmap) but when I add a space in my answer I get an InputMismatchException. while researching I came across this thread Scanner Class InputMismatchException and Warnings that says to use this line of code to solve the issue: .useDelimiter(System.getProperty("line.separator")); i have added this and now my option 2 goes into a never-ending loop of me inputting data. Here is my code:
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AddressBook ad1 = new AddressBook();
String firstName="";
String lastName="";
String key="";
int choice=0;
do{
System.out.println("********************************************************************************");
System.out.println("Welcome to the Address book. Please pick from the options below.\n");
System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");
System.out.print("Please enter a choice: ");
choice = scan.nextInt();
if(choice==1){
//Add user
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
Address address = new Address();
key = lastName.concat(firstName);
Person person = new Person(firstName,lastName);
ad1.addContact(key,person);
System.out.println("key: " + key);
}
else if(choice==2){
//Remove user
System.out.println("Please enter name of user to remove: ");
scan.useDelimiter(System.getProperty("line.separator"));
key=scan.next();
System.out.println("name:" + key);
ad1.removeContact(key);
}
else if(choice==3){
//Edit user
}
else if(choice==4){
//List contact
ad1.listAllContacts();
}
else if(choice==5){
//Sort contacts
}
}while(choice!=6);
}
}
The reason why I need to use a space is to remove a user from my hashmap I need to enter their full name as the key is a concatenation of their last and firstname, any help will be appreciated
nextInt() behaves similar to next() that is when it read a line it places the cursor behind it.
Example:
You give 6 as input
6
^(scanner's cursor)
So next time when you call nextLine(). It will return the whole line after that cursor which is empty in this case.
To fix this issue you need to call an extra nextLine() so that the Scanner closes the previous line it was reading and move on to the next line.
You could do this
System.out.print("Please enter a choice: ");
choice = scan.nextInt(); // Reads the int
scan.nextLine(); // Discards the line
And in choice 2 since you want full name of user you could just use nextLine() to get whole line along with space.
//Remove user
System.out.println("Please enter full name of user to remove: ");
key=scan.nextLine();
System.out.println("name:" + key);
ad1.removeContact(key);
Or you could do something similar to what you did in choice 1
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
key = lastName.concat(firstName);
System.out.println("name:" + key);
ad1.removeContact(key);
scan.nextLine(); // This is will make sure that in you next loop `nextInt()` won't give an input mismatch exception

How to make it so the user can replace a sentence they typed can be replaced in Java

So I am trying to make the program ask the user the following and get the following answer:
For example:
Type a 2nd Sentence Below:
This is a book (user inputs this)
Choose what string of characters do you want to replace:
book (user inputs this)
Choose what new string will be used in the replacement:
car (user inputs this)
The text after the replacement is: This is a car.
import java.util.*;
import java.util.Scanner;
public class StringManipulation {
public static void main(String[]args) {
/*This is where the user can type a second sentence*/
System.out.println("Type a 2nd Sentence Below:");
Scanner sd = new Scanner(System.in);
String typingtwo = sd.nextLine();
String sending;
/*Here the program will tell the user a message*/
System.out.println("This is your sentence in capital letters:");
sending = typingtwo.toUpperCase();
System.out.println(sending);
/*Here the program will tell the user another message*/
System.out.println("This is your sentence in lower letters:");
sending = typingtwo.toLowerCase();
System.out.println(sending);
System.out.print("Your Token Count:");
int FrequencyTwo = new StringTokenizer(sending, " ").countTokens();
System.out.println(FrequencyTwo);
String charactertwo = new String(typingtwo);
System.out.print("Your Character Length:");
System.out.println(charactertwo.length());
String repWords;
String newWord;
String nwords;
String twords;
System.out.println("Choose what string of characters do you want to
replace");
repWords = sd.next();
System.out.println("Choose what new string will be used in the replacement");
nwords = sc.next();
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
}
}
I have tried everything but for some reason I keep getting the word that they chose at the end only. Pleas help!
try using Scanner.nextLine instead of Scanner.next
refer to the Java API documentation to understand the difference between the two
Here is another problem:
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
You are printing nwords instead of twords.
Two errors i could see.
nwords = sc.next(); here it should give compilation error as scanner instance name is sd.
You are trying to print nwords at the end. it should be "twords".

Prevent user from entering whitespace in Java

I want the user to only enter his age. So I did this program :
Scanner keyb = new Scanner(System.in);
int age;
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("How old are you ?");
}
age = keyb.nextInt();
System.out.println("you are" + age + "years old");
I found how to prevent user from using string by using the while loop with keyb.hasNextInt(), but how to prevent him from using the whitespace or from entering more input than his age ?
For example I want to prevent this kind of typing "12 m" or "12 12"
Also, how can I clear all existing data in the buffer ? I'm facing an infinite loop when I try to use this :
while(keyb.hasNext())
keyb.next();
You want to get the whole line. Use nextLine and check that for digits e.g.
String possibleAge = "";
do {
System.out.println("How old are you ?");
possibleAge = keyb.nextLine();
} while (!possibleAge.matches("\\d+"))
Your problem is that the default behaviour of Scanner is to use any whitespace as the delimiter. This includes spaces. This means that a 3 a is in fact three tokens, not one. You can change the delimiter to a new line so that a 3 a becomes a single token, which will then return false for hasNextInt.
I've also added an initial question, because in your example the first input was taken before asking any questions.
Scanner keyb = new Scanner(System.in);
keyb.useDelimiter("\n"); // You can try System.lineSeparator() but it didn't work in IDEA
int age;
System.out.println("How old are you?");
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("No really. How old are you?");
}
age = keyb.nextInt();
System.out.println("You are " + age + " years old");
String age = "11";
if (age.matches(".*[^0-9].*")) {
System.out.println("Invalid age");
} else {
System.out.println("valid age");
}
If age contains other then digits then it will print invalid age.

Putting a loop around nested if else statements

I'm sort of new at working with Java. I'm working on a program that takes in student names and their IDs, and when the correct ID is inputted afterwards, it spits out that student's information. The sample output would sort of look like this: How many students would you like to input? (2) What are their names? (Sally, Jack) What are their IDs? (2332, 5631) Would you like to search for a student? (Y) Please input their ID: (2332) We found Sally!
Here is a snippet of the code that searches back for the Student:
System.out.println("Would you like to search for a student?");
String answer = scan.next();
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
int id = scan.nextInt();
boolean found = Student.lookupID(list, id);
if(found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); //fix this
else
System.out.println("Error");
}
else {
System.out.println("Thanks for using this system!");
}
}
}
Right now, I'm trying to loop the code, so that the Output would now look like this: How many students would you like to input? (3) What are their names? (Sally, Jack, Rick) What are their IDs? (2332, 5631, 3005) Would you like to search for a student? (Y) Please input their ID: (2332) We found Sally! Would you like to search for another student? (Y) Please input their ID: (5631) We found Jack! Would you like to search for another student? (N) Thanks for using our system!
Would someone be able to help me with this?
You need to reset id to program be able to get new id.Try correct your code like this :
System.out.println("Would you like to search for a student?");
String answer = scan.next();
int id = 0; //RESET THE ID TO BE ABLE REPLAYIN WORK!
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
id = scan.nextInt();
boolean found = Student.lookupID(id);
if (found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); // fix
// this
else
System.out.println("Error");
} else {
System.out.println("Thanks for using this system!");
}

If statement is unexpectedly running. How do I debug this? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
The purpose of this application is to get the full name of a user, and split them up. The results are printed.
if(nameParts.length < 2|| nameParts.length > 3) is somehow gaining control from the loop after it runs a 2nd time or beyond. I would assume that name and nameParts should be getting values assigned to them once again. Why is this happening, and how can I fix this?
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
System.out.println("Welcome to the name parser.\n");
while(choice.equalsIgnoreCase("y")) {
System.out.print("Enter a name: ");
String name = sc.nextLine();
String[] nameParts = nameSeperate(name);
if(nameParts.length < 2|| nameParts.length > 3) {
System.out.println("Please enter your full name or your first and last name.");
continue;
}
else if(nameParts.length == 2) {
System.out.println("First Name: " + nameParts[0]);
System.out.println("Last Name: " + nameParts[0]);
}
else {
System.out.println("First Name: " + nameParts[0]);
System.out.println("Middle Name: " + nameParts[1]);
System.out.println("Last Name: " + nameParts[2]);
}
System.out.println("Would you like to enter another name? (y/n)");
choice = sc.next();
}
}
Here is the output:
Welcome to the name parser.
Enter a name: Alfons Pineda
First Name: Alfons
Last Name: Pineda
Would you like to enter another name? (y/n)
y
Enter a name: Please enter your full name or your first and last name.
Enter a name: Alfons Pineda
First Name: Alfons
Last Name: Pineda
Would you like to enter another name? (y/n)
n
I am not sure, but for your first scan you use sc.nextLine() and for the second one just sc.next(). Maybe using sc.nextLine() also for the second statement would help. It could be, that the \n was not read by sc.next().
Therefore in the second loop only the newline would be read by the first scan.

Categories

Resources