What's the problem in this while statement? - java

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");
}

Related

How can I read a number in between 2 numbers?

I am fairly new to Java and I am trying to write a small program that asks a user to enter an integer between 0-4. I have written this so far and but it doesn't seem to work! Can anyone tell me where am I wrong?
import java.util.Scanner;
public class GameCharSelect {
public static void main(String[] argh){
int myChar;
Scanner in = new Scanner(System.in);
{
System.out.print("choose a player: ");
myChar = in.nextInt();
}while(myChar>0 && myChar<4);
System.out.println("--------");
System.out.println("you chose "+ myChar);
}
}
Now I want the number to be 1,2 or 3 or else it loop until the user input one of these but the program accept any number at the moment. Where am I wrong?
You are missing a do keyword in your loop. Also your conditional should be reversed:
public static void main(String[] argh) {
int myChar;
Scanner in = new Scanner(System.in);
do {
System.out.print("choose a player: ");
myChar = in.nextInt();
} while (myChar <= 0 || myChar >= 4);
System.out.println("--------");
System.out.println("you chose " + myChar);
}
Your while condition is wrong.
You are checking if the char is larger than 0 AND lower than 4, and if it is, it will do the loop again, while what you are after is the oposite.
Change the statement to check if myChar is smaller than 1 OR higher than 3.
myChar < 1 || myChar > 3
You are also missing a do at the beginning of the do-while.
You haf two problems in your code:
You are putting the while in a wrong way, you should put a do-while statement or put the while before the {...}.
You also want to run the loop when you put a wrong number (<1 or >3), not when you put the correct number(between 1 and 3)... So you also need to change the expression.
My code would be something like this:
import java.util.Scanner;
public class GameCharSelect {
public static void main(String[] argh){
int myChar;
Scanner in = new Scanner(System.in);
do{
System.out.print("choose a player: ");
myChar = in.nextInt();
} while(myChar<1 || myChar>3);
System.out.println("--------");
System.out.println("you chose "+ myChar);
}
}
Your loop should look like
while (true) {
System.out.print("Choose a player: ");
myChar = in.nextInt();
if (myChar > 0 && myChar < 4) {
break; // out of the loop
}
}
That is you only break; out of it if the scanned value is either 1, 2, or 3.
#Ali, while(true) approach is perfectly fine. In fact, it's far more common to see them than a do-while() in actual code running out there. The downvote received is subjective and based on individual coding style preference rather than an indication on the correctness of the answer.

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

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

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);
}

Java output error

I can't get this to work properly. It functions as it is supposed to, and does the math, but then it loops once, and ends. I need it to either loop until the users decides to end it, or only run once.
import java.util.Scanner;
public class java {
public static void main(String args[]) {
System.out.println("Welcome to the simple Calculator program");
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
Scanner input = new Scanner(System.in);
int math = input.nextInt();
if (math == 1) {
Scanner a = new Scanner(System.in);
int a1;
int a2;
int asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.print("The sum is: " + asum + "Thank You for using this program");
}
Scanner number = new Scanner(System.in);
int number1;
int number2;
int sum;
System.out.print("Enter first number: ");
number1 = number.nextInt();
System.out.print("Enter Second number: ");
number2 = number.nextInt();
sum = number1 + number2;
System.out.printf("Sum is %d\n", sum);
}
}
Use
do{
// do something.
} while(some condition);
And reapeat the same scanner to get input. You can also add one more option to your menu for repeating and evaluate that with while condition.
It is working as it should.
If you want it to loop as per some user input,you must use any looping construct like while.
Instead of if (math == 1) use
`while (math != exit)`
Make a new entry for exit like 0
Try using while loop. Give the user an option to quit the program.
import java.util.Scanner;
public class java
{
public static void main(String args[])
{
Scanner a = new Scanner(System.in);
System.out.println("Welcome to the simple Calculator program");
while(true)
{
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
System.out.println("6=Quit"); // added an option to quit the program
int math = a.nextInt();
if (math == 1)
{
int a1,a2,asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.println("The sum is: " + asum + "Thank You for using this program");
}
// Include actions for math = 2 to 5
if(math == 6)
{
System.out.println("Thank You for using this program");
System.exit(0);
}
}
}
}
The options are displayed again and again after each calculation until the user wants to exit the program by entering 6.
If you want the program to run only once, you should leave out the outer while loop. Everything else remains the same.
PS - You don't need to reopen Scanner again and again (at least not in this problem).
That is because you are only reading the input from the console once..you need to keep the console up with something like while(true) {} or monitor the console for an exit conditon like (" 0 = exit ") .
Also, I don''t think you will need to read two numbers again and again like you are doing right now.
1) You can use a do-while loop with a condition till which you wish to execute.
2) Use a switch case and perform the math operations inside the switch case with different operators. As of now you are trying to perform only addition. So you a switch case where you can perform all the operations.
3) In the switch case have an option which calls the exit(0) method. So that you can run the program until the user wish to exit.
4) By using a switch case you can make the user to choose his own option.
Your entire program is correct dude.
Just add
System.exit(0);
In every if(math==1) ,if(math==2)...before their statement ending.
like if(math==1)
{
...
System.exit(0);
}
You can fix your error...
Like me if your error is fixed. If not tell me the error

Java: Using scanner to read in boolean values failing.

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");
}
}

Categories

Resources