How to do, Do while loop for this code? - java

I have this java code:
public class Ages {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int value = 0;
String name;
int age;
System.out.print("Hey, what's your name? ");
name = keyboard.next();
System.out.println();
System.out.print("Ok, " + name + ", how old are you? ");
age = keyboard.nextInt();
System.out.println();
do{
if(age < 16){
System.out.println("You can't visit in the museum, " + name + ".");
if(age < 18);
System.out.println("You can't visit in the park, " + name + ".");
}
if (age < 25){
System.out.println("You can't visit if you have a car, " + name + ".");
}
if (age >= 25){
System.out.println("You can do anything, " +
name + ".");
}
while(age > 300);
System.out.println("It's not correct..Try Again, " + name +
".");
}
}
and I need that user write the wrong answer, he will get the question again "how old are you?", and after he get another tries..
what I goona do?
Thanks for the help!! :)

One the while block is not correct you have to use :
System.out.println("It's not correct..Try Again, " + name + ".");
do {
if (age < 16) {
System.out.println("You can't visit in the museum, " + name + ".");
if (age < 18);
System.out.println("You can't visit in the park, " + name + ".");
}
if (age < 25) {
System.out.println("You can't visit if you have a car, " + name + ".");
}
if (age >= 25) {
System.out.println("You can do anything, "
+ name + ".");
}
//while(age > 300);<<----------wrong position
System.out.println("It's not correct..Try Again, " + name + ".");
} while (age > 300);//<<----------correct position
Two
The while condition seams not correct, you have to check with min and max age, instead of just max, so you can use :
while (age < minAge || age > maxAge );
So if the age is less then the min OR great then the max repeat again
Three this if will not ever executed :
if (age < 18);//<<----------------note the ; it mean your if is end
System.out.println("You can't visit in the park, " + name + ".");
Four
Instead you can read the age inside your loop :
System.out.print("Hey, what's your name? ");
name = keyboard.next();
System.out.println();
do {
System.out.print("Ok, " + name + ", how old are you? ");
age = keyboard.nextInt();
System.out.println();
....
}while(..);
Hope this can gives you an idea about your problem.

1)You should use this condition : if (age >= 25 && age <= 300){ instead of
if (age >= 25){.
Otherwise the condition is true even if age is over 300 and you don't want to:
while(age > 300);
2)You should also allow the user to enter a new input if the value is not correct.
age = keyboard.nextInt(); should be in the loop.
3) You should allow the loop to finish.
In the while statement, you could specify the condition that requires a new input from the user :
while (age > 300)
This gives the code (not tested) :
int age;
do{
age = keyboard.nextInt();
if(age < 16){
System.out.println("You can't visit in the museum, " + name + ".");
}
else if(age < 18){
System.out.println("You can't visit in the park, " + name + ".");
}
else if (age < 25){
System.out.println("You can't visit if you have a car, " + name + ".");
}
if (age >= 25 && age <= 300){
System.out.println("You can do anything, " +
name + ".");
}
else{
System.out.println("It's not correct..Try Again, " + name + ".");
}
}
while (age > 300);

Try this, please:
public class Ages {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int value = 0;
int age;
System.out.print("Hey, what's your name? ");
String name = keyboard.next();
System.out.println();
while(true) {
System.out.print("Ok, " + name + ", how old are you? ");
age = keyboard.nextInt();
System.out.println();
if (age <= 300) {
break;
}
System.out.println("It's not correct..Try Again, " + name +
".");
}
if(age < 16) {
System.out.println("You can't visit in the museum, " + name + ".");
}
if(age < 18){
System.out.println("You can't visit in the park, " + name + ".");
}
if (age < 25){
System.out.println("You can't visit if you have a car, " + name + ".");
}
if (age >= 25){
System.out.println("You can do anything, " +
name + ".");
}
}
}

Related

Java while loop not terminating despite condition being false [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I want to create a game called Crap. The problem that I am facing is that the main while loop does not end despite the condition being set to false (by user inputing "no" when asked if they want to conitnue playing). What is the problem here? Comments are inserted where I think the problem is.
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (proceed != "no"){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
You are using the wrong operator. != checks if the two objects on left and right side are the the same (e.g. two variables reference the same object in memory).
You must write while (! "no".equals(proceed) ).
I did not write while (! proceed.equals("no") ) on purpose because if the string is null then you would get a NullPointerException.
I am not sure if Scanner.readLine() does ever return a null string, so it may make no difference here. But writing it in the "reverse" way as in my first example is more safely in general.
For a String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .
You have to use .equals(String) to compare Strings, like so:
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (!proceed.equals("no")){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}

How to end the while loop with either player1 or player2 entering "Q"?

I am stuck at a part where in a game, I use while loop and to end the loop and get the results of the game, I want either "player1" or "player2" to enter "Q", and so i tried doing it like this:
if (player1.equals("Q") || player2.equals("Q")){
go = false; //go is a boolean variable
}
This doesn't seem to work as I have to enter "Q" for both player1 and player2 for the game to end, but instead I just want either of them to enter "Q" and the game would stop.
Code:
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Soccer Game Between 2 Teams");
System.out.println("Win is 2 points" + "\n" + "Loss is worth 0 points" + "\n" + "Overtime is worth 1 point");
System.out.println("Type W, O, or L" + "\n" + "Type Q to end the game");
int pointsw = 0;
int pointsl = 0;
int pointso = 0;
int pointsw2 = 0;
int pointsl2 = 0;
int pointso2 = 0;
int totalpoints = 0;
int totalpoints2 = 0;
int counter = 0;
int counter2 = 0;
boolean go = true;
System.out.println("\n" + "Enter team one:");
String phrase = keyboard.next();
System.out.println("\n" + "Enter team two:");
String phrase2 = keyboard.next();
System.out.println();
while (go) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next();
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next();
if (team1.equals("W") || team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("O") || team1.equals("o")) {
pointso += 1;
} else if (team1.equals("L") || team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("W") || team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("O") || team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("L") || team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
if (team1.equals("Q") || team2.equals("Q")) {
go = false;
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
}
}
}
}
You should reorganize your code:
while (true) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next().toLowerCase();
if ("q".equals(team1)) {
break;
}
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next().toLowerCase();
if ("q".equals(team2)) {
break;
}
if (team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("o")) {
pointso += 1;
} else if (team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
} // loop completed
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
I'm not completely sure, but I think the issue is that after player 1 / player 2 says 'Q'
the scanner is still waiting for the next line to read.
String phrase = keyboard.next();
System.out.println("\n"+"Enter team two:");
String phrase2 = keyboard.next();//if player 1 types q this next() method must be resolved before it will continue to the logic
so add an if statement before play 2 goes asking if player 1 typed 'Q' , if so calculate scores and end game, if player 1 did not type 'Q' use else statement to continue on to player 2's turn

How do I initialize a variable in an if else program that combines three choices?

I'm writing a party planner program for a question for class.
I can't initialize my three choices of entertainment, decorations, and food.
Eclipse tells me that I should set all these values to 0. I have to stick to these if else statements because that's what we have learned so far.
Here is my code:
import java.util.Scanner;
public class PartyPlanner {
public static void main(String[] args) {
// TODO Auto-generated method stub
int entertainment;
int decorations;
int food;
int budget = entertainment + decorations + food;
Scanner keyboard = new Scanner(System.in);
System.out.println("For your choices, please type"
+ " in what is contained in the brackets."
+ " We will do the calculations for you.");
System.out.println("Choose entertainment:"
+ " [band] for $400 or " + "[DJ] for $150");
String choice1 = keyboard.nextLine();
if (choice1 == "DJ")
{
entertainment = 400;
}
else if (choice1 == "band")
{
entertainment = 150;
}
System.out.println("Where would you like to buy "
+ "decorations? [school] for $100 or [your own] for $250 ?");
String choice2 = keyboard.nextLine();
if (choice2 == "school")
{
decorations = 100;
}
else if (choice2 == "your own")
{
decorations = 250;
}
System.out.println("Would you like to purchase"
+ " [pizza] for $200 or [sub sandwiches]"
+ " for $250 or [appetizers] for $150?");
String choice3 = keyboard.nextLine();
if (choice3 == "pizza")
{
food = 200;
}
else if (choice3 == "sub sandwiches")
{
food = 250;
}
else if (choice3 == "appetizers")
{
food = 150;
}
System.out.println("You have chosen: " + choice1 +
" and " + choice2 + " and " + choice3);
System.out.println("The total cost of this party"
+ " comes out to:" + budget);
}
}
The problem is
The local variable entertainment, decorations, and food may have not been initalized.
First , you have to make the sum at the end of the code because at first the variables are not initialized yet , and secondly you can assign a value of zero if no choice have been made , like this :
public class PartyPlanner {
public static void main(String[] args) {
// TODO Auto-generated method stub
int entertainment;
int decorations;
int food;
Scanner keyboard = new Scanner(System.in);
System.out.println("For your choices, please type"
+ " in what is contained in the brackets."
+ " We will do the calculations for you.");
System.out.println("Choose entertainment:"
+ " [band] for $400 or " + "[DJ] for $150");
String choice1 = keyboard.nextLine();
if (choice1 == "DJ")
{
entertainment = 400;
}
else if (choice1 == "band")
{
entertainment = 150;
}
else { entertainment = 0; }
System.out.println("Where would you like to buy "
+ "decorations? [school] for $100 or [your own] for $250 ?");
String choice2 = keyboard.nextLine();
if (choice2 == "school")
{
decorations = 100;
}
else if (choice2 == "your own")
{
decorations = 250;
}
else { decorations = 0; }
System.out.println("Would you like to purchase"
+ " [pizza] for $200 or [sub sandwiches]"
+ " for $250 or [appetizers] for $150?");
String choice3 = keyboard.nextLine();
if (choice3 == "pizza")
{
food = 200;
}
else if (choice3 == "sub sandwiches")
{
food = 250;
}
else if (choice3 == "appetizers")
{
food = 150;
}
else { food = 0 ; }
int budget = entertainment + decorations + food;
System.out.println("You have chosen: " + choice1 +
" and " + choice2 + " and " + choice3);
System.out.println("The total cost of this party"
+ " comes out to:" + budget);
}
}

JAVA, How to restart my program from the start?

I am new to Java and I am doing some exercises, I created an if statement and else if so that when the user clicks 2 it will start the program from the start.
The problem is at the else if (yesNo == 2), I don't know what kind of code should I write there to start the program from the start. Can anybody help me? thank you.
if (option == 1) {
System.out.println("1: DAF");
System.out.println("2: Mercedes-benz");
model = in.nextInt();
if (model == 1) {
System.out.println("Model: " + mixer2.getModel());
System.out.println("Age: " + mixer2.getAge());
System.out.println("Cost: " + mixer2.getCost());
System.out.println("Capacity: " + mixer2.getCapacity() + " squares meters");
System.out.println("For how long do you want the vehicle to hire?, maximum is 12 months and every month cost 4000");
hireVehicle = in.nextInt();
cost = 4000 * hireVehicle;
System.out.println("The total cost is " + cost + " Do you want to proceed?");
System.out.println("1: yes");
System.out.println("2: no");
yesNo = in.nextInt();
if (yesNo == 1) {
System.out.println("Now, please enter your first name to complete the contract");
String name = in.next();
System.out.println("CUSTOMER CONTRACT");
System.out.println("Customer name: " + name);
System.out.println("Duration: " + hireVehicle + " months");
System.out.println("Date: " + date.date1());
}
else if (yesNo == 2){
}
You could use a loop like this one :
boolean repeat = True;
while (repeat)
{
if (yesNo ==1)
repeat = False;
else if (yesNo == 2)
repeat = True;
}
It might be easier with a do while loop, but i heard they're dirty

if statement never executed

Why doesn't this code enter into the if statement?
public class GradeCalculator {
public static void main(String[] args) {
/*
* A 900 - 1000(90% to 100%) B 800 - 899(80% to 89%)
* C 700 - 799(70% to 79%) D 600 - 699(60% to 69%)
* F 599 and below (Below 60%)
*/
String Name = JOptionPane.showInputDialog("Please enter your name: ");
String pointsEarned = JOptionPane.showInputDialog("Please enter the points earned: ");
String possiblePoints = JOptionPane.showInputDialog("Please enter the total points possible: ");
double pe = Double.parseDouble(pointsEarned);
double pp = Double.parseDouble(possiblePoints);
double grade = (pe/pp)*100;
char LetterGrade;
if(grade>=900){
LetterGrade = 'A';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you for an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
}
}
}
You have calculated percentage that will not be above 100.Therefore just change if condition to
if (grade>=90)
You can simply debug and see what happens there.Add else block and see value of grade.
if(grade>=900){
LetterGrade = 'A';
// ....
}else{
System.out.print(grade);
}
Your grade variable is a percentage and you are comparing it as if it were the score you calculated the percentage on. So it looks like what you want is just to use pe instead of the grade variable.
if(pe>=900){
then only calculate percentage when displaying
double percentage = (pe/pp)*100
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + percentage + "%" + " and you for an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
Either that or consider grade variable as percentage when testing it
if (grade>=90) //90%
Also
Variables should always start with a lowercase letter so LetterGrade should be letterGrade
That's how I solved it.
import javax.swing.JOptionPane;
public class GradeCalculator
{
public static void main(String[] args)
{
boolean exitLoop = false;
while(exitLoop == false)
{
String Name = JOptionPane.showInputDialog("Please enter your name: ");
String pointsEarned = JOptionPane.showInputDialog("Please enter the points earned: ");
String possiblePoints = JOptionPane.showInputDialog("Please enter the total points possible: ");
double pe = Double.parseDouble(pointsEarned);
double pp = Double.parseDouble(possiblePoints);
double grade = (pe*100)/pp;
double Lgrade = pe;
char LetterGrade;
if(Lgrade >= 900)
{
LetterGrade = 'A';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
} else if (Lgrade <899 && Lgrade >=800)
{
LetterGrade = 'B';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
} else if (Lgrade <799 && Lgrade >=700)
{
LetterGrade = 'C';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
} else if (Lgrade <699 && Lgrade >=600)
{
LetterGrade = 'D';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
} else if(Lgrade <599)
{
LetterGrade = 'F';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
}
int selectedOption = JOptionPane.showConfirmDialog(null, "Do you want to run the program again?", "Yes or No", JOptionPane.YES_NO_OPTION);
if(selectedOption == JOptionPane.YES_OPTION)
{
exitLoop = false;
}
else
{
exitLoop = true;
}
}
}
}

Categories