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);
}
Related
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 19 days ago.
I'm new to Java, just started a couple days ago. I have this program wich does some cool checks on an input number, but for semplicity i just created a class TestToFixLoopIssue because loop is actually the issue im facing. When we choose to enter a number, we enter the if with choice == 1, so the Test class is called, does its things, and when we quit that "program" we get an infinite loop in the console. This does not happen if i just copy paste the Test code into the if (removing its Scanner). So i think its a problem related to the multiple Scanners, but i dont know how to fix it.
EDIT: i tryed adding s.next(); but this does not fix the issue, it just gives another error in console wich stops the program:
Exception in thread "main" java.util.NoSuchElementException
public class Program {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("What do you want to do?");
System.out.println("1. Check a number");
System.out.println("2. What is this program about?");
System.out.println("3. Quit");
if (s.hasNextInt()) {
int choice = s.nextInt();
s.nextLine();
if (choice == 1) {
System.out.println(" ");
// NumberChecker nc1 = new NumberChecker();
// nc1.check();
TestToFixLoopIssue test1 = new TestToFixLoopIssue();
test1.check();
} else if (choice == 2) {
System.out.println(" ");
System.out.println("This program checks multiple properties of a number.");
} else if (choice == 3) {
exit = true;
System.out.println(" ");
System.out.println("Program closed!");
} else {
System.out.println(" ");
System.out.println("Invalid choice. Try again.");
}
} else {
System.out.println("Invalid input. Try again.");
}
}
s.close();
}
}
public class TestToFixLoopIssue {
public void check() {
Scanner scan = new Scanner(System.in);
boolean repeat = true;
while (repeat) {
System.out.print("Insert a number: ");
int number = scan.nextInt();
System.out.println(" ");
System.out.println("You inserted " + number);
System.out.println("Do you want to check another number?");
System.out.println("1. Yes");
System.out.println("2. No");
if (scan.nextInt() == 2) {
repeat = false;
}
}
scan.close();
}
}
I dont want the loop to generate, so the user can keep using the program. I tryed some methods of the Scanner but neither of them worked, i dont actually know whats the issue exacty, so... help!
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");
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
The expected output of the code is for a user to guess a randomly generated number between 0 to 100000, and for each guesses he pay $1.00, if the user guesses right he wins $1m, if not he is asked if he want a hint. each hint cost $2.00. so the code continues to run until the user quits the game or wins. the problem with my code is that after asking the user if he wants a hint or not the scanner input code doesn't run.
package com.company;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int guess, toguess;
String payOrQuit, yesOrNo;
double totalSpent = 0.0, hint, value;
boolean isWon = false, isQuit = false;
Random rand = new Random();
while (!isWon && !isQuit) {
toguess = rand.nextInt(1000000);
System.out.println("Want to win a million dollars?");
System.out.println("If so, guess the winning number (a number between 0 and 100000).");
System.out.print("Insert $1.00 and enter your number or 'q' to quit: ");
payOrQuit = input.nextLine();
if (payOrQuit.matches(".*\\d.*")) { // IF pays or quit
value = Double.parseDouble(payOrQuit);
System.out.println(toguess);
System.out.print("Guess a number: ");
guess = input.nextInt();
if (guess == toguess) { // IF 2 starts
System.out.println("YOU WIN!\nYou won $1000000!");
isWon = true;
} else {
totalSpent += value;
System.out.print("Sorry, good guess,Do you want me to give you a hint (y|n)?");
yesOrNo = input.nextLine();
if (yesOrNo.equals("y")) { // IF 3 starts
System.out.print("Insert $2.00 for the hint! : ");
hint = input.nextDouble();
totalSpent += hint;
if (guess > toguess) {
System.out.println("Guessed number too high");
} else {
System.out.println("Guessed number too low");
}
} else {
System.out.println("amount lost = " + totalSpent);
isQuit = true;
} // IF 3 ends
} // IF 2 ends
} else {
System.out.println("amount lost = " + totalSpent);
isQuit = true;
} // IF pays or quit ends//
}
}
}
The problem is because of input.nextInt() and input.nextDouble().
guess = input.nextInt();
Change it to
guess = Integer.parseInt(input.nextLine());
Similarly, also change
hint = input.nextDouble();
to
hint = Double.parseDouble(input.nextLine());
Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information.
This question already has answers here:
How do I make my program repeat according to certain circumstances?
(3 answers)
Closed 4 years ago.
Hello everyone i just started programming with java but i have kinda a problem question i am making a game where the user needs to put in a a number between 1 and 9 if the user puts a number under 1 or above 9 it gives an error and the user needs to put in a number again but when the user puts in a invalid number the program gives an error and stops working how can i fix this?
My code
public void game()
{
Scanner inputnumber = new Scanner(System.in);
System.out.println("Please select a number (1-9): ");
int number = inputnumber.nextInt();
if (number <1 || number > 9)
{
System.out.println("Please select a number: " + number);
System.out.println("This value is out of range. Please enter a value between 1 and 9.");
while (number <1 || number > 9)
{
return;
}
}
else{
System.out.println("That is a valid entry!");
}
}
}
This would also serve the purpose.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inputnumber = new Scanner(System.in);
int n;
do{
System.out.println("Please select a number (1-9): ");
n = inputnumber.nextInt();
} while ( n >= 1 && n <= 9);
}
}
you can use a do while loop for this.
todo Handle exceptions to support your use case.
One thing which you can try is to use try catch block.
For example :
public class ab {
int inputNumber;
public static void main(String[] args) {
// TODO Auto-generated method stub
takeInput();
}
public static void takeInput()
{
Scanner inputnumber = new Scanner(System.in);
System.out.println("Please select a number (1-9): ");
try {
int number = inputnumber.nextInt();
if (number >=1 && number <=9) {
System.out.println("Valid Number");
}
else
{
takeInput();
}
}
catch (Exception e) {
// TODO: handle exception
System.out.println("Invalid number");
takeInput();
}
}
}
What I really want my program to do is iterate once every time, but when I run code, the first time I try to follow the constraints, it asks me to enter a number between 1 and 7 twice, and after I I go through one trial, the code flows as desired.
//import libraries
import java.util.Scanner;
public class Milestone1 {
public static void main(String[] args) {
//define variables
Scanner scnr = new Scanner(System.in);
int patternDes = 0;
boolean world[][] = new boolean[Config.WORLD_ROWS][Config.WORLD_COLUMNS];
//print statements
System.out.println("Welcome to Conway's Game Of Life");
System.out.println("--------------------------------");
System.out.println("1)Glider 2)Beacon 3)Beehive 4)R-pentomino");
System.out.println("5)Random 6)Custom or 7)Exit");
System.out.print("Choose a pattern:");
//Have the scanner choose a pattern
patternDes = scnr.nextInt();
//check constraints
while(!(patternDes <= 7 && patternDes >= 1))
{
System.out.println("Enter a number between 1 and 7: ");
if(!scnr.hasNextInt()){
scnr.nextLine();
continue;
}
else{
patternDes = scnr.nextInt();
if((patternDes <= 7 && patternDes >= 1)){
break;
}
else{
continue;
}
}
}
//write another while loop now
}
}
This has also happened in many other codes, and it takes me forever to fix the particular method.
Is this what you want ?
Scanner scnr = new Scanner(System.in);
int patternDes;
do {
System.out.println("Enter a number between 1 and 7: ");
patternDes = scnr.nextInt();
}while (patternDes <= 7 && patternDes >= 1);