While loop does not wait for if statement's completion [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am working on a school project for Intro to CS and I can't post my code because our teacher fails us for getting code checked from StackOverflow. My issue is that in my code with the format :
while (condition){
Do something;
if (new condition){
Do something else;
Wait for input;
Depending on input make while's condition false;
}
This code should wait for input when the if statement is evaluated and it does something else. However, my code does not wait for "Wait for input" step and goes directly to the "Do something" step. Here's a bit of the code. Thank you for your help.
while (inum != 102) {
System.out.println("Enter a number between 1 and 100: ");
inum = input.nextInt();
else if (inum == 101) {
System.out.println("Are you sure you want to quit?");
confirm = input.nextLine();
if (confirm == "yes") {
inum = 102;
}
}
Here the code gives me this when I type in 101:
Are you sure you want to quit?
Enter a number between 1 and 100:
*The code does not wait for
confirm = input.nextLine();
if (confirm == "yes") {
inum = 102;
}
step.

The easiest way to solve your problem is calling
input.nextLine();
just below
inum = input.nextInt();
The reason is: when you type "101" in the console, you really type 101 and NEWLINE. nextInt() takes the 101 from the console buffer, but the NEWLINE character remains. For that reason, the second nextLine() in your code was skipped (the code assumed you entered a new empty line)

You should use confirm.equals("yes").
input is already use to input the number and declare another scanner object to input the confirm String.

Define an other input Scanner and don't use the same for both String and int
Try this code (I put System.exist(0) so the program exit when you enter yes)
import java.util.Scanner;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
int inum = 0;
Scanner input = new Scanner(System.in);
Scanner input1 = new Scanner(System.in);
while (inum != 102) {
System.out.println("Enter a number between 1 and 100: ");
inum = input.nextInt();
if (inum == 101) {
System.out.println("Are you sure you want to quit?");
String confirm = input1.nextLine();
if (confirm.equalsIgnoreCase("yes")) {
inum = 102;
System.exit(0);
}
}
}
}

if( StringUtils.equals(confirm, "yes") ) { ...

Related

What's the problem in this while statement?

so I'm a beginner I just started like 3 days ago and I'm trying to make a While statement in java and I can't seem to find a way to make a loop without not having a user input again in the while block, My idea in this code is to ask the user for the wanted operation and if it's empty or non of the operations available, the program will give him an error message then loop the program
import java.util.*;
public class calc{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
int oper = sc.nextInt();
while (oper > 4 || oper < 1) {
System.out.println("Please enter a valid number");
System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
int oper = sc.nextInt();
}
}
}
The only thing really wrong is the second int oper = sc.nextInt();. You've already got a variable oper in scope, you can't declare another.
Remove the int.
You might instead want to consider restructuring the loop, so you don't have to repeat the messages and the reading from the scanner:
int oper;
while (true) {
System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
oper = sc.nextInt();
if (oper >= 1 && oper <= 4) {
break;
}
System.out.println("Please enter a valid number");
}

What is wrong with this java while loop?

New to Java and learning how to use While loops and random generator. This prints a multiplication question. Every time the user answers a question wrong, it should print the same question. Instead, it exits the program. What should I do?
while (true) {
Random multiply = new Random();
int num1 = multiply.nextInt(15);
int num2 = multiply.nextInt(15);
int output = num1 * num2;
System.out.println("What is the answer to " + num1 + " * " + num2);
Scanner input = new Scanner(System.in);
int answer = input.nextInt();
if (answer == output) {
if (answer != -1)
System.out.println("Very good!");
} else {
System.out.println("That is incorrect, please try again.");
}
}
If you want to repeat the same question when the user gets the answer wrong, you should use another while inside your main loop.
This inner loop continues to ask as long as you give a wrong answer.
I also replaced nextInt with nextLine, which reads in a whole line of text. This consumes the "Enter" key and is a safer approach at reading from the console. Since the result is now a String you need to use Integer.parseInt to convert it to an int. This throws an exception if you enter anything but a whole number so I wrapped it into a try-catch block.
If you want, you can add an additional check for validating user input. So in case the user wants to stop playing they only need to input "exit" and the whole outer loop will exit.
boolean running = true; // This flag tracks if the program should be running.
while (running) {
Random multiply = new Random();
int num1 = multiply.nextInt(15);
int num2 = multiply.nextInt(15);
int output = num1 * num2;
boolean isCorrect = false; // This flag tracks, if the answer is correct
while (!isCorrect) {
System.out.println("What is the answer to " + num1 + " * " + num2);
Scanner input = new Scanner(System.in);
try {
String userInput = input.nextLine(); // Better use nextLine to consume the "Enter" key.
// If the user wants to stop
if (userInput.equals("exit")) {
running = false; // Don't run program any more
break;
}
int answer = Integer.parseInt(userInput);
if (answer == output) {
if (answer != -1) {
System.out.println("Very good!");
isCorrect = true; // Set the flag to true, to break out of the inner loop
}
} else {
System.out.println("That is incorrect, please try again.");
}
}
catch(NumberFormatException e) {
System.out.println("Please enter only whole numbers");
}
}
}
Avoid while true. Declare a variable to true, pass the variable to the condiciĆ³n loop and set it to false when the answer is incorrect. You can use break too, but is easier to read the code when you use a exit condition in the while. Also read more about loops https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

Enter a string to integer scanner [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
I want to say enter an integer when someone trying to enter a string in this code.
Can you help me?
Here is my code:
import java.util.Scanner;
public class kl {
public static void main(String[] args) {
boolean primen = true;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a positive integer that is prime or not : ");
int ncheck = input.nextInt();
if (ncheck < 2) {
primen = false;
}
for (int i = 2; i < ncheck; i++) {
if (ncheck % i == 0) {
primen = false;
break;
}
}
if (primen == true) {
System.out.println(ncheck + " is a prime number.");
}
else {
System.out.println(ncheck + " is not a prime number.");
}
}
}
You can find your solution here: Exception handling, Or use codes below
Here is your complete code:
while(true){
System.out.print("Please enter a positive integer that is prime or not : ");
try{
int i = input.nextInt();
break;
}catch(InputMismatchException e){
System.out.print("Wrong type input, pls try again!");
input.nextLine(); \\ prevent infinite loop
}
You can see: I use a Exception handle processor to catch the InputMismatchException and print on console the message. You can replace InputMismatchException by Exception. It's largest Exception Handler class in java
There are two approaches you can use with Scanner.
Call nextInt() and then catch and handle the InputMismatchException that you will get if the next input token isn't an integer.
Call hasNextInt(). If that returns true then call nextInt().
In either case, if you expected an integer and the user entered something else, then neither nextInt() or hasNextInt() will "consume" the unexpected characters. So if you want the user to try try again, you need to call nextLine() which will read all remaining characters on the line. You will typically discard them.
For more information on handling exceptions:
https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
For more information on using Scanner:
https://docs.oracle.com/javase/tutorial/essential/io/scanning.html
http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Why is the confirmation statement printing to the console twice? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
Whenever I run the program, everything works fine but for some reason the Confirmation prints are happening twice and I can't figure out why. Any help would be appreciated.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String Z = "Z";
int number;
String Znumber = "";
String Confirmation = "";
int ExamType;
// Ask user for Z number
do {
System.out.println("Please enter your Z number. Example: 12345678");
number = input.nextInt();
Znumber = Z + number;
} while ((Znumber.length() != 9));
//Confirm Z number entry
do {
System.out.printf(
"Your Z number is: %s. Is this correct? Enter Y/N: \n",
Znumber);
Confirmation = input.nextLine();
} while (!Confirmation.equalsIgnoreCase("y"));
// Ask user which exam they would like to take
ExamType = 0;
Confirmation = "";
System.out.println("Which exam would you like to take? Select 1-3: ");
System.out.println("1: English");
System.out.println("2: Spanish");
System.out.println("3: Math");
ExamType = input.nextInt();
do {
System.out.printf("You selected %s. Are you sure? Enter Y/N: \n",
ExamType);
Confirmation = input.nextLine();
} while (!Confirmation.equalsIgnoreCase("y"));
// Begin exam
if (ExamType == 1) {
System.out.println("Welcome to the English exam!");
// Start code from JavaExam.java
} else if (ExamType == 2) {
System.out.println("Welcome to the Spanish exam!");
// Start code from MathExam.java
} else if (ExamType == 3) {
System.out.println("Welcome to the Math exam!");
// Start code from EnglishExam.java
Instead of Confirmation = input.nextLine();, use Confirmation = input.next(); and you should be good. Tested and confirmed.
You really don't need nextLine here in your do-while loop.
Your first loop (// Ask user for Z number)
number = input.nextInt();
does not read the last '\n'.
I think you need to add a nextLine() in that loop.
In your do-while when you run for the first time print Your Z number is: %s. Is this correct? Enter Y/N:. after that the condition !Confirmation.equalsIgnoreCase("y") is evaluated in this case gives true for this cause try to run the loop do-while in second time.
do {
System.out.printf("Your Z number is: %s. Is this correct? Enter Y/N: \n",
....
} while (!Confirmation.equalsIgnoreCase("y"));

How to reach a desired point in the code in java? [duplicate]

This question already has answers here:
How to repeat/loop/return to a class
(4 answers)
Closed 8 years ago.
I want to make a logic of getting grades. I proceed in a way of getting total marks as input from user using the Scanner class, then I'm validating marks if it is between 0 and 100(both inclusive).
Now if the marks are not in between this range, I print "Enter valid marks!!", and I want it to go to previous step and ask for the input from user again.
import java.util.Scanner;
class Performance
{
public static void main(String[] aa)
{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
}
// Now if this condition is true then I want the control to go again to line 7
// Please suggest me the way to Proceed
}
}
Please suggest the way to proceed with the modification in the above code.
See this link.
You want to do something like that:
do {
code line 1;
code line 2;
code line 3;
} while(yourCondition);
Now, if yourCondition is satisfied, the code will go to code line 1 again (will perform the code block between do and while).
Now, after you understand how it works, you can easily apply this to your task.
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
} else
break;
} while (true);
Try this:
boolean b = true;
while(b){
if(marks<0 || marks>100){
System.out.println("Enter valid marks!!");
marks= scnr.nextInt();
}
else{
b= false;
//Do something
}
}
8 int marks = scnr.nextInt();
9 while(marks<0 || marks>100)
10 {
11 System.out.println("Enter valid marks!!");
12 System.out.println("Enter the marks :");
13 marks = scnr.nextInt();
14 }
Thanks Guys for your help.
FInally i proceeded in the way as follows:
public static void main(String[] aaa)
{
int counter=0;
Scanner scnr = new Scanner(System.in);
int marks;
do
{
counter++;
System.out.println("Enter the marks :");
marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Marks entered are not valid");
if(counter>=3)
{
System.out.println("You have exceeded the maximum number of attempts!!");
System.exit(1);
}
else
System.out.println("Enter valid marks!!");
}
else
break;
} while(true);
}

Categories

Resources