Why is it only taking number as input? - java

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

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 display number without comma java

Scanner a = new Scanner(System.in);
String i = "11,111";
System.out.print("Enter first number a:");
String b = a.next();
I want to display number without comma when user provide
You can simply use String::replace
System.out.println (i.replace (",", ""));
Replace All will do the trick..
String i = "11,000";
System.out.println (i.replaceAll(",", ""));

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".

Error in Java app with scanner. Next() vs NextLine() and why Im getting an error?

Im having an issue with my Java application. The application is required to do the following:
(1) Prompt the user for a string that contains two strings separated by a comma. (1 pt)
Examples of strings that can be accepted:
Jill, Allen
Jill , Allen
Jill,Allen
Ex:
Enter input string: Jill, Allen
(2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings. (2 pts)
Ex:
Enter input string: Jill Allen
Error: No comma in string
Enter input string: Jill, Allen
(3) Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings. (2 pts)
Ex:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
(4) Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit. (2 pts)
Ex:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string: Washington,DC
First word: Washington
Second word: DC
Enter input string: q
My Code:
package parsestrings;
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter input string: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.next();
// Create new input string stream
inSS = new Scanner(lineString);
// Now process the line
firstWord = inSS.next();
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Exiting.");
inputDone = true;
if (firstWord.matches("[a-zA-Z]+,[a-zA-Z]+")) {
System.out.print("Input not two comma separated words");
}
} else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
return;
}
}
The error Im getting returned:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at parsestrings.ParseStrings.main(ParseStrings.java:53)
Java Result: 1
Scanner.next doc says:
Throws: NoSuchElementException - if no more tokens are available
Reason for your exception:
lineString = scnr.next(); // this is reading just one word (token)
//...
inSS = new Scanner(lineString); // this creates a new scanner with a string consisting in just one word
firstWord = inSS.next(); // this reads the word loaded in the inSS scanner
//...
secondWord = inSS.next(); // here is the problem. There are no more words left in this scanner (tokens) and throws the exception.
So It would work if you change this line:
lineString = scnr.next();
with this:
lineString = scnr.nextLine();
Scanner.nextLine will read the entire line as you are expecting. Anyway the user can input one word. So it would be nice to validate the input before proceding. You can do it like this:
lineString = scnr.nextLine();
if(lineString == null || lineString.length() == 0 || lineString.split("\\s+").length < 2){
System.out.println("2 words required. Try again:");
continue;
}
Here I'm using a regular expression to validate that there is more than one word in the input.

How to change cursor's place at java

I am doing a project with using arraylist. I want a alphabet and a number in order from user .
char karakter = klavye.next().charAt(0);
int sayi = klavye.nextInt();
When i write that after first input cursor pass to the bottom line
like:
A
7
But i want like that A 7 Why do not they side by side? How can i do this?
If I am understanding you correctly you just want the user to be able to enter two tokens on the same line. One approach is to just get the whole line and then split it into tokens.
Scanner klavye = new Scanner(System.in);
String tokens[] = klavye.nextLine().split(" ");
while(tokens.length < 2) {
System.out.println("Bad line, enter again:");
tokens = klavye.nextLine().split(" ");
}
char karakter = tokens[0].charAt(0);
System.out.println("karakter = " + karakter);
int sayi = Integer.valueOf(tokens[1]);
System.out.println("sayi = " + sayi);
The user should type A 7 then press the enter key only once at the end.

Categories

Resources