I'm trying to get a dice roller happening and I'm having some difficulty adding a loop somewhere so the program doesn't quit after one roll. I want to ask the user if they want to roll and it rolls by saying "y." I want to end the program by asking the user the same question but it ends with "n"
/*
Natasha Shorrock
Assignmnt A6
11/07/16
*/
package diceroller;
import java.util.Random;
import java.util.Scanner;
public class DiceRoller {
public static void main(String []args) {
System.out.println(" Do you want to roll the dice? ");
Random dice = new Random();
Scanner input = new Scanner(System.in);
int faces;
int result;
System.out.println("Dice Roller\n");
System.out.println("How many faces does the dice have?");
faces = input.nextInt();
result = dice.nextInt(faces) + 1;
System.out.println("\nThe dice rolled a " + result );
}//Dice Roller
}//class DiceRoller
You have to read the input after the following expression:
System.out.println(" Do you want to roll the dice? ");
To receive the users input call: input.nextLine();. Thereafter loop while the input is "y". If the user input is not equals to "y" the while-loop gets terminated.
The while(condition) loop is excuted as long as the condition is true
The while statement continually executes a block of statements while a particular condition is true. The while and do-while Statements
For example consider this code :
public static void main(String[] args) {
Random dice = new Random();
Scanner input = new Scanner(System.in);
System.out.println("Do you want to roll the dice? (y: yes / q: to quit)");
String answer = input.nextLine(); // reading the input
// we check if the answer is equals to "y" to execute the loop,
// if the answer is not equals to "y" the loop is not executed
while ("y".equals(answer)) {
System.out.println("Dice Roller");
System.out.println("How many faces does the dice have?");
int faces = input.nextInt();
int result = dice.nextInt(faces) + 1;
input.nextLine(); // to read the newline character (*)
System.out.println("The dice rolled a " + result);
System.out.println("Do you want to roll the dice? (y: yes / q: to quit)");
answer = input.nextLine();
}
}
To find out more about the while and do-while mechanisms, please visit this toturial
(*) To understand the use of nextLine() after a call to nextInt() please visit Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
A do-while is a very good option. Another way of doing it could be using a while loop with a switch or preferably an IF/ ELSE IF statement. Perhaps something like below. This is only a suggestion.
boolean checkForExit = false;
while(checkForExit != true) { //while checkForExit does not equal true (therefore false) continue..
System.out.println("Do you want to roll the dice?");
String answer = input.next(); //get char input from user.
if(answer.toLowerCase().equals("y")) { //if 'y' then do this
//ask user for number of faces on dice and roll
} else { // otherwise end the program
//set isTrue to true to exit while loop. ends program
isTrue = true;
}
}
Related
I am making an odd or even program with a while loop. I am trying to figure out how to end the while loop with a certain number. Right now I have 1 to continue the loop, and trying to make 2 the number that terminates it. Also trying to figure out how to terminate the program if a user types anything but a number like a letter/words.
package oddoreven;
import java.util.Scanner;
public class oddoreven {
public static void main (String[] args){
int num;
int x = 1;
while(x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}
}
}
You should try to use "a real termination condition" in order to terminate a while loop (or any loop for that matter); it's cleaner and should be easier to understand by everyone else.
In your case, I think it's better to have a do-while loop with some condition around this logic: num % 2 == 0, and an inner while loop for handling user input/validation.
If you still want to break loops abruptly, have a look here.
If you still need some help with the code, hit me up and I'll sketch up something.
I did not follow the conditions you wanted exactly because it does not make sense to have a continue condition AND a terminate condition unless there are other options.
What did you want the user to do if he entered 3, 4 or 5? Exit the code or continue the code? Well if the default is to exit, then you do not need the code to exit on 2 because it already will! If the default is to continue, then you do not need the continue on 1 and only the exit on 2. Thus it is pointless to do both in this case.
Here is the modified code to use a do while loop to ensure the loop is entered at least 1 time:
int x;
do {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
int num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to check another number, anything else to terminate.");
if (!s.hasNextInt()) {
break;
}
else {
x = s.nextInt();
}
} while(x == 1);
}
Note that I added a check to !s.hasNextInt() will check if the user enters anything other than an int, and will terminate without throwing an Exception in those cases by breaking from the loop (which is the same as terminating the program in this case).
If the x is a valid integer, then x is set to the value and then the loop condition checks if x is 1. If x is not 1 the loop terminates, if it is it will continue through the loop another time.
Another thing you can try is that instead of exiting the program you can just keep asking user to enter correct input and only proceed if they do so. I don't know what is your requirement but if you want to go by good code practice then you shouldn't terminate your program just because user entered wrong input. Imagine if you googled a word with typo and google just shuts off.
Anyways here is how I did it
import java.util.Scanner;
public class oddoreven {
public static void main(String[] args) {
int num;
int x = 1;
while (x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
boolean isInt = s.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
s.nextLine(); // Discarding the line with wrong input
System.out.print("Please Enter correct input: "); // Asking user again
isInt = s.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
num = s.nextInt(); // If it is int. It reads the input
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
// trying to figure out how to get the code to terminate if you put in a value
// that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}
}
}
To exit the program when the user enters anything other than a Number, change the variable x type to a String
if (!StringUtils.isNumeric(x)) {
System.exit(0);
}
To exit the program when user enters 2
if (x == 2) {
System.exit(0);
}
So for my Java programming class one of the assesments is the following (a classic number guessing game):
Write a program that plays the HiĀLo guessing game with
numbers. The program should pick a random number between 11 (inclusive) and 88 (exclusive), then
repeatedly prompt the user to guess the number. On each guess, report to the user that he or she is
correct or that the guess is high or low. Continue accepting guesses until the user guesses correctly or
choose to quit. Use a sentinel value to determine whether the user wants to quit. Count the number of
guesses and report that value when the user guesses correctly. At the end of each game (by quitting or
a correct guess), prompt to determine whether the user wants to play again. Continue playing games
until the user chooses to stop. You are required to utilise at least a while loop and a for loop correctly.
So far, the game is fully working, using WHILE and IF functions. But in order to get full marks on my solution, it requires me to use at least one FOR loop, but I'm struggling to do that.
import java.util.*;
public class Guessing {
public static void main (String[] args)
{
//Setting up the variables
final int MAX = 88;
final int MIN = 11;
int answer, guess = 1;
String another="Y";
//Intializing scanner and random
Scanner scan = new Scanner (System.in);
Random generator = new Random();
//play again loop
while (another.equalsIgnoreCase("Y"))
{
//Generate a random number between 11 and 88
answer = generator.nextInt(MAX-MIN)+11;
System.out.print ("Guess the number I picked between "+MIN+" and "
+ MAX + "!\n");
while(guess!=answer)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!");
break;}
}
}
//Asking player to play another game
System.out.println("Do you want to play another game?(Y|N)");
another = scan.next();
if (another.equalsIgnoreCase("N"))
System.out.println("Goodbye, thank you for playing");
}
}
}
So far, the program works. It correctly gives higher/lower advice, the current round stops when typing in 0 as a guess and you can start another round with Y/N. But Im struggling to substitute one of the functions/loops with a FOR loop.
You can substitute the central while loop with a for loop that you can also use to count the number of iterations
for(int i=0;;i++)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!\n");
System.out.println("It took "+i+" guesses to get the answer");
break;}
}
}
This for loop is an infinite loop because it hasn't got the second argument. However your program will exit the for loop when the correct answer is given because of the break in the final else.
As the number of guesses is counted upwards, one may use the for loop on that.
Normally one would write for (int i = 0; i < n; ++i) { but here we want to know the loop counter after the for loop and have to declare it before:
int numberOfGuesses = 0;
for (; guess != 0 && guess != answer; numberOfGuesses++) {
}
... numberOfGuesses
There is no upper limit other than finding the answer or quiting.
All three parts in for (PARTA; PARTB; PARTC) are optional.
import java.util.Scanner;
public class MyFirstGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double randomNumber = Math.random();
double realNumber = randomNumber*10;
double realerNumber = Math.round(realNumber);
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
}
So what I am trying to do is make a "game" for my Java class. I have generate a random number between 1 and 10 and the user has to input a number and if the input and the random number are the same, they "win." If they lose, they try again...? First, I did all the necessary scanner stuff that I don't even fully understand. I just copied the professor. So the program says to enter a number and the program generates a number between 0.0 and 1.0. I multiply that number by 10 to make it between 1 and 10. Then I round the number to the nearest integer. If the input matches this number, the program says you win. If not, it'll say try again.
The problem is how do I make the program repeat itself without the user having to reboot the program with the cmd? I need to repeat the input, random number generator, and then the result. What do I need to do? Also, how is my program? My second big one...yeah right...big. But seriously, how can I make it less complex or anything to improve it. Thanks.
Use a while loop:
long realerNumber = Math.round(realNumber);
// first guess
long guess = scanner.nextLong();
while (guess != realerNumber) {
System.out.println("Try Again...");
// guess again
guess = scanner.nextInt();
}
System.out.println("You Win!");
There is already a class to generate random numbers, you could use it:
// TODO: move to constant
int MAX = 10;
// nextInt(int n) generates a number in the range [0, n)
int randomNumber = new Random().nextInt(MAX + 1)
just put your code inside the do-while loop
Scanner scanner = new Scanner(System.in);
do
{
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double realerNumber = Math.round( Math.random() * 10 );
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
while(someCondition);
the someCondition can be for example a counter (if you want to play n times just set counter to n and decrease it every loop iteration then check if it is 0 in while) or some function checking if a key is pressed (like escape)
int n = 5;
do
{
n--;
...
}
while(n > 0);
This will run forever, but it's the idea mentioned in the first comment
...
Scanner scanner = new Scanner(System.in);
while(true){ // add this after Scanner ... declaration
...
} // end of existing else block
} // end of while loop, so add this single brace
...
My code here checks whether or not the word that the user inputs is a palindrome or not. It executes properly its just that if the user tries to loop it by pressing "1". The program ends. How do I fix this?
int answer =0;
String original, backwards = "";
Scanner input = new Scanner(System.in);
System.out.println("A palindrome is a word that is the same forwards as it is backwards. Enter a word to check if it is a palindrome or not.");
original = input.nextLine();
int length = original.length();
do {
for ( int i = length - 1; i >= 0; i-- )
backwards = backwards + original.charAt(i);
if (original.equals(backwards))
System.out.println("The entered phrase is a palindrome.");
else
System.out.println("The entered phrase is not a palindrome.");
}
while (answer ==1);
System.out.println("If you would like to check another word press 1. If you wish to exit, press 2.");
answer = input.nextInt();
if (answer ==1){
System.out.println("Enter another word");
}
else if (answer == 2){
System.out.println("Have a nice day");
}
}
}
Here is a sample output of the program:
A palindrome is a word that is the same forwards as it is backwards. Enter a word to check if it is a palindrome or not.
racecar
The entered phrase is a palindrome.
If you would like to check another word press 1. If you wish to exit, press 2.
1
Enter another word
Your loop finishes before the user gets to choose if he wants to enter 1 or 2. It is a do...while loop, so it ends at the while. So it executes only once - because as soon as a palindrome is checked, the next thing is to check whether the answer is 1. But the user has not entered either 1 or 2 at this point.
So you should move the } while ( answer == 1 ) part to the line after the closing of the if...else... that checks what the user answer was.
Also, if the answer was 1, you should ask for another input. The only place you ask for input is before the loop starts. If the user answered 1 you should run original = input.nextLine(); again. Be careful - you may need to run two input.nextLine(), as the scanner will think the rest of the line after the 1 or 2 is what you meant.
Your scanner is asking for nextLine, but you're asking for an int. nextLine means it will take what is typed in the nextLine as a string.
Simple fix is replace 1 and 2 with characters a and b.
Complicated way is to parse string into integer.
make the palindrome check as a method and then call the method if the user input is 1.
In your code , it does not do anything if the user inout is equal to 1.
i just used your scanner objects as it is. You can declare them in your class to use it in all the methods.
public void palindrome(String S){
int answer =0;
String original, backwards = "";
Scanner input = new Scanner(System.in);
System.out.println("A palindrome is a word that is the same forwards as it is backwards. Enter a word to check if it is a palindrome or not.");
original = input.nextLine();
int length = original.length();
do {
for ( int i = length - 1; i >= 0; i-- )
backwards = backwards + original.charAt(i);
if (original.equals(backwards))
System.out.println("The entered phrase is a palindrome.");
else
System.out.println("The entered phrase is not a palindrome.");
}
while (answer ==1);
System.out.println("If you would like to check another word press 1. If you wish to exit, press 2.");
int option= input.nextInt();
if (option==1){
System.out.println("Enter another word");
String word= input.readLine();
palindrome(word);
}
You need to put the check if user want to enter another work in the while loop. But in the mean time, be careful to reset all variables to their original value, so it might be best to set them in the while loop as well. Something like this:
import java.util.Scanner;
public class Palidrome {
public static void main(String[] args) {
int answer = 0;
Scanner input = new Scanner(System.in);
String original;
System.out
.println("A palindrome is a word that is the same forwards as it is backwards. Enter a word to check if it is a palindrome or not.");
while( true ) {
original = input.nextLine();
String backwards = "";
int length = original.length();
for (int i = length - 1; i >= 0; i--)
backwards = backwards + original.charAt(i);
if (original.equals(backwards))
System.out.println("The entered phrase " + original + " is a palindrome.");
else
System.out.println("The entered phrase " + original + " is not a palindrome.");
System.out.println("If you wish to exit, press 2");
answer = input.nextInt();
if(answer == 2) {
System.out.println("Have a nice day");
break;
}
input.nextLine();
System.out.println("Enter another word");
}
input.close();
}
}
A do while loop works the same way as a regular while loop, except the first conditional check is omitted. If the condition in your while was met, then execution of the code in the do block would be continued. However, the while condition is never met, can you see why? Even if this condition was met, that's not the code you wanted executed next. The code below while is not a part of the do-while loop. You need to move the while to come after both of your conditional blocks at the end. The Java docs on while loops should be a useful read.
I am trying to do a do-while loop that makes the program iterate again after the user inputs "y" or "Y", but everytime i run the program, It prints out something like this:
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box] (I enter y)
Are you a student? (no input box is shown, and it skips it)
Are you a member of staff or faculty? [DrJava Input Box] (i enter yes or no)
How many tickets do you need? [DrJava Input Box] (I enter an int, but it doesnt complete that part where it shows how many tickets sold or how much it costs)
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box]
this is what my program looks like:
import java.util.Scanner;
public class Ticket
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double ticketprice = 12.00;
double result;
double result2;
double result3;
char repeat;
String input;
String student;
String staff;
int ticket;
do
{
System.out.println("Are you a student?");
student = keyboard.nextLine();
System.out.println("Are you a member of staff or faculty?");
staff = keyboard.nextLine();
System.out.println("How many tickets do you need?");
ticket = keyboard.nextInt();
if(student.equals("yes"))
{
System.out.println("Here is your " + ticket + " tickets for $0.00");
}
if(staff.equals("yes"))
{
result = ticketprice * .85;
result2 = ticket * result;
System.out.printf("Here are your " + ticket + " tickets for $%.2f\n", result2);
}
if(student.equals("no") && staff.equals("no"))
{
result3 = ticket * ticketprice;
System.out.printf("Here are your " + ticket + " tickets, for $%.2f\n", result3);
}
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
}
while(repeat == 'y' || repeat == 'Y');
}
}
i am a beginner to programming, so any help would be good. Thank you.
At the end of the loop you call next() to read the "try again" response. This reads the next token, but still leaves the line ending on the input stream.
Next time through the loop, when you call nextLine() to read the "are you a student" response, it simply reads the remainder of that line immediately.
The easiest solution is:
Use nextLine() instead of next() for your "try again" prompt, but then this means you'll have to take care of the line ending left by nextInt() in the "tickets" question, so then you'll also have to...
Use nextLine() instead of nextInt() for your "tickets" question, then use Integer.parseInt() to parse the string into an int.
An alternate option, since all your responses seem to be just single-word responses, is to use next()/nextInt() everywhere and not use nextLine() at all. The point is, when you mix the two, you have to be aware of how they interact.
The issue lies in this block of code:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
When you call keyboard.next(), it doesn't read the entire line, so when your program loops again, the next time you call keyboard.nextLine(), it takes in part of what you entered previously in the loop and it gets ahead of itself.
The best solution would be to add a keyboard.nextLine() after you call keyboard.next() so that the remainder of the line will be consumed and won't be left over to mess up future iterations of the loop.
So for example you could change it like this:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
keyboard.nextLine();
repeat = input.charAt(0);