Repeating a statement in while loop Java - java

Sorry for the newbish question, am quite new with Java.
So I want to display an error message when user input is outside of the bounds (Lesser than 0, greater than 100) which I've managed to do but I also want that the user can try again but my current code only continues with the execution of the program.
This is what I have now:
import java.util.Scanner;
public class storeQuota {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int quotas [] = new int [100];
int NumberOfWorkers = 100;
for (int i = 0; i<numberOfWorkers; i++) {
if (i == 0) {
System.out.print("Enter the quota for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the quota for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the quota for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the quota for the " + (i+1) + "th student: ");
}
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0)
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
//Printing all quotas.
System.out.println("Thank you for your input. Your entered quotas are: ");
for (int i=0; i<numberOfWorkers; i++)
{
System.out.print(quotas[i] + ", ");
}
input.close();
}
}
With this code, the error message is correctly displayed when a user inputs an int that isn't between 0 and 100 but the user will be unable to try again, the program continues to ask for the next quoata.

I think the problem is located in this line
break;
after
System.out.println("Error - Can only be between 0 and 100.");
which always breaks the while loop. Instead you only want to break the while loop if the input is in valid range. I would not use while(true) but some sort of conditional variable which is set to false in the while loop if the input is in valid range, also because while(true) is not a good programming practice from my point of view.

Your problem is using Break;
rather than using that, you should change the while(true) to while(false), you've also forgot to add curly brackets around the if statement.
boolean x = true;
while (x){
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0){
System.out.println("Error - Can only be between 0 and 100.");
x = false;
}
}
also I suggest learning exceptions as they would make this 10x easier.

When executed, "break" breaks the loop you are currently in. In your code, break is executed irrespective of what the input is resulting in the unwanted result.
Simplest solution would be (closest to your original code):
while(true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
} else {
break;
}
}
Here, the loop will break only if correct input is entered.

You haven't used curly braces in if condition.
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}

Related

I want to write a program that allows the user to guess a number between 0 and 100 in 7 attempts. I don't know why is this not working

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rnd = (int)(Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for (int count = 1; count <= 7; count++) {
while (num != rnd) {
if (num < rnd) {
System.out.println("Your guess is too low.");
}
if (num > rnd) {
System.out.println("Your guess is too high.");
}
if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2)) {
System.out.println("But your guess is VERY close.");
}
num = scan.nextInt();
}
System.out.println("You got it right!");
}
System.out.println("You should guess it in 7 tries.");
}
}
So I used two loops and just nested them. Is that how it works for this? Right now the code is like starting with for loop and if that is true it goes to the while loop part where the guessing number takes place. Can this be fixed with just moving some codes and fixing minor areas around?
What you should do in a situation like this is do the code manually. Literally. Grab a piece of paper and pretend you're a computer. It's a good exercise, and it will help you figure out your problem.
The problem is your inner loop. It loops until they guess correctly regardless of the number of attempts. Then you force them to do it 6 more times with the outer loop.
You really only need 1 loop. I would have a single loop like this:
int attempts = 0;
int num = 0;
do {
num = scan.nextInt();
... most of the if code from your inner loop but not another scan.nextInt
} while (++attempts < 7 && num != rnd);
// and here you look at num == rnd to see if success or failures
I think you should rebuild you code to make it more clear.
Split the title (with description of the task)
Split main loop where you read user input and check it with expected number
Split output of the final result, where you print the result.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int rnd = new Random().nextInt(101);
final int maxAttempts = 7;
System.out.println("The program is going to give a number that is between 0 and 100 (including them).");
System.out.println("You can guess it within maximum " + maxAttempts + " attempts by pressing Run.");
boolean success = false;
for (int attempt = 1; attempt <= maxAttempts && !success; attempt++) {
System.out.format("(%s of %s) Enter your number: ", attempt, maxAttempts);
int num = scan.nextInt();
if (num == rnd)
success = true;
else {
System.out.print("Your guess is too " + (num > rnd ? "high" : "low") + '.');
System.out.println(Math.abs(rnd - num) <= 2 ? " But it's VERY close." : "");
}
}
System.out.println(success ? "You got it right!" : "Bad luck this time. Buy.");
}
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int rnd = (int) (Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for(int count = 1; count <= 7; count++)
{
if (num < rnd)
{
System.out.println("Your guess is too low.");
}
else if (num > rnd)
{
System.out.println("Your guess is too high.");
}
else if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2))
{
System.out.println("But your guess is VERY close.");
}
else
System.out.println("You got it right!");
System.out.println("Enter Next number: ");
num = scan.nextInt();
}
}
}
It should work Fine.Basically Your reasoning wass wrong because You are putting a while loop inside a for loop. What you want to do is you want only 7 iteration.In those 7 iterations you are checking the conditions based on user Input.

Replacing an Element

I'm working on code that shows the simple operation of an array. I can't seem to make it work at the part of re-inserting a deleted element inside my created array. My goal is to put another element inside another deleted element (when I delete an element it becomes 0). My insert case just tells the duplicate input, it does not let me resume in the deleted element at a certain position.
case 2:
{
if (limit1 < 5 || limit1 > 20){
System.out.println("Error: Invalid Array Limit");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
else{
System.out.println("Enter the " + array.length + " numbers now.
Or enter -1 to exit");
int i = 0;
while(i < array.length){
array[i] = in.nextInt();
boolean dups = false;
if(array[i] != -1){
for(int k = 0; k < i; k++)
if(array[k] == array[i])
{
System.out.println("Error: Duplicate Element");
System.out.println("Please Enter Another Value");
dups = true;
break;
}
if(!dups){
i++;}
}
else{
array[i] = 0;
System.out.println("Exit Confirmed");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
System.out.println("You have entered the "+ limit1 + " numbers");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
Another problem is, if I input a sentinel value (-1), it just makes the current input position 0. I just wish to exit the case not put a 0 at the position
I see some problems with your code. Using switch statements without any break statements is not a good practice. You can easily refactor your method to use a while loop like this:
public void e() {
do {
m();
choice1 = in.nextInt();
cls();
if (choice1 > 0) {
processChoice(); // contains switch block for processing input
}
} while (choice1 > 0); // Loop will terminate when user presses 0
}
This should also exit your program whenever user presses 0.
I see a problem in your Insertion into array block. You seem to be assigning value received from input directly to array[i]. What's the point of checking if it's a duplicate value after assigning it to array[i]. I think you should do something like this:
while (i < array.length) {
int currentInput = in.nextInt();
boolean dups = false;
if (array[i] != -1) {
for (int k = 0; k < i; k++)
if (array[k] == currentInput) {
System.out.println("Error: Duplicate Element");
System.out.println("Please Enter Another Value");
dups = true;
break;
}
if (!dups) { // currentInput not a duplicate; assign to array[i]
array[i] = currentInput;
i++;
}
Regarding exiting on providing -1, You should probably remove this line array[i] = 0 in order to not assign 0 to array[i]:
if (array[i] != -1) {
// ...
} else {
System.out.println("Exit Confirmed");
System.out.println("Press Any Key To Continue...");
new Scanner(System.in).nextLine();
System.out.print('\u000C');
break;
}
Here are some errors I found in your code:
You go to newline in System.out.plintln("Enter the " + array.length + "...."); in the middle of the string, you should do something like that:
System.out.println("Enter the " + array.length + " numbers now." + "\nOr enter -1 to exit")
if the input is -1 you don't exit straight away but you do array[i]=0 (remember that array[i] now is array[-1])
then you don't break the loop after -1 is inputted
case shouldn't be enclosed in brackets and should always finish with break:
case 1:
//DO THINGS
//....
//...
break;
case 2:
//DO OTHER THINGS
//....
//...
break;
Here are some suggestions on how to improve it:
I don't remember very well Java, but I don't think you have to create a new Scanner every time
if I was you I would check if the input is -1 as the first thing (there are several ways to do that)
not using the brackets for the for is a bit confusing
you already break when a duplicate is found, so you don't need to check it again with if(!dups)
I hope this solves your problem.

This very simple guess game does not work

I try to make a very simple guess game and i wanted to add an exciting addition by doing an analysis of the guesswork from the user using switch function but I was surprised that it did not run that analysis
public static void main (String args[]){
Scanner reader = new Scanner(System.in).useLocale(Locale.ROOT);
int num = 8 , guess;
boolean positiveguess = true;
while (positiveguess) {
System.out.println("Enter your guess = ");
guess = reader.nextInt();
if (guess != num)
switch(guess)
{
case '1':
if (num-5 < guess && num + 5 >guess)
System.out.println("Your guess is almost close! \nTry again ");
break;
case '2':
if (num-10 < guess && num + 10 >guess)
System.out.println("You need to guess again ");
break;
}
else
positiveguess = false;
}
System.out.println("Great !");
Your switch is based on the user input and not the difference between given and exepcted value. First I suggest you to keep it simple with if/else structure like
public class Main {
public static void main (String args[]) {
Scanner reader = new Scanner(System.in).useLocale(Locale.ROOT);
int num = 8, guess;
boolean positiveguess = true;
while (positiveguess) {
System.out.println("Enter your guess = ");
guess = reader.nextInt();
if (guess != num) {
if (num - 5 < guess && num + 5 > guess) {
System.out.println("Your guess is almost close! \nTry again ");
} else if (num - 10 < guess && num + 10 > guess) {
System.out.println("You need to guess again ");
}
} else {
positiveguess = false;
}
}
System.out.println("Great !");
}
}
Then I suggest you to remove your positiveguess and do a while loop with your condition inside. And use Math.abs() to get the difference between the guess and the expected value.
public class Main {
public static void main (String args[]) {
Scanner reader = new Scanner(System.in).useLocale(Locale.ROOT);
int num = 8;
int guess = Integer.MIN_VALUE;
while (guess != num) {
System.out.println("Enter your guess = ");
guess = reader.nextInt();
int diff = Math.abs(num - guess);
if (diff != 0) {
if (diff < 5) {
System.out.println("Your guess is almost close! \nTry again ");
} else if (diff < 10) {
System.out.println("You need to guess again ");
} else {
System.out.println("You're way too far bro");
}
}
}
System.out.println("Great !");
}
}
You are using switch wrongly here. It seems you are looking for something like this:
switch (guess) {
// first case
case (num-5 < guess && num + 5 >guess):
System.out.println("Your guess is almost close! \nTry again ");
// second case
case (num-10 < guess && num + 10 >guess):
System.out.println("You need to guess again ");
}
But this is not valid syntax. In Java, a switch/case can only compare elements to other elements of the same type (or, in newer version, multiple elements, or a class), not perform complex conditional checks like if can.
Probably you then tried to "fix" it by combining case '1' and the if statements, but while legal, case '1' will only be the case if guess is '1' (i.e. 49), and only then will continue to check the if condition.
Instead, just drop the switch/case and use your if statements directly (don't forget the else):
if (num-5 < guess && num+5 > guess) {
System.out.println("Your guess is almost close! \nTry again ");
} else if (num-10 < guess && num+10 > guess) {
System.out.println("You need to guess again ");
}
Also, you could make those checks more readable by changing the order to (num-5 < guess && guess < num+5) or using Math.abs to find the absolute difference and use that in the condition.

How can I check that the next input is an integer while checking if it's > and < at the same time in Java?

There's two things I'm needing help with. Loop issue 1) I have to initialize this variable outside of the loop, which makes the loop fail if the user inputs a string. Is there a way around that? Basically, if I set N to anything then the do-while loop just immediately reads it after getting out of the
import java.util.Scanner;
/**
* Calculates sum between given number
*/
public class PrintSum {
public static void main(String[] args) {
int N = 0;
String word;
boolean okay;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number from 1-100: ");
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
} else {
okay = true;
}
} while (!okay);
loop(N, 0);
}
public static void loop(int P, int total) {
while (P >= 1) {
total = total + P;
P--;
}
System.out.println(total);
}
}
If not, then the issue becomes, how do I solve this? I thing that I need to be able to say
if (scan.hasNextInt() || ??? > 100 || ??? < 1) {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
} else {
okay = true;
}
What do I put in the ??? to make this work? I think I just don't know enough syntax.
Thank you!
Why don't you try this?
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
continue;
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
continue;
} else {
okay = true;
}
} while (!okay);
break is used to end the loop as soon as the user enters the invalid character(condition of the else clause), so the loop doesn't fail.
Looking at your edited question, continue is what you are looking for if you might want to allow the user to enter another value after entering the invalid value.
Use break or continue based on requirement. More on breaks and continue.
Your second approach can be solved as follows:
if (scan.hasNextInt()){
N = scan.nextInt();
if (N > 100 || N < 1) {
System.err.print("Invalid input. Try again. ");
}
//perform some operation with the input
}
else{
System.err.print("Invalid Input. Try again. ");
}

While loop in Java with Multiple conditions

Can someone help me figure out why the while statement isn't working? The loop does stop after i = 3 but won't stop if continueSurvey = 0. It runs but it won't quit the loop if I change continueSurvey to O. Even if I step into the processes and I can see that the variable is 0, the loop continues.
import java.util.Scanner;
public class SurveyConductor
{
public static void main(String[] args)
{
Survey a = new Survey();
a.display();
a.enterQuestions();
int continueSurvey = 1;
int i = 0;
while ((continueSurvey != 0) && (i < 3))
{
for (int row = a.getRespID(); row < 3; row++)
{
System.out.println("Respondent " + (row+1) + " Please tell us how you would rate our: ");
for (int col = 0; col < 3; col++)
{
Scanner input = new Scanner(System.in);
System.out.println(a.presentQuestion(col) + ": ");
System.out.println("Enter your response (1-Strongly Disagree, 2-Disagree, 3-Neutral, 4-Agree, 5-Strongly Agree): ");
int response = input.nextInt();
if ((response < 1) || (response >5))
{
while ((response < 1) || (response > 5))
{
System.out.println("Your response must be between 1 and 5. Please try again.");
System.out.println(a.presentQuestion(col) + ": ");
System.out.println("Enter your response (1-Strongly Disagree, 2-Disagree, 3-Neutral, 4-Agree, 5-Strongly Agree): ");
response = input.nextInt();
}
}
a.logResponse(row,col,response);
System.out.println();
}
a.displaySurveyResults();
System.out.println();
System.out.println("The top rated question is Question #" + a.topRatedQuestion() + ".");
System.out.println("The bottom rated question is Question #" + a.bottomRatedQuestion() + ".");
System.out.println();
Scanner input2 = new Scanner(System.in);
System.out.println("Are there any more repondents (0 - No, 1 - Yes): ");
continueSurvey = input2.nextInt();
a.generateRespondentID();
i++;
}
}
}
}
You need to add a break inside your for loop. IE,
if(continueSurvey == 0)
break;
This will exit the for loop and allow the while loop to exit.
The part where you ask if the user wants to continue is inside this for loop
for (int row = a.getRespID(); row < 3; row++)
not just your while loop. This means it will keep asking until the for loop is done, only quitting when it finally gets back around to the while loop condition.
Your condition in the while loop is:
((continueSurvey != 0) && (i < 3))
which means that the inner block of the while loop will be executed if and only if continuSurvey != 0 and i < 3 in the same time. You have inner loops which have different conditions. I would search for the problem in the inner loops using a debugger. If this answer is not enough for you, then please specify what would you want to achieve.
if you want to exit the loop if either continueSurvey is 0 OR i=3
you have to write the while loop like this:
while((continueSurvey != 0) || (i < 3)) {
...
}
the && (and) operator symbolises that both conditions have to be true in order for the loop to exit not one of them (|| or).

Categories