So, in this program when the while loop ends, it properly displays "You Win!" and it does execute the code asking if the user wants to view credits. However, the input isn't being accepted after the question and the program ends without accepting any input.
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to play a game called Threes? Y/N");
String answer = scan.nextLine(); //Simple yes or no
if (answer.contains("Y") || (answer.contains("y"))) {
System.out.println("OK, want to know how it works? Y/N");
String answer2 = scan.nextLine();
if (answer2.contains("n") || (answer2.contains("N"))) {
System.out.println("OK, Enter a single number.");
int mistake = 0; //Used as a counter for number of division mistakes made
int numstart = scan.nextInt(); //First number input
int current = numstart; //Current number displayed - starts as the first number
System.out.println("Enter 1 or -1 if you're adding or subtracting, and 0 to divide.");
System.out.println(numstart); //Displays first number input
int input = scan.nextInt(); //First function performed by user
while (current != 1) { //The game will run until the number '1' is reached
if (input == 1) { //If '1' is input, add one to the number, and display new number
current++;
System.out.println(current);
input = scan.nextInt();
}
if (input == -1) { //If '-1' is input, subtract one from the number, and display new number
current--;
System.out.println(current);
input = scan.nextInt();
}
if (input == 0) { //If '0' is input, try to divide
if (current % 3 != 0 && current != 1) { //If you can't divide by three, try again
System.out.println("Try again.");
mistake++;
input = scan.nextInt();
}
if (current % 3 == 0) { //If you can divide, do it and display new number
current = current / 3;
System.out.println(current);
input = scan.nextInt();
}
}
if (input == 69 || input == 666) //Cheat code! If you input 69 or 666, you automatically win
break;
if (((input > 1) && (input != 69) && (input != 666)) || input < -1) { //If input is not valid, try again and display error
System.out.println("Error - wrong input.");
input = scan.nextInt();
}
}
System.out.println("You Win! Mistakes: " + mistake + "\n"); //Will display a win condition, and amount of division errors
System.out.println("Thank you for playing Threes \n - Chris Burbach");
}
System.out.println("Credits? Y/N");
String credits = scan.nextLine();
if(credits.contains("Y")||credits.contains("y"))
{
System.out.println("\n***********************************************************************");
System.out.println("*Threes: a game of dividing by three - inspired by my boredom in class*");
System.out.println("***********************************************************************");
Sorry for any confusion, I figured it out. After each instance of "You Win!", outside of its nested if statement, I needed to addscan.nextLine(); because of it returning a newline character and terminating the program due to an empty input.
Related
Sorry for the newbish question, am quite new with Java.
So I want to display an error message when user input is outside of the bounds (Lesser than 0, greater than 100) which I've managed to do but I also want that the user can try again but my current code only continues with the execution of the program.
This is what I have now:
import java.util.Scanner;
public class storeQuota {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int quotas [] = new int [100];
int NumberOfWorkers = 100;
for (int i = 0; i<numberOfWorkers; i++) {
if (i == 0) {
System.out.print("Enter the quota for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the quota for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the quota for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the quota for the " + (i+1) + "th student: ");
}
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0)
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
//Printing all quotas.
System.out.println("Thank you for your input. Your entered quotas are: ");
for (int i=0; i<numberOfWorkers; i++)
{
System.out.print(quotas[i] + ", ");
}
input.close();
}
}
With this code, the error message is correctly displayed when a user inputs an int that isn't between 0 and 100 but the user will be unable to try again, the program continues to ask for the next quoata.
I think the problem is located in this line
break;
after
System.out.println("Error - Can only be between 0 and 100.");
which always breaks the while loop. Instead you only want to break the while loop if the input is in valid range. I would not use while(true) but some sort of conditional variable which is set to false in the while loop if the input is in valid range, also because while(true) is not a good programming practice from my point of view.
Your problem is using Break;
rather than using that, you should change the while(true) to while(false), you've also forgot to add curly brackets around the if statement.
boolean x = true;
while (x){
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0){
System.out.println("Error - Can only be between 0 and 100.");
x = false;
}
}
also I suggest learning exceptions as they would make this 10x easier.
When executed, "break" breaks the loop you are currently in. In your code, break is executed irrespective of what the input is resulting in the unwanted result.
Simplest solution would be (closest to your original code):
while(true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
} else {
break;
}
}
Here, the loop will break only if correct input is entered.
You haven't used curly braces in if condition.
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
I need to write a java program reading in an indefinite amount of numbers and saves them to a collection of numbers, until an (even number) is entered in by the user. I have tried with a while loop, that when a positive number is found in it it stops. But it is not really working. Here is codes I have tried:
public static void main(String[] args) {
int programInteger = 1;
int inputtedInteger;
while (programInteger < 2) {
System.out.println("Enter a number: "); //Asks user to input a number
Scanner in = new Scanner(System.in);
inputtedInteger = Scanner(in.nextLine);
if (inputtedInteger != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
inputtedInteger=in.nextInt();
}
else if (inputtedInteger % 2 == 0){
programInteger =+1;
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
}
/* if(inputtedInteger % 2 == 0) {
System.out.println("The number "+ inmatatTal +" you entered is an even number!");
}
else {
System.out.println("Enter a number?! ");
inputtedInteger = in.nextInt();
}
Fixing a few things in the logic of the loop should work:
int inputtedInteger = 0;
Scanner in = new Scanner(System.in);
while (inputtedInteger < 1) {
System.out.println("Enter a number: "); //Asks user to input a number
inputtedInteger = in.nextInt();
if (inputtedInteger % 2 != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
}
else if (inputtedInteger % 2 == 0){
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
I would setup an outline for the code like this:
setup Scanner, create collection
while true:
userInput = scanner.nextInt()
if userInput > 0: break
collection.add(userInput)
print('user entered', collection.length(), 'numbers.')
Hope that helps. I'll leave you to fill this using actual Java syntax.
I wrote a comment on the OP on why your structure is failing to solve the issue at hand.
This is a Hi-Lo number guessing game code, and the program ends either when the user gets the correct number or enters -1 while playing the game.
Here, I was wondering if it is possible to make the program run again even after the user enters -1 and the game ends, for example, in a situation where the user feels like restarting the game without finishing the first game.
import java.util.Random;
import java.util.Scanner;
public class HighLowGame {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
int guess = scanner.nextInt();
**//if user enters -1, the game ends
if(guess == -1){
break;
}**
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
count = 0;
System.out.println("Would you like to play the game again?(yes/no): ");
String another = scanner.next();
if (another.equalsIgnoreCase("no")) {
break;
}
// if the user wants to play the game one more time, it starts again
else {
number = generator.nextInt(100) + 1;
System.out.println("Please guess the number(Enter -1 to quit): ");
}
}
}
}
}
You can just put the game into a method, and when the method ends, you just ask them.
Main:
public static void main(String[] args){
boolean flag = true;
while(flag){
play();//play the game
Scanner input = new Scanner(System.in);//read the respound
System.out.println("want to play again?");
if(input.nextLine().equal("no"){//Want to play? BTW: I'm assuming you only enter "no" or "yes"
flag = false;//Don't want to play
}
}
}
And the method:
public static void play(){
//create scanner, variables and a random number
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
//prompt user to enter a number
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
//user enters a number
int guess = scanner.nextInt();
//if user enters -1, the game ends
if(guess == -1){
break;
}
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
//displays the message and the attempt count
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
}
}
}
BTW: you said when the user enters -1, you end the game, then why in the world do you want to ask the user again ?_?
I want the while loop to execute when the user's input is a non-integer value, an integer value less than 1, or an integer value greater than 3. Once the input is valid, I will use it. However, the loop only works when the user inputs a non-integer value. I have gone through the logic and I am still not sure what's wrong.
Code:
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Please enter an integer value 1-3 for the row.");
while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
{
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
row = scnr.nextInt() - 1;
"while" works fine by itself. No "do" is required in this case. Here is your code:
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter an integer value 1-3 for the row.");
while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
{
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
int row = scnr.nextInt() - 1;
You need "do" when you want to execute code at least once and then check "while" condition.
Also each call for nextInt actually requires next int in the input. So, better use it only once like this:
int i;
while((i=scnr.hasNextInt() && (i > 3)) || (scnr.hasNextInt() && (i < 1)) || (!scnr.hasNextInt()))
I am not completly sure about this, but an issue might be calling scnr.nextInt() several times (hence you might give the value to a field to avoid this).
An easy to read solution would be introducing a tester-variable as #Vikrant mentioned in his comment, as example:
System.out.println("Please enter an integer value 1-3 for the row.");
boolean invalid=true;
int input=-1;
while(invalid)
{
invalid=false;
if(scnr.hasNextInt())
input=scnr.nextInt();
else
invalid=true;
if(input>3||input<1)
invalid=true;
if(!invalid)
break;
System.out.println("Your input is not valid.");
System.out.println("Please enter an integer value 1-3 for the row.");
scnr.next();
}
im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i