Do While loop with Yes = start again No = exit Program - java

I have to add a do-while loop to my project so after the program iterates it says: "You want a run this program again? (Yes or No)"
If user inputs are Yes or YEs or YES or yEs or yES or yeS
It runs a program again.
If it's no, program should automatically exit.
import java.text.DecimalFormat;
import java.util.Scanner;
public class CalculatePay {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String Name = " ";
int hours;
double payRate;
char F;
char P;
char T;
String input = " ";
char repeat = input.charAt(0);
double grossPay;
int attempt = 0;
System.out.print("What is your name? ");
Name = reader.nextLine();
System.out.print("How many hours did you work? ");
hours = reader.nextInt();
while (hours < 0 || hours > 280)
{
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
if(attempt >= 2) {
System.out.println("You are Fired!");
return ;
}
}
System.out.print("What is your pay rate? ");
payRate = reader.nextDouble();
System.out.print("What type of employee are you? ");
F = reader.next().charAt(0);
grossPay = hours * payRate;
DecimalFormat decFor = new DecimalFormat("0.00");
switch (F)
{
case 'F' :
case 'f' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a full-time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'P' :
case'p' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a part- time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'T' :
case 't' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a temporary employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
default:
System.out.println(" unknown employee type");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
}
System.out.println("Do you want to run this program again? (Yes or No)");
}
}

I suggest yo to wrap your logic in another method, so you can call it later:
import java.text.DecimalFormat;
import java.util.Scanner;
public class CalculatePay {
private static void doStuff() {
Scanner reader = new Scanner(System.in);
String Name = " ";
int hours;
double payRate;
char F;
char P;
char T;
String input = " ";
char repeat = input.charAt(0);
double grossPay;
int attempt = 0;
System.out.print("What is your name? ");
Name = reader.nextLine();
System.out.print("How many hours did you work? ");
hours = reader.nextInt();
while (hours < 0 || hours > 280)
{
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
if(attempt >= 2) {
System.out.println("You are Fired!");
return ; }
}
System.out.print("What is your pay rate? ");
payRate = reader.nextDouble();
System.out.print("What type of employee are you? ");
F = reader.next().charAt(0);
grossPay = hours * payRate;
DecimalFormat decFor = new DecimalFormat("0.00");
switch (F)
{
case 'F' :
case 'f' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a full-time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'P' :
case'p' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a part- time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'T' :
case 't' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a temporary employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
default:
System.out.println(" unknown employee type");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
do {
//Call your bussines logic.
doStuff();
System.out.println("Do you want to run this program again? (Yes or No)");
}
while(reader.nextLine().toLowerCase().equals("yes"));
} }
Note that the function is static. This is because you can not call a non-static method from a static context (main is static).

Related

Addition in Java program equals different value

I'm having a problem with this Java code. It's a questionnaire that should calculate your grade. It all goes and runs well until the very last part where it says "current score" that whole equation should equal 33.16 but instead it equals 24.
I changed some values, did some research but I haven't found what I'm looking for.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
System.out.println("Grading Scale:");
System.out.println("A\t 90 - 100");
System.out.println("B\t 80 - 89");
System.out.println("C\t 70 - 79");
System.out.println("D\t 60 - 69");
System.out.println("F\t below 60");
System.out.println("What letter grade do you want to achieve for the course?");
String desiredGrade;
Scanner keyboard = new Scanner(System.in);
desiredGrade = keyboard.next();
if (desiredGrade.equalsIgnoreCase("A") || desiredGrade.equalsIgnoreCase("B")
|| desiredGrade.equalsIgnoreCase("C") || desiredGrade.equalsIgnoreCase("D")
|| desiredGrade.equalsIgnoreCase("F")) {// is this necessary? vv
System.out.println("Enter Percentage Weights");
}
else {
System.out.println("Input error.");
System.exit(0);
}
int exam1, exam2, finalExam, labs, projects, attendance, quizzes;
System.out.println("Exam 1:\t");
exam1 = keyboard.nextInt();
System.out.println("Exam 2:\t");
exam2 = keyboard.nextInt();
System.out.println("Final Exam:\t");
finalExam = keyboard.nextInt();
System.out.println("Labs:\t");
labs = keyboard.nextInt();
System.out.println("Projects:\t");
projects = keyboard.nextInt();
System.out.println("Attendance:\t");
attendance = keyboard.nextInt();
System.out.println("Quizzes:\t");
quizzes = keyboard.nextInt();
// so the semicolon isn't needed after the if statement?
if (exam1 + exam2 + finalExam + labs + projects + attendance + quizzes != 100) {
System.out.println("Weights don't add up to 100, program exiting");
System.exit(0);
}
System.out.println("Enter your scores out of a 100:");
System.out.println("Do you know your Exam 1 score?");
String answer;
int exam1score = 0, exam2score = 0, finalExamScore = 0, labAverage = 0, projectAverage = 0, quizAverage = 0, attendanceAverage = 0;
double currentScore = 0;
answer = keyboard.next();
// ask about this
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
// why can't i put int here?
System.out.println("Score received on exam 1:");
exam1score = keyboard.nextInt();
System.out.println("Do you know your Exam 2 score?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on exam 2:");
exam2score = keyboard.nextInt();
System.out.println("Do you know your Final Exam score?");
answer = keyboard.next();
}
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on final exam");
finalExamScore = keyboard.nextInt();
}
}
System.out.println("Do you know your lab average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Lab Grade:");
labAverage = keyboard.nextInt();
}
System.out.println("Do you know your project average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Project Grade:");
projectAverage = keyboard.nextInt();
}
System.out.println("Do you know your quiz average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Quiz Grade:");
quizAverage = keyboard.nextInt();
}
System.out.println("Do you know your attendance average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Attendance Grade:");
attendanceAverage = keyboard.nextInt();
}
currentScore = ((double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage)/((double)exam1+exam2+finalExam+labs+projects+attendance+quizzes);
System.out.println("Current Grade Score:\t " + currentScore);
String grade;
if (currentScore >= 90)
grade = "A";
else if (currentScore >= 80)
grade = "B";
else if (currentScore >= 70)
grade = "C";
else if (currentScore >= 60)
grade = "D";
else
grade = "F";
}
}
The following only converts the exam1score*exam1 value to double, not the entire expression.
(double) exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore + ....
So, you should do something like this.
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage;
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (double) nominator / denominator;
OR
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage);
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (nominator * 1.0) / denominator;
(double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage
only converts the first one to double and leaves the rest as int.

How do I state the }while(???) portion of the loop?

I need this code to loop for however many iterations someone decides to use, I do not understand what condition I would need to put into the {while**(??here??)**;
Also I understand that the loop should go around my input statements and tax computation, have I placed the do and the while in the right position?
EDIT* I've removed 2 of the cases from the code which are pretty much the same so I could post within the rules here.
import java.util.Scanner;
public class Assignment333 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter your first name:");
String name = input.next();
System.out.println("Enter your age in years:");
byte age = input.nextByte();
System.out.println("Enter your gender (F/M):");
char gender = input.next().charAt(0);
System.out.println("Enter your marital status (S/M/D/W):");
char marital_status = input.next().charAt(0);
System.out.println("Enter your taxable income for 2016:");
long income = input.nextLong();
String name_prefix;
double tax_amount;
if (gender == 'M') {
name_prefix = (age < 18) ? "Master." : "Mr.";
} else {
name_prefix = (marital_status == 'M') ? "Mrs." : "Ms.";
}
switch (marital_status) {
case 'M':
if (income < 8500) {
tax_amount = 0;
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe no tax for the fiscal year 2016");
} else {
if (income < 24000) {
tax_amount = income * 0.01;
} else {
tax_amount = income * 0.025;
}
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe a tax of $" + tax_amount + " for the fiscal year 2016");
}
break;
case 'W':
if (income < 8500) {
tax_amount = 0;
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe no tax for the fiscal year 2016");
} else {
if (income < 24000) {
tax_amount = income * .015;
} else {
tax_amount = income * 0.034;
}
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe a tax of $" + tax_amount + " for the fiscal year 2016");
}
while ()
}
break;
default: System.out.println("Sorry! Our system is unable to calculate your tax at this time.");
}
System.out.println("Thank you!");
//closing all objects
input.close();
}
}
You can finish it like this:
...
System.out.println("Would you like to try again? (y/n)");
} while (Objects.equals("y", input.next()))
...

Program ignoring "If Else" and printing everything

I'm trying to create a Random Number Generator program which tracks a player's wins, losses, winning percentage and total winnings. The logic of the program is that a player gets 3 chances per session and the computer generates a random number which the player needs to guess or rather should match.
I've tried to use if & else statements to tell the user if he needs to guess a higher number or a lower number within the 3 allowed guesses. What's happening is that it completely ignores the conditions and prints all three chances at once and ends the game.
Any inputs on this would be highly appreciated.
Game Class:
import java.util.Scanner;
public class Game {
Player player;
LuckyNumberGenerator lng;
public Game() {
player = new Player();
lng = new LuckyNumberGenerator();
}
public void eventLoop() {
Scanner scanner = new Scanner(System.in);
int choice = 0;
boolean exit = false;
while (!exit) {
System.out.println("Welcome to the Guessing Game");
System.out.println("==============================");
System.out.println("(1) Set Up New Player");
System.out.println("(2) Play One Round");
System.out.println("(3) Player Win Statistics");
System.out.println("(4) Display Game Help");
System.out.println("(5) Exit Game");
System.out.println("Choose an option: ");
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 5) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
} catch (NumberFormatException e) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
switch (choice) {
case 1:
createNewPlayer(scanner);
break;
case 2:
guessNumber(scanner);
break;
case 3:
printStatistics();
break;
case 4:
printHelp();
break;
case 5:
exit = true;
}
}
scanner.close();
}
public void printHelp() {
System.out.println(" ");
}
public void printStatistics() {
try {
if (player.getName() == null || player.getName().trim().length() < 1) {
System.out.println("Player has not been set up!");
} else {
System.out.println("Player statistics are: ");
System.out.println("Name: " + player.getName());
System.out.println("Wins: " + player.getGamesWon());
System.out.println("Losses: " + player.getGamesLost());
System.out.println("Amount won so far: " + player.getTotalWinnings());
System.out.println("Winnings percentage : "
+ (((player.getGamesWon()) / (player.getGamesWon() + player.getGamesLost())) * 100));
}
} catch (ArithmeticException ae) {
System.out.println("wins and loss both are 0: divide by zero exception");
}
}
public void guessNumber(Scanner scanner) {
int compGuess = lng.generate();
int userGuess = 0;
int numAttempts = 0;
int cnum = lng.generateConsole();
do {
try {
System.out.println("Guess a number between 1-100: ");
userGuess = Integer.parseInt(scanner.nextLine());
if (userGuess < 1 || userGuess > 100) {
System.err.println("Error : your Guess must be between 1-100");
}
} catch (Exception e) {
System.err.println("Error : your Guess must be between 1-100");
}
} while (userGuess < 1 && userGuess > 100);
do {
if (userGuess > compGuess) {
System.out.println("Your Guess is: " + userGuess + "and the random number: " + compGuess);
System.out.println("Sorry, you need to go LOWER :");
} else if (userGuess < compGuess) {
System.out.println("Your Guess is: " + userGuess + "and the random number: " + compGuess);
System.out.println("Sorry, you need to go HIGHER :");
}
numAttempts++;
if (userGuess == compGuess) {
System.out.println("Lucky Number was : " + compGuess + "your guess was : " + userGuess);
System.out.println("Congratulations you won " + 10 + "$");
player.setGamesWon(1);
player.setTotalWinnings(10);
}
if (userGuess != compGuess && (userGuess <= (compGuess + 5)) && (userGuess >= (compGuess - 5))) {
System.out.println("Lucky Number was : " + compGuess + "your FINAL guess was : " + userGuess);
System.out.println("Congratulations you won " + cnum + "$");
player.setTotalWinnings(5);
} else if (userGuess != compGuess) {
System.out.println("Lucky Number was : " + compGuess + "your guess was : " + userGuess);
System.out.println("Sorry better Luck Next time");
player.setGamesLost(1);
player.setTotalWinnings(-1);
}
} while (userGuess != compGuess && numAttempts < 3);
}
public void createNewPlayer(Scanner scanner) {
String name = null;
do {
try {
System.out.println("Enter the name of the player: ");
name = scanner.nextLine();
if (name.isEmpty()) {
System.err.println("Name cannot be empty");
}
} catch (Exception e) {}
} while (name.isEmpty());
this.player = new Player(name);
}
public static void main() {
Game game = new Game();
game.eventLoop();
}
}
do {
try {
System.out.println("Guess a number between 1-100: ");
userGuess = Integer.parseInt(scanner.nextLine());
if (userGuess < 1 || userGuess > 100) {
System.err.println("Error : your Guess must be between 1-100");
}
} catch (Exception e) {
System.err.println("Error : your Guess must be between 1-100");
}
} while(userGuess < 1 && userGuess > 100);//incorrect
//correct condition -> while(userGuess < 1 || userGuess > 100);
a number cannot be less than 1 and greater than 100 at the same time.
Edit 1 : In your 2nd loop the following two condition
1) if (userGuess != compGuess && (userGuess <= (compGuess + 5))
&& (userGuess >= (compGuess - 5)))
2)else if (userGuess != compGuess)
should only be evaluated if the number of guesses by player exceeds the number of attempts, therefore the two if conditions should be written outside the loop.
Also you need the first while loop to keep the user input valid between 1-100, And your second while loop will be inside it.
The final code will look something like this.
do {
do {
try {
System.out.println("Guess a number between 1-100: ");
userGuess = Integer.parseInt(sc.nextLine());
if (userGuess < 1 || userGuess > 100) {
System.err
.println("Error : your Guess must be between 1-100");
}
} catch (Exception e) {
System.err
.println("Error : your Guess must be between 1-100");
}
} while (userGuess < 1 || userGuess > 100);
System.out.println(" " + userGuess);
if (userGuess > compGuess) {
System.out.println("Your Guess is: " + userGuess
+ "and the random number: " + compGuess);
System.out.println("Sorry, you need to go LOWER :");
}
if (userGuess < compGuess) {
System.out.println("Your Guess is: " + userGuess
+ "and the random number: " + compGuess);
System.out.println("Sorry, you need to go HIGHER :");
System.out.println("if 1");
}
numAttempts++;
if (userGuess == compGuess) {
System.out.println("Lucky Number was : " + compGuess
+ "your guess was : " + userGuess);
System.out.println("Congratulations you won " + 10 + "$");
// player.setGamesWon(1);
// player.setTotalWinnings(10);
}
} while (userGuess != compGuess & numAttempts < 3);
if (userGuess != compGuess && (userGuess <= (compGuess + 5))
|| (userGuess >= (compGuess - 5))) {
System.out.println("Lucky Number was : " + compGuess
+ " your FINAL guess was : " + userGuess);
// System.out.println("Congratulations you won " + cnum + "$");
// player.setTotalWinnings(5);
} else if (userGuess != compGuess) {
System.out.println("Lucky Number was : " + compGuess
+ "your guess was : " + userGuess);
System.out.println("Sorry better Luck Next time");
// player.setGamesLost(1);
// player.setTotalWinnings(-1);
}
}
Try to put the first do-while in the second do-while at the top.
while(userGuess < 1 && userGuess > 100);
do{
This contains the error. The loop should run while the userGuess is between 1 and 100, you have excluded it.
It should be
while(userGuess >= 1 && userGuess <= 100);
do{
AND condition needs to be changed to an OR condition. Because you want to loop only when the user inputs something lower than 1 or higher than 100.
while(userGuess < 1 && userGuess > 100); ===> while(userGuess < 1 || userGuess > 100);
Again, another AND needs to be changed to OR.
// Issue with logic
if (userGuess != compGuess && (userGuess <= (compGuess + 5)) &&
(userGuess >= (compGuess - 5))) {
// Corrected Code
if (userGuess != compGuess && (userGuess <= (compGuess + 5)) ||
(userGuess >= (compGuess - 5))) {

Trying to make a lottery program which asks the user how many people want to enter the lottery

The program should output the name, email, and phone number. I need help so far I have a lottery for each individual user... I would need help trying to have one winning lottery and have each person input their numbers. Also, there is a problem when inputting two or more people. It just shows the winning lottery plus the numbers of the previous winning lottery numbers.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean error = true;
int customerAmount;
String name, phone, email, lottery = "";
String lotteryNum = "";
String userGuess;
double pickedNumber;
String stringOfPickedNumber = "";
int correct;
int counter;
customerAmount = Integer.parseInt(JOptionPane.showInputDialog("How many people would you like to enter?"));
for (int i = 0; i < customerAmount; i++) {
name = JOptionPane.showInputDialog("Please enter person " + (i + 1) + "'s name");
phone = JOptionPane.showInputDialog("Please enter person " + (i + 1) + "'s phone number");
email = JOptionPane.showInputDialog("Please enter person " + (i + 1) + "'s email");
JOptionPane.showMessageDialog(null, "Please type in the output box below.");
System.out.println("Guess person " + (i + 1) + "'s three digit number (e.g. 123): ");
userGuess = input.next();
System.out.println("");
System.out.println("Name: " + name);
System.out.println("Phone Number: " + phone);
System.out.println("Email: " + email);
//Identify the repeated steps and use a for loop structure
//Input: Ask user to guess 3 digit number
//Generate a 3-digit "lottery" number composed of random numbers
for (counter = 1; counter <= 3; counter++) {
pickedNumber = Math.random();
if (pickedNumber < 0.1) {
stringOfPickedNumber = "0";
} else if (pickedNumber < 0.2) {
stringOfPickedNumber = "1";
} else if (pickedNumber < 0.3) {
stringOfPickedNumber = "2";
} else if (pickedNumber < 0.4) {
stringOfPickedNumber = "3";
} else if (pickedNumber < 0.5) {
stringOfPickedNumber = "4";
} else if (pickedNumber < 0.6) {
stringOfPickedNumber = "5";
} else if (pickedNumber < 0.7) {
stringOfPickedNumber = "6";
} else if (pickedNumber < 0.8) {
stringOfPickedNumber = "7";
} else if (pickedNumber < 0.9) {
stringOfPickedNumber = "8";
} else if (pickedNumber < 1) {
stringOfPickedNumber = "9";
}
System.out.println(counter + ": " + stringOfPickedNumber);
lotteryNum += stringOfPickedNumber;
}
//print the lottery number
System.out.println("The winning lotto number for person " + (i + 1) + " was: " + lotteryNum);
//convert each string to appropriate substrings
//Compare the user's guess to the lottery number and report results
correct = 0;
for (counter = 0; counter <= 2; counter++) {
if (lotteryNum.substring(counter, (counter + 1)).equals(userGuess.substring(counter, (counter + 1)))) {
correct++;
}
}
if (correct == 2 && !(lotteryNum.substring(0, 1).equals(userGuess.substring(0, 1)) && (lotteryNum.substring(2, 3).equals(userGuess.substring(2, 3))))) {
System.out.println("One pair matched, congrats!");
} else if (correct == 3) {
System.out.println("All numbers matched - you WIN!");
} else if (correct == 1) {
System.out.println("One number matched, but you aren't a winner, sorry.");
} else if (correct == 2) {
System.out.println("Two numbers matched, but they weren't adjacent so you aren't a winner, sorry");
} else {
System.out.println("No numbers matched, sorry.");
}
}
}
}

Very simple game about Guessing The Number

/hello, I am trying to learn how to use "break" commend in java as well as continuing loop with "y or n" choice. I am writing this game Guessing Number and I have some trouble with "y" choice. I will try to explain, to write a game of guessing number was easy so I started to add some conditions like the possibility on the and to play again or not, later I was thinking that would be more interesting if I add possibility to quit any time player wish, but that does not working correctly. Please help, thats my code
package guessinggame;
import java.util.Random;
import java.util.Scanner;
/**
*
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
}
}
Here is an alternative that achieves that same outcome
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
int guess = 0;
int number_of_tries = 0;
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
guess = input.nextInt(); //get first input
while (guess != -1)
{
int number_guess = rand.nextInt(5) + 1;
++number_of_tries;
//check if user wins and exits loop
if (isWin (number_guess,guess))
{
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? [1 yes/ -1 no]: ");
guess = input.nextInt();
if (guess == -1)
break;
else
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
}
else if (number_guess < guess )
{
System.out.println(" Guess is too High " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
else if (number_guess > guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
}
System.out.println ("bye bye");
}
public static boolean isWin (int number,int guess)
{
return (number == guess) ? true :false;
}
}
You forgot to wait for user input after this statement:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
E.g. you could try next approach:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (input.hasNext()) {
if (another.equalsIgnoreCase("y")) {
play_again = true;
input.next();
} else {
play_again = false;
}
}
It looks like your braces are messed up for your play again if statement
This will work.
package aa;
import java.util.Random;
import java.util.Scanner;
public class abc {
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
break;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
input.next();
if (win == true){
System.out.println(" You Win!!! ");
}
else{
System.out.println(" Good Luck Next Time!!! ");
System.out.println(" The number was " + number_guess);
}
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
another = input.next();
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
System.out.println("Thank you!!!");
}
}

Categories

Resources