I'm currently trying to create a little program which creates Recipes as csv files. That worked fine till the point where I want to add an Ingredient with spaces in between for example: 'real big bananas'. Whenever I write something like this or with underscores or with minus it enters null instead of the word I wrote.
I have a class Ingredients(double amount, String unit, String ingredient, String tags) with getter and setters for all of the variables.
My Code for creating a csv
public static ArrayList<Ingredients> createIngredientList() {
Scanner scan = new Scanner(System.in);
ArrayList<Ingredients> list = new ArrayList<Ingredients>();
char quit = 'Y';
String unit, ingredient, tags;
double amount;
while(quit == 'Y') {
System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
System.out.print("Amount: ");
amount = scan.nextDouble();
System.out.print("Unit: ");
unit = scan.next();
System.out.print("Ingredient: ");
ingredient = scan.nextLine();
System.out.print("Tags (e.g. tag;tag;tag): ");
tags = scan.nextLine();
list.add(new Ingredients(amount, unit, ingredient, tags));
System.out.print("More Ingredients? (Y/N) ");
String s = scan.next();
s = s.toUpperCase();
quit = s.charAt(0);
}
return list;
}
You can find the whole class in my pastebin below.
https://pastebin.com/vi09kGqi
while (quit == 'Y') {
System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
System.out.print("Amount: ");
amount = scan.nextDouble();
scan.nextLine() ;
System.out.print("Unit: ");
unit = scan.next();
scan.nextLine() ;
System.out.print("Ingredient: ");
ingredient = scan.findInLine("(\\s|\\S)*");
scan.nextLine() ;
System.out.print("Tags (e.g. tag;tag;tag): ");
tags = scan.next();
scan.nextLine() ;
list.add(new Ingredients(amount, unit, ingredient, tags));
System.out.print("More Ingredients? (Y/N) ");
String s = scan.next();
scan.nextLine() ;
s = s.toUpperCase();
quit = s.charAt(0);
}
This is due to a known problem with Scanner in java. Check the link here: Scanner is skipping nextLine() after using next() or nextFoo()?
You can use a blank scanner.nextLine() after every scanner.nextDouble() or scanner.next() to overcome this.
public static ArrayList<Ingredients> createIngredientList() {
Scanner scan = new Scanner(System.in);
ArrayList<Ingredients> list = new ArrayList<Ingredients>();
char quit = 'Y';
String unit, ingredient, tags;
double amount;
while(quit == 'Y') {
System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
System.out.print("Amount: ");
amount = scan.nextDouble();
scan.nextLine();
System.out.print("Unit: ");
unit = scan.next();
scan.nextLine();
System.out.print("Ingredient: ");
ingredient = scan.nextLine();
System.out.print("Tags (e.g. tag;tag;tag): ");
tags = scan.nextLine();
list.add(new Ingredients(amount, unit, ingredient, tags));
System.out.print("More Ingredients? (Y/N) ");
String s = scan.next();
s = s.toUpperCase();
quit = s.charAt(0);
}
return list;
}
Output:
Please use underscores instead of spaces e.g. real_big_boats.
Amount: 111
Unit: 111
Ingredient: a b c
Tags (e.g. tag;tag;tag): a b c
More Ingredients? (Y/N) N
Ingredients [amount=111.0, unit=111, ingredient=a b c, tags=a b c]
Another solution would be to accept every input as String by using scanner.nextLine() and then parsing it to the desired type.
Related
So im having trouble getting the first read input to read all inputs on the line. But for some reason it doesnt take into consideration of whitespaces. in fact, it considers the whitespace from the print information as part of the whitespace. only name has this problem. ID does not have this problem. I would just like to know how to fix this one problem since it is giving me the most trouble.
public class Project2 {
public static Scanner sc = new Scanner (System.in);
public static void main(String[] args) {
PersonList PersonList = new PersonList();
System.out.print("Welcome to my personal Management Program\n\n");
System.out.print("\nChoose one of the following options: \n\n");
//print out options for user
for (;;) {
int input = 0;
System.out.print("1- Enter the information of a faculty\n");
System.out.print("2- Enter the information of a student\n");
System.out.print("3- Print tuition person for a student\n");
System.out.print("4- Print faculty information\n");
System.out.print("5- Enter the information of a staff member\n");
System.out.print("6- Print the information of a staff member\n");
System.out.print("7-Exit the program\n\n");
System.out.print("\tEnter a selection: ");
input = sc.nextInt();
if (input == 1) {
faculty f = new faculty();
System.out.print("Enter the faculty info:\n");
System.out.print("\tName of Faculty: ");
f.name = sc.nextLine();
System.out.print("\tID: ");
f.ID = sc.nextLine();
String rank, department;
for(;;) {
System.out.print("\n\tRank: ");
rank = sc.nextLine();
if (rank.equalsIgnoreCase("professor") || rank.equalsIgnoreCase("adjunct")) {
f.rank = rank;
break;
}
else {
System.out.print("\"" + rank +"\" is invalid");
}
}
for(;;) {
System.out.print("\tDepartment: ");
department = sc.nextLine();
if (department.equalsIgnoreCase("mathematics") || department.equalsIgnoreCase("engineering") || department.equalsIgnoreCase("sciences")) {
f.Department = department;
break;
}
else {
System.out.print("\"" + department +"\" is invalid");
}
}
System.out.println("Faculty added!");
PersonList.addPerson(f);
}
When you read the selection input = sc.nextInt() it returns the next integer it finds, stopping right after that. It returns the choice typed but it does not read the newline. If you typed 1 (space one space) it would skip over the leading space then read the 1 and stop; it would not read the following space or the newline.
So when you get to the faculty name f.name = sc.nextLine() it reads whatever was remaining from the input = line, which is probably just a newline, and returns that for the name.
Now when you get to f.ID = sc.nextLine() the input buffer is clear so it reads ID as you expect it to.
A simple solution is to just finish reading the line by adding a nextLine() after reading the selection:
System.out.print("\tEnter a selection: ");
input = sc.nextInt();
sc.nextLine(); // Read the remainder of the line and throw it away
Read the javadoc for java.util.Scanner and for nextInt() and nextInt(radix)
Here is a basic while loop program, where the program at the end should ask the user if you want to keep going or not. The bug is that the program doesn't let me input (y/n) which is the last String Input.
This does not happen when the last input is an integer value.
import java.util.Scanner;
public class lol {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age;
String name = "";
String height = "";
String userOption = "";
while (!userOption.equals("n"))
{
System.out.println();
System.out.print("Enter your name: ");
name = sc.nextLine();
System.out.println();
System.out.print("Enter your age: ");
age = sc.nextInt();
System.out.println();
System.out.print("Enter your height: ");
height = sc.nextLine();
System.out.println();
System.out.println("Do you want to keep going? (y/n)");
// The program over looks this line of code
userOption = sc.nextLine();
if(userOption.equals("y"))
{
System.out.println("Breaking");
break;
}
else
{
continue;
}
}
}
}
See this topic, additional nextLine() call could be a workaround
Scanner is skipping nextLine() after using next() or nextFoo()?
Minor adjustments to the code will fix its behaviour ;)
Scanner sc = new Scanner(System.in);
int age;
String name = "";
String height = "";
String userOption = "";
while (true) {
System.out.print("Enter your name: ");
name = sc.nextLine();
System.out.println();
System.out.print("Enter your age: ");
age = sc.nextInt();
System.out.println();
System.out.print("Enter your height: ");
height = sc.nextLine();
System.out.println();
System.out.println("Do you want to keep going? (y/n)");
// The program over looks this line of code
userOption = sc.nextLine();
if (userOption.equals("y")) {
// nothing
System.out.println("Continuing");
} else {
System.out.println("Stopping");
break;
}
}
System.exit(0);
I would however agree that you should take a look at Scanner is skipping nextLine() after using next() or nextFoo()?
I've been reading validation for user input if it is not a number or if input isn't a character, but how do I check if the user input is something I defined for them?
System.out.println("What meal would you like to eat?"
+ " (appetizer, soup, salad, main, or dessert)");
String meal = console.next();
I saw
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
but compiler does not like when i change
(!sc.hasNext("[aeiou]"))
to
(!sc.hasNext("[appetizer, soup, salad, main, dessert]"))
Maybe you want to try it this way (you also can use enums instead of a HashSet):
System.out.println("What meal would you like to eat?"
+ " (appetizer, soup, salad, main, or dessert)");
HashSet<String> vowels = new HashSet<String>();
vowels.add("appetizer");
vowels.add("soup");
vowels.add("salad");
vowels.add("main");
vowels.add("dessert");
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (sc.hasNext()) {
String vowel = sc.next();
if (vowels.contains(vowel)) {
System.out.println("That's a vowel!");
} else {
System.out.println("That's not a vowel!");
}
}
You can do as follows. Check if the user's input is inside an array of permitted values.
List<String> meals = Arrays.asList(
new String[]{"appetizer", "soup", "salad","main","dessert"});
String meal = console.next().toLowercase();
if(meals.contains(meal)){
//Do what you want with correct input.
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 6 years ago.
In this snippet what I am doing taking three different types of variables and adding them and then printing then down.
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "HackerRank ";
Scanner scan = new Scanner(System.in);
int firstVariable = 0;
double secondVariable = 0.0;
String theString = "";
firstVariable = scan.nextInt();
secondVariable = scan.nextDouble();
theString = scan.nextLine();
System.out.println(firstVariable+i);
System.out.println(secondVariable+d);
System.out.println(s+""+theString);
}
I am providing input for firstVariable hitting enter and then providing the input for secondVariable and now as soon as I hit enter theString is capturing that value(I know it should capture it).
EDIT: in this case how should I provide the input to theString without as well as with space ?
I did try something like this,
while(scan.hasNext())
theString = scan.nextLine();
But it didn't work either.
Simply check scan.nextLine() is empty if so call scan.nextLine() again as next:
secondVariable = scan.nextDouble();
theString = scan.nextLine().trim();
if (theString.isEmpty()) {
theString = scan.nextLine();
}
Another approach with a pattern:
firstVariable = scan.nextInt();
secondVariable = scan.nextDouble();
theString = scan.next("\\w+");
There are two ways to solve your problem:
The first one is to use
nextLine()
each time you read from the user like this:
int firstVariable = scan.nextInt();
scan.nextLine();
double secondVariable = scan.nextDouble();
scan.nextLine();
String theString = scan.nextLine();
The second one is to parse the integer and double value from nextLine() like this:
int firstVariable = Integer.parseInt(scan.nextLine());
Double secondVariable = Double.parseDouble(scan.nextLine());
String theString = scan.nextLine();
You need to add an extra scan.nextLine(); before your String theString, to capture the Enter after the double. Like this:
firstVariable = scan.nextInt();
secondVariable = scan.nextDouble();
scan.nextLine();
theString = scan.nextLine();
Just as an advice to reduce your code, there's no need to add these:
int firstVariable = 0;
double secondVariable = 0.0;
String theString = "";
Just add the type to the variables to capture the scan:
int firstVariable = scan.nextInt();
double secondVariable = scan.nextDouble();
scan.nextLine();
String theString = scan.nextLine();
does anybody see wrong code here ?? i'd like to see do-while is working constantly as long as condition is not satisfied but it is certainly not. please tell me which part of code ruins my expected result?
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Item> cart = new ArrayList<Item>();
Item item;
String itemName;
double itemPrice;
int quantity;
String keepShopping;
double total = 0.0;
DecimalFormat m = new DecimalFormat("######,##");
do {
System.out.print ("Enter the name of the item: ");
itemName = scan.nextLine();
System.out.print ("Enter the unit price: ");
itemPrice = scan.nextDouble();
System.out.print ("Enter the quantity: ");
quantity = scan.nextInt();
item = new Item(itemName,itemPrice,quantity);
cart.add(item);
total +=itemPrice*quantity;
System.out.println ("Continue shopping (y/n)? ");
keepShopping = scan.nextLine();
} while (keepShopping.equals("y"));
for (int i = 0; i < cart.size(); i++) {
System.out.println(cart.get(i).toString());
System.out.println("Total price: " + m.format(total));
}
scan.close();
}
nextInt() does not consume any characters following the integer value, so the CR LF after it is still in the buffer and is read by the nextLine() call, meaning that keepShopping is always a blank string (or whatever was typed after the quantity value on the same line).
Your code is also calling nextDouble() and nextInt() without first calling the corresponding hasNextDouble() and hasNextInt() methods, so if you type something wrong, the program will crash and burn. Very common flaw in the use of Scanner.