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
Related
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".
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.
This code is only showing output as
Enter Name of the item you want to add Enter the price of item
While it should take the name before it takes the double as input.
newMenu = new Scanner(System.in);
System.out.println("Please select on of the menuItems \n 1. Premium \n 2. Discount \n 3. Standard ");
FileWriter file = new FileWriter(f,true);
//Create an instance of the PrintWriter class using output as the argument
PrintWriter abc = new PrintWriter(file);
if(newMenu.nextInt()==1){
abc.println("Premium");
System.out.println("Enter Name of the item you want to add");
String name=newMenu.nextLine();
abc.println(m1.getNoOfItems()+1+" "+name);
System.out.println("Enter the price of item");
double price=newMenu.nextDouble();
abc.println(price);
m1.setNoOfItems(m1.getNoOfItems()+1);
}
Instead of :
if(newMenu.nextInt() == 1){
You can use newMenu.nextLine() instead like this :
if (Integer.parseInt(newMenu.nextLine()) == 1) {
While it should take the name before it take the double as input.
You don't get this scenario because you don't consume the all the line.
You need to consume the \n after .nextInt() Do
if(newMenu.nextInt()==1){
newMenu.nextLine();
//..rest of code
I'm looking for a way to basically give back to the user some console output that looks identical to what they type and then prompt again for more input. The problem is I have a method that modifies each String discovered that does not consist of white space.
At the end of each sentence given by the user, I am trying to figure out a way to get a newline to occur and then for the prompt to output to the console again saying "Please type in a sentence: ". Here is what I have so far...
System.out.print("Please type in a sentence: ");
while(in.hasNext()) {
strInput = in.next();
System.out.print(scramble(strInput) + " ");
if(strInput.equals("q")) {
System.out.println("Exiting program... ");
break;
}
}
Here is what is displaying as console output:
Please type in a sentence: Hello this is a test
Hello tihs is a tset
And the cursor stops on the same line as "tset" in the above example.
What I want to happen is:
Please type in a sentence: Hello this is a test
Hello tihs is a tset
Please type in a sentence:
With the cursor appearing on the same line as and directly after "sentence:"
Hopefully that helps clear up my question.
Try this, I didn't test it but it should do what you want. Comments in the code explain each line I added:
while (true) {
System.out.print("Please type in a sentence: ");
String input = in.nextLine(); //get the input
if (input.equals("quit")) {
System.out.println("Exiting program... ");
break;
}
String[] inputLineWords = input.split(" "); //split the string into an array of words
for (String word : inputLineWords) { //for each word
System.out.print(scramble(word) + " "); //print the scramble followed by a space
}
System.out.println(); //after printing the whole line, go to a new line
}
How about the following?
while (true) {
System.out.print("Please type in a sentence: ");
while (in.hasNext()) {
strInput = in.next();
if (strInput.equals("q")) {
System.out.println("Exiting program... ");
break;
}
System.out.println(scramble(strInput) + " ");
}
break;
}
The changes are:
You should be printing "Please type in a sentence: " inside a loop to have it print again.
I think you want to check if the strInput is "q" and exit BEFORE printing it, i.e. no need to print the "q", or is there?
Use println to print the scrambled strInput so that the next "Please type in a sentence: " appears in the next line, and the cursor appears on the same line as " ... sentence: " because that is output by System.out.print (no ln)
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.