Java do-while loop executes only 2 runs [duplicate] - java

This question already has answers here:
Java: Infinite loop using Scanner in.hasNextInt()
(4 answers)
Closed 3 years ago.
I am trying to do a simple program where the user selects a number 1,2,3 for a simple calculation. The program will continue to run unless the user types in '0' when asked on the menu. The same menu will be presented to the user as long as they select 1, 2 or 3.If the user was to select 0, the program will terminate.
The code I have:
import java.util.Scanner;
public class QuadraticSolving {
public static void main(String[] args) {
// Declarations
int user;
double a;
double b;
double c;
int num1;
int num2;
Scanner in = new Scanner(System.in);// Create scanner in
do{
System.out.print("Press 0 to exit, 1 for Multiplication Solving, 2 for Sum or 3 for Print Message:");// main menu
user = in.nextInt();
}
while(user == 0);
{
if(user == 1)// multiplication solver
{
System.out.print("Enter a:");
a = in.nextDouble();
System.out.print("Enter b:");
b = in.nextDouble();
System.out.print("Enter c:");
c = in.nextDouble();
System.out.println(a*b*c);
}
else if(user == 2)// addition
{
System.out.print("Enter an integer:");
num1 = in.nextInt();
System.out.print("Enter another integer:");
num2 = in.nextInt();
System.out.println(num1 + num2);
// System.out.println(allSum(num1,num2));
System.out.print("");
}
else if (user == 3)// welcome statement
{
System.out.println("Welcome to IT");
}
else
{
System.out.println("Bye");
break;
}
System.out.print("Press 0 to exit, 1 for Multiplication Solving, 2 for Sum or 3 for Print Message:");
user = in.nextInt();
}
}
After the first run through the menu, it works perfectly. During the 2nd run, it always terminates the program, no matter what choice you pick.
Outcome example here
Whenever I enter '0' for all the runs it turns into an endless loop. The only way I can stop it is by ending the execution of the code.
Endless example here
I don't understand why the program only runs perfectly the first time and the 2nd run it terminates on its own. Also, I don't get why it goes into an endless loop when the user enters '0'. Any explanation as to why this happens? (Sorry for bothering, I am new to programming. Thanks)

It enters in a endless loop when the user types 0 because the while expression is checking if the typed number is equal to 0 and not different
And it is running ok on the first time because the code that runs after the while is not repeating, it only executes once, that code should be inside here
do {
.
. // Here you scan
. // Here you paste the logic
.
} while (user != 0);

Related

how to end a while loop with a certain variable

I am making an odd or even program with a while loop. I am trying to figure out how to end the while loop with a certain number. Right now I have 1 to continue the loop, and trying to make 2 the number that terminates it. Also trying to figure out how to terminate the program if a user types anything but a number like a letter/words.
package oddoreven;
import java.util.Scanner;
public class oddoreven {
public static void main (String[] args){
int num;
int x = 1;
while(x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}
}
}
You should try to use "a real termination condition" in order to terminate a while loop (or any loop for that matter); it's cleaner and should be easier to understand by everyone else.
In your case, I think it's better to have a do-while loop with some condition around this logic: num % 2 == 0, and an inner while loop for handling user input/validation.
If you still want to break loops abruptly, have a look here.
If you still need some help with the code, hit me up and I'll sketch up something.
I did not follow the conditions you wanted exactly because it does not make sense to have a continue condition AND a terminate condition unless there are other options.
What did you want the user to do if he entered 3, 4 or 5? Exit the code or continue the code? Well if the default is to exit, then you do not need the code to exit on 2 because it already will! If the default is to continue, then you do not need the continue on 1 and only the exit on 2. Thus it is pointless to do both in this case.
Here is the modified code to use a do while loop to ensure the loop is entered at least 1 time:
int x;
do {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
int num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to check another number, anything else to terminate.");
if (!s.hasNextInt()) {
break;
}
else {
x = s.nextInt();
}
} while(x == 1);
}
Note that I added a check to !s.hasNextInt() will check if the user enters anything other than an int, and will terminate without throwing an Exception in those cases by breaking from the loop (which is the same as terminating the program in this case).
If the x is a valid integer, then x is set to the value and then the loop condition checks if x is 1. If x is not 1 the loop terminates, if it is it will continue through the loop another time.
Another thing you can try is that instead of exiting the program you can just keep asking user to enter correct input and only proceed if they do so. I don't know what is your requirement but if you want to go by good code practice then you shouldn't terminate your program just because user entered wrong input. Imagine if you googled a word with typo and google just shuts off.
Anyways here is how I did it
import java.util.Scanner;
public class oddoreven {
public static void main(String[] args) {
int num;
int x = 1;
while (x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
boolean isInt = s.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
s.nextLine(); // Discarding the line with wrong input
System.out.print("Please Enter correct input: "); // Asking user again
isInt = s.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
num = s.nextInt(); // If it is int. It reads the input
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
// trying to figure out how to get the code to terminate if you put in a value
// that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}
}
}
To exit the program when the user enters anything other than a Number, change the variable x type to a String
if (!StringUtils.isNumeric(x)) {
System.exit(0);
}
To exit the program when user enters 2
if (x == 2) {
System.exit(0);
}

GPA calculator assistance

Hi I was wondering if I could get some help with a GPA calculator.
What it needs to do is:
The input will consist of a sequence of terms, e.g., semesters.
The input for each term will consist of grades and credits for courses taken within that term.
For each term, the user will type in an integer that represents the number of courses
taken within that term.
Each course is specified by a String letter grade and an int number of credits, in that order, separated by white space. 5. If the user types in -1 for the number of courses taken in a term, then the program must print a final overall summary and then terminate.
DO NOT prompt for any input. Thus, after you run your program in BlueJ, type Ctrl-T to force the Terminal window to pop up.
As always, follow the input / output format depicted in the Sample runs section.
Shown below is the error message I get and the code I have, thank you for any assistance in advance or tips I could try.
Terminal window and error message:
import java.util.Scanner;
/*
*
*
*/
public class Prog2 {
public static void main(String args[]) {
Scanner numberInput = new Scanner(System.in);
int numberofClasses = numberInput.nextInt();
Scanner input = new Scanner(System.in);
String [] grade = new String[5];
int [] credit = new int [5];
double totalCredit = 0.0;
double realGrade = 0.0;
double result = 0.0;
while (numberofClasses > 0)
{
for (int x = 0; x < numberofClasses; x++ )
{
grade[x] = input.next();
credit[x] = input.nextInt();
}
for(int x=0;x < numberofClasses; x++ ){
if(grade[x].equals("A+")){
realGrade=4.0;
}
else if(grade[x].equals("A")){
realGrade=4.0;
}
else if(grade[x].equals("A-")){
realGrade=3.67;
}
else if(grade[x].equals("B+")){
realGrade=3.33;
}
else if(grade[x].equals("B")){
realGrade=3.00;
}
else if(grade[x].equals("B-")){
realGrade=2.67;
}
else if(grade[x].equals("C+")){
realGrade=2.33;
}
else if(grade[x].equals("C")){
realGrade=2.00;
}
else if(grade[x].equals("C-")){
realGrade=1.33;
}
result = result+realGrade*credit[x];
totalCredit=totalCredit+credit[x];
}
System.out.println("Summary for term:");
System.out.println("----------------------------------");
System.out.println("Term total grade points: " + result);
System.out.println("Term total credits:" + totalCredit);
System.out.println("GPA:"+result/totalCredit);
}
// This block is getting used later please ignore
System.out.println("Final Summary:");
System.out.println("----------------------------------");
System.out.println(" Overall terms");
System.out.println(" Total grade points: " + result);// this needs to be all );
System.out.println(" Total credits" + totalCredit);//This needs to be all );
System.out.println("Cumulative GPA:"+result/totalCredit);
}
}
When your while loop ends, numberofClasses still contains the value that was entered before the while loop started the first time. Specifically, after you output the line:
GPA=3.0588...
you hit the end of the loop, then return to:
while (numberofClasses > 0)
which is true. The next "3" that you enter doesn't go into numberofClasses, it is picked up by
grade[x] = input.next();
Then the "A" is picked up by
credit[x] = input.nextInt();
which throws an exception since it's not an integer.
All you need to do is ask for the number of classes again at the end of the while loop:
System.out.println("GPA:"+result/totalCredit);
numberofClasses = numberInput.nextInt();
}
Output:
5
A 3
B 2
C 4
A 5
C 3
Summary for term:
----------------------------------
Term total grade points: 52.0
Term total credits:17.0
GPA:3.0588235294117645
3
A 3
B 5
C 1
Summary for term:
----------------------------------
Term total grade points: 81.0
Term total credits:26.0
GPA:3.1153846153846154
i recommend looking into whether your compiler or IDE has a "debug" feature. It is a very helpful tool, and lets you watch how your program goes through your code
Just a tip...
When you ask for input, print what you're asking for first. When I launched your program I had no idea what to do. Try adding System.out.println("input number of classes you took");before you prompt for that number.
Here is what is wrong. (If you printed what you're asking for first, this would be more apparent).
after your program displays the stats, you enter 5. Yet your program is actually still on this line grade[x] = input.next(); on line 22 i believe.
when you enter 5, your scanner is expecting a letter. and an exception is thrown.
you need to consider how you escape this loop here. while (numberofClasses > 0) perhaps use an if statement? otherwise your program loops for forever, never asking for a new class number

Adding message when certain condition is met (Java)

Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!

How do I make my program repeat according to certain circumstances?

import java.util.Scanner;
public class MyFirstGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double randomNumber = Math.random();
double realNumber = randomNumber*10;
double realerNumber = Math.round(realNumber);
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
}
So what I am trying to do is make a "game" for my Java class. I have generate a random number between 1 and 10 and the user has to input a number and if the input and the random number are the same, they "win." If they lose, they try again...? First, I did all the necessary scanner stuff that I don't even fully understand. I just copied the professor. So the program says to enter a number and the program generates a number between 0.0 and 1.0. I multiply that number by 10 to make it between 1 and 10. Then I round the number to the nearest integer. If the input matches this number, the program says you win. If not, it'll say try again.
The problem is how do I make the program repeat itself without the user having to reboot the program with the cmd? I need to repeat the input, random number generator, and then the result. What do I need to do? Also, how is my program? My second big one...yeah right...big. But seriously, how can I make it less complex or anything to improve it. Thanks.
Use a while loop:
long realerNumber = Math.round(realNumber);
// first guess
long guess = scanner.nextLong();
while (guess != realerNumber) {
System.out.println("Try Again...");
// guess again
guess = scanner.nextInt();
}
System.out.println("You Win!");
There is already a class to generate random numbers, you could use it:
// TODO: move to constant
int MAX = 10;
// nextInt(int n) generates a number in the range [0, n)
int randomNumber = new Random().nextInt(MAX + 1)
just put your code inside the do-while loop
Scanner scanner = new Scanner(System.in);
do
{
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double realerNumber = Math.round( Math.random() * 10 );
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
while(someCondition);
the someCondition can be for example a counter (if you want to play n times just set counter to n and decrease it every loop iteration then check if it is 0 in while) or some function checking if a key is pressed (like escape)
int n = 5;
do
{
n--;
...
}
while(n > 0);
This will run forever, but it's the idea mentioned in the first comment
...
Scanner scanner = new Scanner(System.in);
while(true){ // add this after Scanner ... declaration
...
} // end of existing else block
} // end of while loop, so add this single brace
...

Right Loop for this exercise in Java

Hi guys i am learning java in order to code in Android, i got some experience in PHP, so i got assigned an exercise but cant find the right loop for it, i tried else/if, while, still cant find it, this is the exercise:
1- prompt the user to enter number of students, it must be a number that can divide by 10 (number / 10) = 0
2- check of user input, if user input not dividable by 10 keep asking the user for input until he enter the right input
How i code it so far, the while loop not working any ideas how to improve it or make it work?
package whiledowhile;
import java.util.Scanner;
public class WhileDoWhile {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
/* int counter = 0;
int num;
while (counter <= 100) {
System.out.println("Enter number");
num = user_input.nextInt();
counter += num; // counter = counter + num
//counter ++ = counter =counter +1
}
System.out.println("Sum = "+ counter);
*/
int count = 0;
int num;
System.out.println("Please enter a number: ");
num = user_input.nextInt();
String ex;
do {
System.out.print("Wrong Number please enter again: " );
num++;
}
while(num/10 != 0 );
}
}
When using a while loop, you'll want to execute some code while a condition is true. This code needs to go inside the do or while block. For your example, a do-while loop seems more appropriate, since you want the code to execute at least one time. Also, you'll want to use the modulo operator, %, inside of your while condition, not /. See below:
Scanner s = new Scanner(System.in);
int userInput;
do {
// Do something
System.out.print("Enter a number: ");
userInput = s.nextInt();
} while(userInput % 10 != 0);
Two things:
I think you mean to use %, not /
You probably want to have your data entry inside of your while loop
while (num % 10 != 0) {
// request user input, update num
}
// do something with your divisible by 10 variable

Categories