#pablo
I seem to be stuck in this loop :
do{
System.out.println("Voulez-vous saisir d'autres parties? (o/n)");
reponse = niveau.nextLine(); // extraction de la dernière ligne
if (reponse.toLowerCase().equals("o") == false || reponse.toUpperCase().equals("O") == false || reponse.toLowerCase().equals("n") == false || reponse.toUpperCase().equals("N") == false) {
System.out.println("R\u00C9PONSE INVALIDE ! VEUILLEZ ENTRER O OU N.");
} else {
validationReponse = true;
}
}while(!validationReponse);
Thank you all for your help ! I was able to get the validation working for questions with numeric answers but now I don't know how to get it working for questions with a "y or n" answer. I tried this but it's not working :
do{
System.out.println("Do you want to enter more game scores ? (y/n)");
reponse = niveau.nextLine();
if (reponse != o || reponse != n) {
System.out.println("Answer is invalid! Please enter y or n.");
} else {
validationReponse = true;
}
}while(!validationReponse);
I am a beginner. I am taking my first java class. In my code, I would like to add a validation for the questions : Please choose a game level, Have you won the game and Do you want to enter more games, I need to make sure that the input is valid and if an invalid answer is provided, it needs to loop back to the question. I am not sure how to do that.
No advanced coding in your answers please. I am in a beginners class. It needs to be simple.
String reponse="O";
while (reponse.toLowerCase().equals("o"))
{
System.out.println("Please choose your game level :");
System.out.println (" ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println (" For Beginner press 1");
System.out.println (" For Advanced press 2");
System.out.println (" For Expert press 3");
System.out.println (" ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.print (" My choice is : ");
Niveau = niveau.nextInt();
if(Niveau == 1){
int choix1 = 0;
nbParties_Facile++;
System.out.println("Have you won the game ?");
System.out.println(" Press 1 for YES ");
System.out.println(" Press 2 for NO ");
choix1 = niveau.nextInt();
niveau.nextLine();
if (choix1 == 1){
nbPartiesFaciles_Finies++;
tauxReussite_Facile = nbPartiesFaciles_Finies / nbParties_Facile * 100;
System.out.println("How many times did you take to complete the grid ?");
System.out.println(" Please enter the time in minutes");
String afficheur5 = niveau.nextLine();
tempsResolution_Facile = (nbPartiesFaciles_Finies * tempsResolution_Facile) + Integer.parseInt(afficheur5) / (nbPartiesFaciles_Finies);
}
else if (choix1 == 2){
tauxReussite_Facile = nbPartiesFaciles_Finies - 1 / nbParties_Facile * 100;
}
else {
//default
}
}
if(Niveau == 2){
int choix2 = 0;
nbParties_Intermediaire++;
System.out.println("Have you won the game ?");
System.out.println(" Press 1 for YES ");
System.out.println(" Press 2 for NO ");
choix2 = niveau.nextInt();
niveau.nextLine();
if (choix2 == 1){
nbPartiesIntermediaires_Finies++;
tauxReussite_Intermediaire = nbPartiesIntermediaires_Finies / nbParties_Intermediaire * 100;
System.out.println("How many times did you take to complete the grid ?");
System.out.println(" Please enter the time in minutes");
String afficheur7 = niveau.nextLine();
tempsResolution_Intermediaire = (nbPartiesIntermediaires_Finies * tempsResolution_Intermediaire) + Integer.parseInt(afficheur7) / (nbPartiesIntermediaires_Finies);
}
else if (choix2 == 2){
tauxReussite_Intermediaire = nbPartiesIntermediaires_Finies - 1 / nbParties_Intermediaire * 100;
}
else {
//default
}
}
if(Niveau == 3){
int choix3 = 0;
nbParties_Expert++;
System.out.println("Have you won the game ?");
System.out.println(" Press 1 for YES ");
System.out.println(" Press 2 for NO ");
choix3 = niveau.nextInt();
niveau.nextLine();
if (choix3 == 1){
nbPartiesExpertes_Finies++;
tauxReussite_Expert = nbPartiesExpertes_Finies / nbParties_Expert * 100;
System.out.println("How many times did you take to complete the grid ?");
System.out.println(" Please enter the time in minutes");
String afficheur9 = niveau.nextLine();
tempsResolution_Expert = (nbPartiesExpertes_Finies * tempsResolution_Expert) + Integer.parseInt(afficheur9) / (nbPartiesExpertes_Finies);
}
else if (choix3 == 2){
tauxReussite_Expert = nbPartiesExpertes_Finies - 1 / nbParties_Expert * 100;
}
else {
//default
}
}
System.out.println("Do you want to enter more games ? (o/n)");
reponse = niveau.nextLine();
}
niveau.close();
Let's use as an example Please choose a game level question
So you there are many ways to do this, I will try to keep it as simple as possible since you are a beginner to the language, but the goal is always to stick to object orientated programming. However, we can accomplish this with a a simple method
. So you could have a simple method like this:
private static boolean askForLevel() {
System.out.println("What is the level you want?");
String response = scanner.nextLine();
if (!response.equals("something")) {
return false;
}
askForLevel();
// More stuff
return true;
}
Do somwething as Below,
do {
System.out.println("Please choose your game level :");
System.out.println (" ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println (" For Beginner press 1");
System.out.println (" For Advanced press 2");
System.out.println (" For Expert press 3");
System.out.println (" ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.print (" My choice is : ");
while (!sc.hasNextInt()) {
System.out.println("That's not a number, Please choose a Number !");
sc.next();
}
number = sc.nextInt();
} while (number<=3);
inside if(number==1) do the thing same as above.
I would use JOptionPane instead of scanner...but that's a matter of opinion. Since you are new, your teacher is probably not going to jump right into object-oriented programming, which is ok because you need to understand the basics, so with a minimal use of object-oriented programming:
//user input
int level = 0;
do{
level = Integer.parseInt(JOptionPane.showInputDialog("Choose the level :").trim());
}while(level < 1 || level > 3);
if (level == 1) {
//your code
}
else if(level == 2){
//your code
}
else if(level == 3){
//your code
}
You could build this in a private method like Pablo suggested.
Related
The question is this:
Simulate an ATM machine.
Create ten accounts in an array with id 0, 1, . . . , 9, and initial balance $100. The system prompts the user to enter an id. If the ID is entered incorrectly, ask the user to enter a correct id. Once an ID is accepted, the main menu is displayed as shown in the sample run. You can enter a choice 1 for viewing the current balance, 2 for withdrawing money, 3 for depositing money, and 4 for exiting the main menu. Once you exit, the system will prompt for an id again. Thus, once the system starts, it will not stop.
My code is this:
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
Account9_07 test = new Account9_07();
test.setBalance(100.00);
int [] account = new int [9];
for( ; ;) {
System.out.print("Enter an ID # (0-9): ");
int IDinput = input.nextInt();
if( IDinput <10 && IDinput > 0)
break;
System.out.println("The ID entered is incorrect. Please enter the correct ID \n");
}
for( ; ; ) {
System.out.println("\n Main Menu " + "\n 1: check balance " + " \n 2: withdraw" + "\n 3: deposit" + "\n 4: exit" );
System.out.print(" Enter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.print("\n The balance is " + test.getBalance());
}
else if(choice == 2) {
System.out.print("How much would you like to withdraw: ");
double withdraw = input.nextDouble();
test.withdraw(withdraw);
}
else if(choice == 3) {
System.out.print("How much would you like to deposit: ");
double deposit = input.nextDouble();
test.deposit(deposit);
}
if( choice == 4)
break;
}
//4 is not looping back to enter an ID
}
EDIT: I've added some changes to the code itself, so please check it out again.
So what I've done, is place both for loops in an infinite while loop.
boolean CO = true;
while(true)
{
for( ; ;) {
System.out.print("Enter an ID # (0-9): ");
int IDinput = input.nextInt();
if( IDinput <10 && IDinput > 0)
break;
System.out.println("The ID entered is incorrect. Please enter the correct ID \n");
}
for( ; ; ) {
System.out.println("\n Main Menu " + "\n 1: check balance " + " \n 2: withdraw" + "\n 3: deposit" + "\n 4: go back to ID" + "\n 5: terminate program");
System.out.print(" Enter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.print("\n The balance is " + test.getBalance());
continue;
}
else if(choice == 2) {
System.out.print("How much would you like to withdraw: ");
double withdraw = input.nextDouble();
test.withdraw(withdraw);
continue;
}
else if(choice == 3) {
System.out.print("How much would you like to deposit: ");
double deposit = input.nextDouble();
test.deposit(deposit);
continue;
}
else if( choice == 4)
{
break;
}
else if(choice == 5)
{
CO = false;
break;
}
}
if(CO == true)
{
continue;
}
break;
}
According to the code you posted, the program keeps running forever, so read the comments in the code. I've taken the liberty of giving another choice to the user, to enter 5 if he wants to stop the program.
CO stands for "Continue Outer".
By default, CO remains true. So when the user enters 4, then the second loop breaks. Since CO is still true, the outermost loop continues.
If the user enters 5, then CO becomes false, and the second loop breaks.
Now, because CO is false, the outermost loop breaks, and the program stops.
Hi im currently creating a guessing letter game! So far i have made it so you guess between the numbers 1 and 26 using the java.util.random class. However this random number should be converted into the corresponding number within the alphabet! ie a=1 etc..This is where my problem is i dont know how to convert this randomly generated number into a letter! This needs to be related to the integer as i have to able to tell the user if they are above the letter in the alphabet or to low based on the guess they entered! One more thing is that the users guess will be a letter also! Below is my code! Any help will be greatly appreciated!
{
Random rand = new Random(); //This is were the computer selects the Target
int guess;
int numGuesses = 0;
int Target;
String userName;
String playagain;
boolean play = true;
int session = 0;
int sessions = 0;
int bestScore = 0;
Scanner consoleIn = new Scanner(System.in);
Scanner name = new Scanner(System.in);
System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
userName= name.nextLine();
System.out.println("Hello "+ userName + " :) Welcome to the game!\n");
while (play = true)
{
session++;
Target = rand.nextInt(26) + 1;
System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have
do {
guess = consoleIn.nextInt();
numGuesses++;
if (guess > 26)
System.out.println("Error! Above MAXIMUM range");
else if (guess <= 0)
System.out.println("Error! Below MINIMUM range");
else if (guess > Target)
System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
else if (guess < Target)
System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
}
while(guess != Target && numGuesses <5);
if(guess == Target) {
System.out.println("Congratulations "+ userName + ", it took you "+ numGuesses +" attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
sessions++;
}
else
{
System.out.println("Sorry "+ userName + ", You've used up all of your guesses! The correct answer was "+ Target + "!"); //This tells the player that they failed to find the number and then tells them what the correct answer
}
{
Scanner answer = new Scanner(System.in);
System.out.println("Would you like another GO "+ userName +"? [Y/N]");//This asks the player if they would like to play again
playagain = answer.nextLine();
if(playagain.equalsIgnoreCase("Y"))//This is what happens if the player opts to play again
{
play = true;
numGuesses = 0;
} else if(playagain.equalsIgnoreCase("N"))//This is what happens if the player opts to exit the game
{
play = false;
System.out.println("Thanks for playing "+ userName +"! :) Please come back soon!");
System.out.println("You had "+ session +" Goes");
System.out.println("The number of times you guessed correctly: "+ sessions +"");
break;
}
}
}
}
Random random = new Random();
char c = (char) (random.nextInt(26) + 'a');
This maps (0 to 25 ) to ('a' to 'z')
Im making a player 2 guesses player 1's number game. Ive made an int counter thats == 10 and is meant to go down everytime player 2 gets answer wrong. I cant get it to work and i need help on how to make this. Youll see what i mean...
package guessMain;
import java.awt.*;
import java.util.Scanner;
public class GuessCodeSource {
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else if (answer <= 100){
System.out.println("Guess in the space below.");
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
}else if (guess != answer);
for (int counter = 10; counter-=1);
System.out.println("You have " + count + " of guesses left");
}
}
}
To make reduce a number by one, use the decrement operator.
For example,
counter--;
would subtract one from the counter.
If you want to subtract more than one, you can use the "-=" operator in the following manner:
counter -= 2;
So, in your code, in the final else if block, you could change the code to the following to reduce "counter" by 1.
else if (guess != answer) {
counter--;
System.out.println("You have " + count + " of guesses left");
}
But, in your code, you never declare the variable counter. Somewhere, most likely at the top of your code, you want to create this variable. To create an Integer variable you do the following:
int counter = 10;
You asked how to LOOP as well, so here it is. Read the comments to gain understanding of what the code does. If you have more questions, ask below.
public static void main(String[] args) {
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
int guess = 0; // Create these variables up here to access them everywhere in "main"
int counter = 0;
boolean continueTheGame = true; // A boolean variable that holds ONLY either true or false
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
// A while loop will continue as long as a boolean expression is true.
// So, we create a boolean variable somewhere above called "continueTheGame"
// As long as this is true, the code INSIDE of the while loop's brackets will repeat.
// If the user has less than zero guesses left, we can set the variable to false,
// which will make the loop stop!
while (continueTheGame == true) { // The start of the while loop
if (answer >= 100) {
System.out.println("BUSTED! I said a number between 1 - 100!");
} else if (answer <= 100) {
System.out.println("Guess in the space below.");
guess = josh.nextInt();
}
if (guess == answer) {
System.out.println("CORRECT!!!!!");
} else if (guess != answer) {
counter--;
System.out.println("You have " + counter + " of guesses left");
if (counter > 0) { // If they have MORE than zero guesses left, loop again!
continueTheGame = true;
} else { // If they have zero guesses left, make it stop looping
continueTheGame = false;
}
}
}
// Once the loop ends, the code will start again here,
// because the bracket above is the final bracket of the WHILE loop
}
Okay, so here is the full functional main method you are looking for:
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else {
System.out.println("Guess in the space below.");
}
for (int count = 10; count>=0; count--) {
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
System.exit(0);
} else {
System.out.println("You have " + count + " of guesses left");
if (count == 0) {
System.out.println("Sorry, you lost, no more tries..");
System.exit(0);
}
}
}
josh.close();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I need help making my guessing game give you the option to choose which difficulty, can someone fix my code and repost it because I'm kinda lost right now!
import java.util.*;
public class GuessingGame
{
public static void main(String[] args)
{
boolean play = true;
String input1;
while(play == true){
Scanner input = new Scanner(System.in);
Random rand = new Random();
int counter = 0;
int guess = -1;
int dif = 0;
int easy = rand.nextInt(10) + 1, med = rand.nextInt(1000) + 1, hard = rand.nextInt(10000) + 1;
System.out.println("Difficulty Select");
System.out.println("=================");
System.out.print("1) Easy 2) Medium 3) Hard :");
dif = input.nextInt();
switch (dif)
{
case 1:
if (dif == 1)
System.out.println ("Random number between 1 and 10 selected." + easy);
else if (dif == 3)
System.out.println ("Random number between 1 and 10000 selected.");
break;
}
while (guess != med)
{
System.out.print ("|" + med + "|" + "Random number between 1 and 1000 selected.");
guess = input.nextInt();
counter = counter + 1;
if (guess == med)
System.out.println ("YOU WIN MOFO!");
else if (guess < med)
System.out.println ("You're to cold!");
else if (guess > med)
System.out.println ("You're to hot!");
}
System.out.println ("It took you " + counter + " guess(es) to get it correct");
System.out.print ("Do you want to play again? (y/n): ");
input1 = input.nextLine(); // absorb enter key from integer
input1 = input.nextLine();
if (input1.equals("y"))
play = true;
else
play = false;
}
}
}
Do not combine a switch and an if for the same purpose (and put them inside each other). Pick one. Both are fine here.
In your construction here:
switch (dif)
{
case 1:
if (dif == 3) ...
}
The if can never be true, since you put it in the case 1 block. Obviously, dif can't be both 1 and 3 at the same time.
Update
The first time the user makes a choice such as "1" the menu is displayed again. The next time a selection is made the payment information begins to cycle. After the cycling is complete and the menu is displayed again, it works as it should. Also, the first two years are output instead of just the first when a selection begins to cycle, but then outputs one year at a time as intended.
//create scanner object for choosing a loan, then prompt for and accept input
Scanner choose = new Scanner(System.in);
String choice;
System.out.println("\nType 1, 2, or 3 and press enter to see the monthly payment information for the respective loan. To end the program type \"end\".");
choice = choose.next();
//cycle loan 1 payment information
//create scanner object to advance to the next year's payments
//loop for cycling payment information
//initialize loan principal to variable
while (!"end".equals(choice)) {
System.out.println("\nType 1, 2, or 3 and press enter to see the monthly payment information for the respective loan. To end the program type \"end\".");
choice = null;
choice = choose.next();
if ("1".equals(choice)) {
//calculation code
}
if (j < 6) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
}
choice = null;
}
if ("2".equals(choice)) {
//calculation code
}
if (j < 14) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
}
choice = null;
}
if ("3".equals(choice)) {
//calculation code
}
if (j < 29) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = next.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
}
choice = null;
}
}
choose.close();
}
}
I can see three issues upfront:
You don't need two scanners for System.in stream. Remove this statement Scanner next = new Scanner(System.in); and use the choose instance.
If you close your input scanner as next.close();, it closes your input stream System.in as well and you may not be able read the stream again. Make sure you close the stream only when you are completely done with your program.
Use equals method to compare the condition in while as while(!"end".equals(choice)). Put the literal "end" as first argument will take care of the null value of choice.
EDIT:
Your modified code at high level:
Scanner choose = new Scanner(System.in);
String choice= null;
int j = 0;
while (!"end".equals(choice)) {
System.out.println("\nType 1, 2, or 3 and press enter to see the monthly payment information for the respective loan. To end the program type \"end\".");
choice = choose.nextLine();
if ("1".equals(choice)) {
//calculation code
if (j < 6) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
choice = null;
}
if ("2".equals(choice)) {
if (j < 14) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
choice = null;
}
if ("3".equals(choice)) {
if (j < 29) {
System.out.println("Press enter to get the mortgage information for year " + (j + 2));
choice = choose.nextLine();
} else {
System.out.println("Congratulations, your mortgage has been paid off.");
}
choice = null;
}
}
choose.close();
One bug is that String equality isn't the same as ==. You should use .equals():
while (!choice.equals("end")) {
Hope that helps!
You're setting choice to null, so choice != "end" is always true.
Move the next.close(); choice = null to outside the while loop.
Also, what weolfe91 said.
import java.util.Scanner;
class Main
{
public static void main(String [] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.1:");
int a=sc.nextInt();
System.out.println("Enter no.2:");
int b=sc.nextInt();
boolean exit=false;
do
{
System.out.println("1.addition");
System.out.println("2.subtraction");
System.out.println("3.multiplication");
System.out.println("4.division");
System.out.println("5.exit");
System.out.println("choose one!");
Scanner sd=new Scanner(System.in);
System.out.println("enter your choice");
int num=sd.nextInt();
switch(num)
{
case 1:
int add=a+b;
System.out.println("addition="+add);
System.out.println("\n");
break;
case 2:
int sub=a-b;
System.out.println("subtraction="+sub);
System.out.println("\n");
break;
case 3:
int mul=a*b;
System.out.println("multilpication="+mul);
System.out.println("\n");
break;
case 4:
int div=a/b;
System.out.println("division="+div);
System.out.println("\n");
break;
case 5:
exit=true;
break;
}
}while(!exit);
}
}