For some reason, my code will not accept input on the last line "What would you like to order: "
Could anyone tell me what my error is here? It is compiling correctly and everything. I am only a beginner so please tell me in basic terms.
import java.util.Scanner;
import java.util.*;
class RestaurantMain {
public static void main(String[] args)
{
//Create an array list
ArrayList menu = new ArrayList();
//Variables//
int choice;
int customerChoice;
boolean trueFalse;
int restart = 0;
String choice2;
String addItems = "";
int menuCount = 0;
int indexCount = 0;
String item = "";
//Import input device
Scanner in = new Scanner(System.in);
ArrayList theMenu = new ArrayList();
System.out.println("Welcome to the Cooper's restaurant system!");
System.out.println("How can I help?");
System.out.println("");
System.out.println("1. Customer System");
System.out.println("2. Management System");
System.out.println("");
System.out.println("");
System.out.print("Which option do you choose: ");
choice = in.nextInt();
if (choice == 1) {
System.out.println("Our menu's are as follows:");
System.out.println("");
System.out.println("1. Drinks");
System.out.println("2. Starters");
System.out.println("3. Mains");
System.out.println("4. Desserts");
System.out.println("");
System.out.println("Please note - You MUST order 5 items.");
System.out.println("");
System.out.print("What menu would you like to follow? ");
customerChoice = in.nextInt();
if (customerChoice == 1) {
System.out.println("Drinks Menu");
System.out.println("Would you like to order? ");
choice2 = in.nextLine();
if (choice2 == "yes") {
System.out.println("Please enter the amount of items you want to order: ");
while (indexCount <= menuCount);
System.out.println("Please enter your item: ");
item = in.nextLine(); {
theMenu.add(item);
}
}
}
if (customerChoice == 2) {
System.out.println("Starters Menu");
}
if (customerChoice == 3) {
System.out.println("Mains menu");
}
if (customerChoice == 4) {
System.out.println("Desserts Menu");
}
You need to call in.nextLine() right after the line where you call in.nextInt()
The reason is that just asking for the next integer doesn't consume the entire line from the input, and so you need skip ahead to the next new-line character in the input by calling in.nextLine()
customerChoice = in.nextInt();
in.nextLine();
This pretty much has to be done each time you need to get a new line after calling a method that doesn't consume the entire line. Consider using a BufferedReader object instead!
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int integer = Integer.parseInt(reader.readLine());
This will throw the same errors that Scanner.nextInt() does if the input can't be parsed as an integer.
Regarding your comment about errors, there is one:
while (indexCount <= menuCount);
System.out.println("Please enter your item: ");
item = in.nextLine(); {
theMenu.add(item);
}
}
Should instead be like the following:
while(indexCount <= menuCount){
System.out.println("Please enter your item: ");
item = in.nextLine();
theMenu.add(item);
}
Also, it isn't strictly necessary, but I suggest that you do declare the ArrayList's generic type when instantiating the list, so that further calls to theMenu.get() don't need to be casted to a String.
ArrayList<String> theMenu = new ArrayList<String>();
When comparing strings, ensure that you use the str.equals("string to compare with") method, instead of the equality operator (==). Therefore for example, choice2 == "yes" should instead be choice2.equals("yes"). Using equalsIgnoreCase instead of equals would ignore case differences, which may be useful in this situation.
insted of in.nextLine(); function you just try another scanner functions like 'in.next()'. just R&D with the methods that already give the JVM itself.
you just use correct the logic and use equal() or equlIgnoreCase() methods insted of "=" operator.
Related
I'm new to stackoverflow and wanted to know why my statement keeps on being repeated twice when i introduce an if statement in my while loop # "if done, type "back"". Secondly, can someone tell me why the ArrayList keeps an empty String at index 0 when i only add one item to the ArrayList? Thanks!
Here is the code:
package com.codewithrichard;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//global variables
boolean appIsStillOn = true;
ArrayList <String> shoppingList = new ArrayList<>();
System.out.println("Welcome to your mobile shopping list" + "\n" + "Your options are");
System.out.println("1) add item to list");
System.out.println("2) display list and amount of items in it");
System.out.println("3) quit!");
while (appIsStillOn) {
System.out.println("Option (1-4): ");
int option1 = input.nextInt();
if (option1 == 1) {
while (true) {
System.out.println("item (if done, type \"back\"): ");
String itemAdded = input.nextLine().toLowerCase();
if (!itemAdded.equals("back")) {
shoppingList.add(itemAdded);
} else {
break;
}
}
}
else if (option1 ==2){
System.out.println(shoppingList);
System.out.println("size of shopping list: " + shoppingList.size());
}
else {
System.out.println("Can't wait for you to come back!");
appIsStillOn = false;
}
}
}
}
The Scanner#nextInt() method (and many other next...() methods) does not consume the newLine character from the Scanner buffer which is produced when the ENTER key is hit. The Scanner#nextLine() method will consume it if encountered after a Scanner#nextInt() method therefore giving the impression that the prompt for input was skipped over.
Also Consider this...
What is to happen if the User accidentally types in an alpha character instead of a menu choice digit? That's right, your application will crash due to a InputMismatchException.
You should always carry out some form of validation for User input and if that validation fails, allow the User to make a proper entry. This obviously promotes a more trouble free environment when using your application. Using your current model, here is an example of this:
java.util.Scanner input = new java.util.Scanner(System.in);
//global variables
boolean appIsStillOn = true;
ArrayList<String> shoppingList = new ArrayList<>();
System.out.println("Welcome to your mobile shopping list.");
while (appIsStillOn) {
int option1 = 0;
while (option1 < 1 || option1 > 3) {
System.out.println();
System.out.println("Your Shopping List options are:");
System.out.println(" 1) Add item to list.");
System.out.println(" 2) Display list and amount of items in it.");
System.out.println(" 3) Quit!");
System.out.print("Choice (1-3): --> ");
try{
option1 = input.nextInt();
if (option1 < 1 || option1 > 3) {
throw new java.util.InputMismatchException();
}
/* Consume the enter key hit (newline char) in case
a Scanner#nextLine() prompt is next so that it
doesn't get consumed by that method. */
input.nextLine();
}
catch (java.util.InputMismatchException ex) {
System.err.println("Invalid menu choice supplied! Try again...");
/* Consume the enter key hit (newline char) in case
a Scanner#nextLine() prompt is next so that it
doesn't get consumed by that method. It is also
required here in case an exception has bypassed
the above 'input.nextLine()' call.*/
input.nextLine(); // Consume the enter key hit (newline char)
}
}
if (option1 == 1) {
while (true) {
System.out.println();
System.out.println("Enter the item to add (when done, enter \"back\"): ");
System.out.print("Item: --> ");
String itemToAdd = input.nextLine();
if (itemToAdd.trim().equals("")) {
System.err.println("Invalid Item String! You must supply something!");
continue;
}
else if (itemToAdd.equalsIgnoreCase("back")) {
break;
}
shoppingList.add(itemToAdd);
}
}
else if (option1 == 2) {
System.out.println();
System.out.println(shoppingList);
System.out.println("Number of Items in shopping list: " + shoppingList.size());
}
else {
System.out.println();
System.out.println("Bye-Bye - Can't wait for you to come back!");
appIsStillOn = false;
}
}
After take input input.nextInt(), when you press enter input.nextLine().toLowerCase() takes the data of that line since input.nextInt() doesn't take \n(newline).
Read the newline to skip it after input.nextInt()
int option1 = input.nextInt();
input.nextLine();
Write a program called PasswordChecker that does the following:
1. prompts the user to enter a password
2. prompts the user to renter the password
3. checks to ensure that the two password entries are identical
4. (for the first three attempts) Repeats steps 1 through 3 until the password is correctly entered twice.
5. After the 3rd attempt, if the user doesn’t enter the password correctly, the program needs to display an informative message indicating user account is suspended.
My code:
import java.util.Scanner;
public class passwordChecker{
public static void main(String [] args){
String pw1;
String pw2;
int count=0;
Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
count++;
if(pw1.equals(pw2))
System.out.println("Correct");
else if(count>=3)
System.out.println("Account is suspended");
while(pw1==pw2||count>3);
}
}
You seem to be missing a closing brace (you open the do but don't close before while). Your first condition should be count < 3 and I think you want to loop while the two String(s) are not equal. Something like,
do {
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
count++;
if (pw1.equals(pw2)) {
System.out.println("Correct");
} else if (count >= 3) {
System.out.println("Account is suspended");
}
} while (count < 3 && !pw1.equals(pw2));
Edit
The reason you don't use == (or !=) for Object types is that it tests reference equality only. You want to test for value equality (these String(s) came from different lines, so they won't compare equal by reference).
Do it simply
public class PasswordChecker {
public static void main(String[] args) {
String pw1;
String pw2;
int count = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
while(true){
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
if (pw1.equals(pw2)) {
System.out.println("Correct");
break;
} else if(count == 3){
System.out.println("Account is suspended");
break;
}
count++;
}
}
}
My full code is pasted here. Below are the 2 methods that are related to my question.
private static boolean playGameAgain()
{
char playAgain = 'y';
Scanner input = new Scanner(System.in);
while(playAgain != 'n')
{
System.out.println("Go again?(y/n)");
/// PROBLEM HERE.... Somehow, it will NOT wait for INPUT. It just throws an error
playAgain = input.next().charAt(0);
}
input.close();
return (playAgain != 'y')?false:true;
}
// [Trimmed]
public static void initialize(ArrayList<String> names, ArrayList<Integer> scores)
{
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 5; i++)
{
System.out.println("Enter the name for score #" + i + ":");
names.add(input.nextLine());
System.out.println();
System.out.println("Enter the score for score #" + i + ":");
while(!input.hasNextInt())
{
//input.nextLine();
System.out.println("Please input a valid integer value for the score for #" + i + ":");
if(!input.hasNextInt())
input.nextLine();
}
scores.add(input.nextInt());
input.nextLine();
}
input.close();
}
I have tried many combinations of how to read in one character. This used to work, that I could read in one character by using:
Scanner input = new Scanner(System.in);
char temp = input.next().charAt(0);
But, somehow, in this program I wrote, it won't work.
It's a program that will read in 5 user names (strings) & 5 scores (integers) and put them in 2 arrays. It will sort the arrays in descending order and then it will print them out. So, the only problem I have is asking if they want to play again and taking some char input to see if they want to play again (y/n)?
Please help if you can. I've tried many combinations of: if (input.hasNext()), to no avail.
You are not setting playAgain to something other than 'y' in playGameAgain(). You have a bug here.
import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
I'm trying to do as the picture shows here:
This is my code:
import java.util.Scanner;
public class IcsProject
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner (System.in);
int menuNum,ID,semNum,semCode,semCourses;
do{
System.out.println("Please Enter your Choice from the menu:");
System.out.println("1. Enter Student Sanscript");
System.out.println("2. Display Transcript Summary");
System.out.println("3. Read Student Franscript from a File");
System.out.println("4. Write Transcript Summary to a File");
System.out.println("5. Exit");
menuNum = keyboard.nextInt();
if (menuNum == 2 || menuNum == 3 || menuNum == 4)
System.out.println("Not working");
} while (menuNum > 1 && menuNum < 5);
//// Option 1: Enter student transcript
if (menuNum == 1)
System.out.println("Please enter your student's FIRST and LAST name:");
String stuName = keyboard.nextLine();
System.out.println("Please enter the ID number for " + stuName);
ID = keyboard.nextInt();
System.out.println("Please enter the number of semesters");
semNum = keyboard.nextInt();
for(int i=1 ; i < semNum ; i++)
{System.out.println("Please enter semester code for semester n# " + semNum);
semCode = keyboard.nextInt();
System.out.println("Please enter the number of courses taken in " + semCode );
semCourses = keyboard.nextInt();}
System.out.println("Enter course code, credit hours, and letter grade ")
///I stopped here
}
Do I have to use array starting from the semester code? show me an example please.
After entering all the values The program should show the Menu again so I can choose from it. How to do that?
I'm having a problem at the first question "entering the student first and last name"
The program just skip it and move to next question. Is there a mistake with my keyboard.nextLine();
I would use a list of objects which have all the fields you want to record.
For examples, just use google.
http://www.google.com/search?q=java+list+examples 27.9 million result
http://www.google.com/search?q=java+object+examples 18 million results.
http://www.google.com/search?q=java+array+examples 15 million results.
Regarding issue #2 - put the menu in a separate method. use a loop that it's condition is the menu or something similar to process according to the result from menu (this is abstract, I think you can figure it out from here):
while(doAnotherLoop)
{
switch(showMenu())
{
case 1:
...
case 2:
...
case 5: // Exit
doAnotherLoop = false;
}
}
Regarding issue #3. You read an int: menuNum = keyboard.nextInt(); but the line is not over, so the next nextLine (String stuName = keyboard.nextLine();) takes the rest of the line. use nextLine() and parse the integers instead.