Java program exit function not working - java

i'm a newbie to java so i decided to create a simple program that prints out even numbers. I tried to make it exit a while loop if you answered no to the question but it just keeps on going.
Here's the code
public static void main(String[] args){
String continueYorN = "Y";
int i = 0;
while (continueYorN.equalsIgnoreCase("y")){
while(i >= 0){
i++;
if((i%2) == 0){
System.out.println(i);
continue;
}
System.out.println("Do you want to generate another even number?");
continueYorN = userInput.nextLine();
}
}
}

Your loop has no break condition (i.e, something that stop the loop in some condition), so it will continue forever.
You should replace the inner while with something like that:
while(i >= 0){
i++;
if((i%2) == 0){
System.out.println(i);
break;
}

Related

Repeating a statement in while loop 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;
}
}

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

Close after failed attempts

I am trying to have an input asking me to select a number 1-99, I want too have this system.close(0) after 2 failed attempts, if anyone could help me it would be appreciated.
package joey;
import java.util.Scanner;
public class Joey {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Please enter an number between 0-99: ");
int n = input.nextInt();
if ((n > 99) || (n < 1))
System.out.println("Invalid number");
else
break;
}
}
}
Use a counter for the failed attempts (code updated):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int failed = 0;
while (failed < 2) {
System.out.println("Please enter an number between 0-99: ");
int n = input.nextInt();
if ((n > 99) || (n < 1)) {
System.out.println("Invalid number");
failed += 1;
} else {
System.out.println("Correct! Closing now");
return;
}
}
System.out.println("Finished after two failed attempts");
}
}
See it working here
In order to have ''this'' system.close, you need just to finish running the program manually - aka exit the loop. So A. Check you number. B. Set a Boolean flag and make the while loop itirate on that flag. When it'll change state the loop will over and the computer will back to it's state.
You need to create a flag variable... something like:
int counter = 0;
Then change your while (true) { loop to:
do {
//Do whatever you want here
counter++; //Don't forget to increase the counter or you'll end up with an infinite loop
//If number is in range 1-99 then incorrect = false otherwise it becomes true
} while (counter < 2 && incorrect);
if (incorrect) {
System.out.println("Good bye! You failed!");
} else {
System.out.println("Good bye! You approved!");
}
There is no need for a System.exit(0); call
Or perhaps you could use a do-while loop but I'm leaving that up to you

Is the following flowchart correct for the given code?

I have designed a flowchart that is based on this code in Java.
public static void main(String args[]) throws IOException {
BufferedReader bw = new BufferedReader(new InputStreamReader(System.in));
attendance_and_student_management object = new attendance_and_student_management();
int flag = 1;
do {
{
int var = object.menu();
if (var == 1) {
System.out.println("\f");
object.add_student();
System.out.println();
} else if (var == 2) {
System.out.println("\f");
object.search_student();
System.out.println();
} else if (var == 3) {
System.out.println("\f");
object.change_student_information();
System.out.println();
} else if (var == 4) {
System.out.println("\f");
object.take_attendance();
System.out.println();
} else if (var == 5) {
System.out.println("\f");
object.attendance_summary();
System.out.println();
} else if (var == 6) {
System.out.println("\f");
object.monthly_defaulter_list();
System.out.println();
} else if (var == 7) {
System.out.println("\f");
System.out.println("THANK YOU FOR USING THE PROGRAM!!");
System.exit(0);
} else {
System.out.println("\f");
System.out.println();
System.out.println("Invalid Input. Would you like to try again? Press 1 for Yes");
int choice1 = Integer.parseInt(bw.readLine());
if (choice1 == 1) {
continue;
} else {
break;
}
}
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag = Integer.parseInt(bw.readLine());
if (flag != 1) {
System.out.println("Are you sure you want to exit? Press 1 for Yes");
int flag2 = Integer.parseInt(bw.readLine());
if (flag2 == 1)
flag = 0;
else
flag = 1;
}
}
}
while (flag == 1);
}
The flowchart is given below:
I am still learning how to construct flowcharts, therefore, I am not sure whether this diagram is correct. Any inputs or suggestions will be much appreciated.
PS: I tried to make the flow chart a bit simpler, please do tell if this is more appropriate than the previous one...
Your condition on the chart
Is var equal to 1,2,3,4,5,6 or 7?
ist not 100% right.
Your program works with if and else if conditions, which check each condition serial. You first check the 1, then the 2, then the 3 and so one...
Your chart shows this conditions as an All-In-One condition, what in java mean a switch).
So your chart should show these if's more like this:
Next, you dont need to draw the chart-boxes
Execute Method
In your code, you can draw just one box for the action in a true if-condition (like my added image).
And finally, you should have only one "Exit / End" point on the chart. Each flow that stopps the program, should link to this End-Point.

Termination of program using if else statement?

trying to terminate program using negative numbers and if else statement . does anyone see whats wrong with this thanks.
import java.util.Scanner;
public class Assignment {
public static void main(String args[]){
int n;
int i=0;
System.out.print("Enter a Number:");
Scanner scanner = new Scanner(System.in);
n= scanner.nextInt();
int backUp = n;
if(n>0)
n=n/10;
i++;
else if(backUp = -1)
System.out.print("program terminated......");
System.exit(0);
System.out.println("Number of Digits in " +backUp +" is " +i);
}
}
First of all, = is for assigning values. Use == for comparing.
Also, you need to use {} after if and else statements if you want to run more than one line.
else if(backUp = -1)
Should be
else if(backUp == -1)
= assignment operator , == is for comparing
And finally with missed {}
if (n > 0) {
n = n / 10;
i++;
} else if (backUp == -1) {
System.out.print("program terminated......");
System.exit(0);
}else{
// do something else. I have no idea.
}
You are missing { } for your if-statements. In if statements without the { }, only the line following the if-statement will be affected by the outcome of the if-test.
So:
if (condition)
doSomething();
doSomethingElse();
will execute doSomething() if condition == true and doSomethingElse() no matter if condition == true.
if (condition) {
doSomething();
doSomethingElse();
}
will execute both doSomething() and doSomethingElse(), if and only if condition == true.
You are using an assignment operator to evaluate a condition.
else if(backUp = -1)
should be
else if(backup == -1)
remove else use if(backup==-1).
First of all your indenting.
Secondly, if you want to execute multiple statements given a certain condition you'll need to put it in a code block like if(x) { /* do multiple things */ }.
Thirdly, your else if(backUp = -1) is invalid because you need a boolean expression inside a if, backUp = -1 is an assignment and thus does not evaluate to a boolean (you probably want backUp == -1).
And you probably want to loop the n = n/10; i++; part because now it will never count more than 1 digit.

Categories