Why isn't this do while loop working properly? [duplicate] - java

This question already has answers here:
Java do-while loop isn't working
(3 answers)
Closed 7 years ago.
I working on a project for my course. The program runs fine until it hits my end program I've been messing with it for about 2 hours when I thought I was already finished.
This is the code it's messing up on.
do {
System.out.println("Do you want to end program? (Enter n or y):");
endProgram = Input.next();
if(!endProgram.equals("y") || (!endProgram.equals("n"))){
System.out.println("Do you want to end program? (Enter n or y):");
}
if (endProgram.equalsIgnoreCase("n")){
endProgram = "n";
aui = true;
}
if (endProgram.equalsIgnoreCase("y")){
endProgram = "y";
aui = true;
}
} while(aui = false);
I tried messing with the else if then switched to if. Full code is
public static String endProgram = null;
public static void main(String[] args) {
String MUR = "--------------Monthly Use Report--------------";
int minutesAllowed;
int minutesUsed = 0;
int minutesOver;
double totalOwed;
double monthlyRate = 74.99;
double minOver = 0.20;
double realOwed;
boolean valid = false;
boolean over = false;
boolean aui = false;
Scanner Input = new Scanner(System.in);
System.out.println("Welcome to the Cell Phone Minutes Calculator.");
do {
do {
System.out.println("Please input the amount of minutes you were allowed to use per month.");
System.out.println("Please Enter a value between (200 - 800)");
minutesAllowed = Input.nextInt();
} while (minutesAllowed <= 199 || minutesAllowed >= 801);{
}
do{
try{
System.out.println("How many minutes were used during the previous month?");
minutesUsed = Input.nextInt();
if(minutesUsed <= 1){
System.out.println("--Invalid Input! Please use a positive number.--");
} else {
valid = true;
}
} catch(Exception e){
System.out.println("Invalid Input! Please try again.");
Input.next();
}
}while(!valid);
minutesOver = minutesAllowed - minutesUsed;
if(minutesAllowed >= minutesUsed){
System.out.println("You were not over your minutes for the month!");
} else {
System.out.println("You were over your minutes by "+ Math.abs(minutesOver));
over = true;
}
totalOwed = (Math.abs(minutesOver))*(minOver);
realOwed = totalOwed+monthlyRate;
System.out.println(MUR);
System.out.println("Minutes allowed were "+ minutesAllowed);
System.out.println("Minutes used were "+ minutesUsed);
if(over){
System.out.println("Minutes over were "+ Math.abs(minutesOver));
System.out.println("Total due is $"+ realOwed);
} else {
System.out.println("Total due is $"+ monthlyRate);
}
do {
System.out.println("Do you want to end program? (Enter n or y):");
endProgram = Input.next();
if(!endProgram.equals("y") || (!endProgram.equals("n"))){
System.out.println("Do you want to end program? (Enter n or y):");
}
if (endProgram.equalsIgnoreCase("n")){
endProgram = "n";
aui = true;
}
if (endProgram.equalsIgnoreCase("y")){
endProgram = "y";
aui = true;
}
} while(aui = false);
}while((endProgram.equalsIgnoreCase("n")) && (aui = false));
}
}
Sorry if the code is sloppy. When I run the Program it runs properly unless I put two improper user inputs. such as,
Program running//
--------------Monthly Use Report--------------
Minutes allowed were 450
Minutes used were 500
Minutes over were 50
Total due is $84.99
Do you want to end program? (Enter n or y):
g
Do you want to end program? (Enter n or y):
If I add Input.Next(); to nest if statement to
if(!endProgram.equals("y") || (!endProgram.equals("n"))){
System.out.println("Do you want to end program? (Enter n or y):");
endProgram = Input.next();
it displays it correctly. I tried messing with the massive do while loop that goes across the whole project. If anybody can help me it will be much appreciated. Sorry if this is confused I'll respond if you guys have any questions. Thanks in advance for any response and sorry for the inconveniences.

Replace
while (aui = false); //here you are assigning aui to false value
to
while (aui == false); //here you are comparing aui to false value
= is as assignment operator, == is comparison operator.
The best practise is to use boolean directly, not by comparing:
while (!aui);

Related

i want to display every number entered in my while loop.so how can i do this

must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}

Unable to access scanner on nested if condition [duplicate]

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.

Can't make String equal method and Converting Strings to Numbers work together.

It is a Java beginner question. The program is not complicated, it just asks the user input grade and then finish it when the user input "y" , and then calculate max, min,average, and total.
My trouble is that I can't stop the loop when I type y. Thank you so much, if anyone can help me out. I have tried many approaches to figure that.
do
{
System.out.println("please go on");
input = keyboard.next();
grade = Integer.parseInt(input);
InputTimes++;
if (grade>Maxgrade)
{
Maxgrade = grade;
}
if(Mingrade>grade)
{
Mingrade= grade;
}
if (input.equals("y"))
{
GameOver = true;
System.out.println("yyyyyyy");
break;
}
else
{
GameOver = false;
System.out.println("nnnnnn");
}
totalgradeNoF = grade+totalgradeNoF;
}while(GameOver==false);
Scanner keyboard = new Scanner(System.in);
int Maxgrade = 0, Mingrade = 0, InputTimes = 0, grade = 0, totalgradeNoF = 0;
boolean GameOver = false;
String input = "";
do {
System.out.println("Please go on : ('y' to stop)");
input = keyboard.nextLine();
if (input.equals("y")) {
GameOver = true;
} else {
grade = Integer.parseInt(input);
InputTimes++;
if (grade > Maxgrade) {
Maxgrade = grade;
}
if (Mingrade > grade) {
Mingrade = grade;
}
totalgradeNoF = grade + totalgradeNoF;
}
} while (!GameOver);
Some things to change :
You need to check the "y" BEFORE and if it is not a "y" so you can cast to int
You don"t need to use breakso
You may use !GameoOver instead of GameOver==false
Don't need to set Gameover=false at each iteration, just at the initialisation
When you enter 'y' NumberFormatException is coming, so you need to handle this exception and then you can exit from the loop after typing 'y'.
Use for Scanner methods nextInt() and nextLine() for reading input.
EX:-
Scanner scan = new Scanner(System.in);
then we can use scan.nextInt() for get int
and we can use scan.nextLine() for get Strings
https://www.tutorialspoint.com/java/util/scanner_next.htm
this link may be help for you.
sorry for my english.

Using java scanner to check two conditions while taking user input

I need to user to enter an int between 1 and 301.
I have this simple loop here to check for user input.
I just want a single number from the user, and if the user enters anything other than an int between 1 and 301, I want to display the print line and prompt the users to try again until they enter a valid input.
while (!sc.hasNextInt()) {
System.out.print("Invalid Input. Please enter a valid number between 1 and 301: ");
sc.next();
}
int numToCheck = sc.nextInt();
// do stuff with numToCheck
This checks that the input is an int, but I can't seem to find a way to give the int input a bound. I tried to assign the user input to a variable and then check the conditions input < 1 or input > 301, but I get InputMismatchException if user enters a letter. How should I store the user input? (I want to store it as an int to check the conditions, but can't do that since I don't know what the user will enter).
Perhaps there is a better design to accomplish all this. Those are welcomed too.
Thanks in advance.
You're not saving the value of the of the input. So your program is waiting on the user to enter a number each time it see "sc.nextInt()" Assign the input to a variable, and then check the condition.
EDIT: okay, I'll go the extra mile for you. See if this works.
***Accounted for the case where the user might enter a character instead of a number.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int input;
while (true){
if (sc.hasNextInt()){
input = sc.nextInt(); // Assign the next integer to a variable
if (input <= 301 && input >= 1){ // Check if integer meets condition
break; // Condition met, break out of loop
}
}else{
sc.next();
}
System.out.println("Invalid Input. Please enter a valid number between 1 and 301: ");
}
}
}
I ran this code, to see if it would show a better performance than yours.
Scanner sc = new Scanner(System.in);
boolean valid = true;
do {
if (!valid) {
System.out.print("Invalid Input. ");
}
System.out.print("Please enter a valid number between 1 and 301: ");
String input = sc.next();
try {
int value = Integer.parseInt(input);
valid = (value >= 1 && value <= 301);
} catch (NumberFormatException nfex) {
valid = false;
}
} while (!valid);
When the conversion to integer fails, the JVM hangs a little. I believe your problem has more to do with the try / catch mecanism that Scanner performs under the hood, than with design.
Assuming you want only 1 input from the user, try following simple code, which takes input from the user until user enters a valid input.
Scanner in = new Scanner(System.in);
int flag = 0,x=0;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
flag = 1;
}
}
And if you want user to input more than 1 inputs (i.e 3 here), than set a counter that increases with every valid input of the user, as following:
Scanner in = new Scanner(System.in);
int flag = 0,x=0,count = 1;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
//executes when input is valid
if(count == 3){
flag = 1;
}
count++;
}
}
Edit:
If you also want to check whether the input is Integer or not, than you have to add one extra condition in above code. And as you said you want only one input from user rather than 3, you have to change exit condition. Change code as following:
Scanner in = new Scanner(System.in);
int flag = 0,count = 1,x=0,flag1 = 0;
String y;
while(flag == 0){
y = in.next();
flag1 = 0;
try{
x = Integer.parseInt(y);
}
catch(NumberFormatException e){
flag1 = 1;
System.out.println("Invalid Input.");
}
if((x<1 || x>301)&&flag1 == 0){
flag = 0;
System.out.println("Invalid Input.");
}
else if(flag1 == 0){
//executes when input is valid
if(count == 1){ // put count == 3 if you want 3 inputs from user.
flag = 1;
}
count++;
}
}
Here we are taking the input as a String and than converting the String into the Integer by using Integer.parseInt(). If the String is not Integer, than it will throw the exception and we will continue the loop till the valid input is entered by the user.
Use DO WHILE for result
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
OK ?

How to exit the program with a letter

I am attempting to create a program thtat does some processing and exits when a given letter is typed.
//1.00usd = .727751euro
int reset = 0;
while(reset == 0)
{
double euro;
double ems;
String input = JOptionPane.showInputDialog(null,"Enter Amount of US Dollar: ");
ems = Double.parseDouble(input);
if (ems < 0)
{
JOptionPane.showMessageDialog(null, "Please enter a real amount of money");
reset = 0;
}
if (ems >= 0)
{
euro = .727751;
ems = ems*euro;
ems = ems*100;
ems = Math.round(ems);
ems = ems/100;
JOptionPane.showMessageDialog(null,"Amount in euros: € " + ems);
}
}
This program is to convert usd to euro and I wanted to know how I can make the program exit when entering the letter "Q".
This is for a an object class so I'm still learning.
Something like
String input = JOptionPane.showInputDialog(null,"Enter Amount of US Dollar: ");
if( input.equals("Q") ) // but the case is important here
{
System.out.println("Bye bye");
System.exit(0);
}
ems = Double.parseDouble(input);
If your question is "how to exit the program", you can call
System.exit(0);
when the user presses a key.
If you just want to "quit" the loop you're in, manage to get the condition true, or use "break" (but you should not need it in your case).
Add this if statement in the while loop.
if(inputString.equalsIgnoreCase("q")) {
System.exit(0);
}

Categories

Resources