Java For Loop data validation - java

I am currently doing some java excersises in uni and ive been stuck on this one for about 5 hours now! I am practising For loops and have the loop ask 5 times for a number from 1 to 3. When testing, if I enter an invalid selection it carries on and includes the invalid selection as a zero, I have got an error message working when an invalid input is entered but it still carries on until the loop finishes, I know there is a way to return to the beggining of the selection but I cant figure it out.
I have searched everywhere for a solution but cannot find it! I know it cant be much and I'm not back in uni for a few days so I cant ask the lecturer and I would really like to crack on to the next chapter.
Here is my code (I know its probably a bit scrappy!!), thanks, Rob
import java.util.Scanner;
/* this is s a survey of how 5 people sweeten thier coffee */
class coffee
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int person, preference, nothing, sugar, sweetner;
String pluralone = "People dont";
String pluraltwo = "People use";
String pluralthree = "People use";
person = 0;
preference = 0;
nothing = 0;
sugar = 0;
sweetner = 0;
for (person = 1; person <= 5; person++)
{
System.out.println("How do you sweeten your coffee");
System.out.println("1. I Don't");
System.out.println("2. With Sweetner");
System.out.println("3. With Sugar");
preference = input.nextInt();
if (preference != 1 && preference != 2 && preference != 3)
System.out.println("Sorry that is not a valid option");
else if (preference == 1)
nothing++;
else if (preference == 1)
sweetner++;
else
sugar++;
}
System.out.println("Survey Report");
System.out.println("#############");
if (nothing < 2)
{
pluralone = "person doesnt";
}
System.out.println(nothing + " " + " " + pluralone + " sweeten thier coffee");
if (sweetner < 2)
{
pluraltwo = "person uses";
}
System.out.println(sweetner + " " + pluraltwo + " " + "sweetner to sweeten thier coffee");
if (sugar < 2)
{
pluralthree = "person uses";
}
System.out.println(sugar + " " + pluralthree + " " + "sugar to sweeten thier coffee ");
}
}

just ask for the users selection in a while loop so that it doesn't continue until a valid option has been entered, something like:
preference = input.nextInt();
while (preference != 1 && preference != 2 && preference != 3) {
System.out.println("Sorry that is not a valid option");
preference = input.nextInt();
}
alternatively you could decrement person in your if statement to cause another iteration of the for loop, but that's a bit hacky:
if (preference != 1 && preference != 2 && preference != 3) {
System.out.println("Sorry that is not a valid option");
person--;
}

If you change your for loop to this
for (person = 1; person <= 5; person ++)
{
System.out.println ("How do you sweeten your coffee");
System.out.println ("1. I Don't");
System.out.println ("2. With Sweetner");
System.out.println ("3. With Sugar");
preference = input.nextInt();
while(preference != 1 && preference != 2 && preference != 3) {
System.out.println ("Sorry that is not a valid option");
System.out.println ("How do you sweeten your coffee");
System.out.println ("1. I Don't");
System.out.println ("2. With Sweetner");
System.out.println ("3. With Sugar");
preference = input.nextInt();
}
if(preference == 1) {
nothing ++;
} else if(preference == 2) {
sweetner ++;
} else if(preference == 3) {
sugar ++;
}
}
This will fix it

Replace the if/else with an Switch/Case:
preference = input.nextInt();
switch(preference) {
case 1:
nothing++;
break;
case 2:
sweetner++;
break;
case 3:
sugar++;
break;
default:
System.out.println("Sorry, thats not a valid option! Please pick a valid option");
preference = input.nextInt();
person--;
break;
}

I did the while loop and it works, thank you very much Dan. While loops are the next part in the book that im moving onto so its given me a head start too. Many thanks to you and everyone else who replied, a couple of the other things suggested seem a little advanced for me but I know I can always refer to the comments if I need them in the future. Thanks again, Robin.

Related

Problem producing a new random number at the end of HiLo guessing game

I'm creating a HiLo guessing game in Java. Everything I have so far works as intended except at the end when I prompt a user to play again, the random number remains the same from the previous game. How do I make it so the code produces a new random number when the user chooses to play a new game?
int answer = (int)(Math.random() * 100 + 1);
int guess = 0;
int guessCount = 0;
boolean playGame = true;
String restart;
Scanner scan = new Scanner(System.in);
while(playGame == true)
{
while (playGame == true)
{
System.out.println("Enter a number between 1 and 100: ");
guess = scan.nextInt();
guessCount ++;
System.out.println(answer);
if (guess < 1 || guess > 100)
{
System.out.println("You have entered an invalid number.");
guessCount --;
} else if (guess == answer)
{
System.out.println("Correct! Great guess! It took you " + guessCount + " tries!");
break;
} else if (guess > answer)
{
System.out.println("You've guessed too high! Guess again: ");
} else if (guess < answer)
{
System.out.println("You've guessed too low! Guess again: ");
}
}
System.out.println("Would you like to play again? Y/N");
restart = scan.next();
if (restart.equalsIgnoreCase("Y"))
{
playGame = true;
} else if(restart.equalsIgnoreCase("N"))
{
System.out.println("Thank you for playing!");
break;
}
}
The value in the variable 'answer' remains same since variable is a reference to what you have stored / Initialized or Assigned. It does not manipulate in itself. You have to rewrite the code for e.g. answer = (int)(Math.random()*100+1) at the point before game will be restarted or after it.
You're initializing the answer before the loop, it never changes. You have to assign answer a new value when the user chooses to play a new round. This is not the code I'd write, but here it is:
if (restart.equalsIgnoreCase("Y"))
{
answer = (int)(Math.random() * 100 + 1);
}

I can't figure out why the "play again" potion of my code isn't working

So I've been using java for a few weeks now and wanted to try to make my first little game. Everything I had was working fine until I tried adding a play again feature. It looks like it just skipping a small portion of code at the bottom and I can't figure out why.
I've tried moving different parts of the code around but can't figure out why it's not working.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("You have 10 tries to correctly guess a random number between 1 and 10. Good luck! \n"
+ "After you have entered a number, press ENTER to see if you won.");
boolean play;
play = true;
do
{
int tries = 10, triesLeft = 0, triesUsed = 0;
String YorN;
do
{
System.out.print("\nEnter A Number: ");
int numInp = scan.nextInt();
int randomNumber = (int)(Math.random()*9) + 1;
System.out.println("The number was " + randomNumber);
if(numInp == randomNumber) {
System.out.println("\nYou Win! Great job.");
triesLeft = --tries;
triesUsed = 10 - triesLeft;
tries = -1;
} else {
System.out.println("Try Again...");
tries --;
}
}
while( tries > 0);
String playAgain = (" Feel free to play again soon!");
if(tries == 0) {
System.out.println("\nOut of tries :( You lose loser " + playAgain);
}
if(tries == -1) {
System.out.println("\nYou used " + triesUsed + " tries and had "
+ triesLeft + " tries left! :)" + playAgain);
}
System.out.print("\nDo you want to play again? Y or N?");
YorN = scan.nextLine();
if (YorN == ("Y") || YorN == ("y"))
{
play = true;
}
else if (YorN == ("N") || YorN == ("n"))
{
play = false;
}
else {}
} while(play = true);
if (play = false){
System.out.println("\nGood Bye");
}
}
This system doesn't seem to be doing anything when I run the code:
YorN = scan.nextLine();
if (YorN == ("Y") || YorN == ("y"))
{
play = true;
}
else if (YorN == ("N") || YorN == ("n"))
{
play = false;
}
else {}
Here's what I see when I run it:
You Win! Great job.
You used 5 tries and had 5 tries left! :) Feel free to play again soon!
Do you want to play again? Y or N?
Enter A Number:
It doesn't give me a spot to type y or n as it should. If anyone knows why I would really appreciate the help
nextInt() or next() method does not read enter. usually after number
you must be pressing enter which is not readied by above method. a
sort cut to avoid this is keep 1 extra sc.nextLine() method call. it
will read and discard enter.
scan.nextLine();
YorN = scan.nextLine();
if (YorN == ("Y") || YorN == ("y"))
{
play = true;
}
else if (YorN == ("N") || YorN == ("n"))
{
play = false;
}
else {}

Trying to create a quiz with java, but something went wrong. What part of my program did i screw up?

So I'm starting to get the hang of java, and I'm creating a quiz as a mini project. However, when I get to the input part of my program, it breaks down. What's going on?
I also apologize for the formatting
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int score = 0;
int total = 0;
System.out.println("Are you ready for a quiz? (Y/N)");
char answer = in.findInLine(".").charAt(0);
if (answer == 'Y' || answer == 'y');
{
String a = "Barrow";
String b = "Juneau";
String c = "Anchorage";
String d = "Annapolis";
System.out.println("Alright! Lets get right to it!");
System.out.println("What is the Capital of Alaska?");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
char choice = in.findInLine(".").charAt(0);
if (choice == 'B' || choice == 'b')
{
System.out.println("Good Job! 1 point for you!");
score = score + 1;
}
else
{
System.out.println("Incorrect! the answer was actually " + b);
}
String e = "Yes";
String f = "No";
System.out.println("Alright, Next Question! Can you"
+ " store the value 'cat' in a variable of type int?");
System.out.println("A: " + e);
System.out.println("B: " + f);
char secchoice = in.findInLine(".").charAt(0);
if (secchoice == 'A' || secchoice == 'a')
{
System.out.println("Correct! Good Job!");
score = score + 1;
}
else
{
System.out.println("Incorrect");
}
System.out.println("What is the result of 2+2X3-5?");
int result = in.nextInt();
if (result == 3)
{
System.out.println("Correct! Good Job!");
}
else
{
System.out.println("Incorrect");
}
System.out.println("Your total score was " + score + "out of 3");
}
}
}
You are getting a NullPointerException on line 26 because of the way that findInLine() works. Basically, you have used up the one line of input you give it when it starts and the Scanner has advanced passed it to find the next one (which does not exist). In other words, you should use another method for Scanner or use an entirely different approach for getting input.
For example, it is preferable to use this technique
char answer = in.nextLine().charAt(0);
because nextLine() will wait until it has more input.
Of course, you will have to come up with some way to parse the input from the user to make sure that it is valid (i.e. if they can only choose between 'Y' and 'N' you handle the case where they choose neither).
That would look something like
char answer = parseInput(in.nextLine().charAt(0));
where parseInput(String s) is a method you write yourself.
As far as other approaches go, this tutorial from Oracle can help you get started.

Correct use for Switch? Menu option order a Sandwich OR Salad

Good Morning/Afternoon,
Below is the code I've written for my Java class ( As in school homework ). I'm not here trying to get someone to do the homework for me.
My question is: Can the switch/case be used how I have it set?
Prompt user for input 1 or 2. Answer 1 they are getting a sandwich, answer 2 they are getting a salad.
The instructions for this program starts with the customer will order a sandwich or a salad. Then proceed to add toppings for an additional charge and can decline extra toppings as well.Then print out the order and total. The professor specified to use IF statements and the Switch. However, I have a feeling I am missing something because it looks like the Switch is the replacement of the IF statements in the examples I've found on Stack. Thank you for any and all assistance!
import java.util.Scanner;
//loaded scanner to take user input
public class Restaurant
//dude change this, do 3 outputs asking for input 1 input 2 input 3 make those if statements after
{
/* Author:
Date:
Program: create a class that will offer a sandwich for $7.00 with optional three
toppings lettuce, tomato, cheese $1.00 each
or a salad with optional two toppings tomatos, cheese $0.50 each.
*/
public static void main(String[] args)
{
// Declarations sandwich,salad,Sandwich-cheese,Sandwich-tomato,Sandwich-lettuce, salad-cheese, salad-tomato.
double sandwich = 7.00;
double salad = 7.00;
double sandChe = 1.00;
double sandTom = 1.00;
double sandLet = 1.00;
double salChe = .50;
double salTom = .50;
int userInput;
int userInput1;
int userInput2;
int userInput3;
double sandTotal;
double saladTotal;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 1 for a Sandwich or 2 for a Salad");
int userInput = scanner.nextLine();
switch(userInput)
{
case 1: // a sandwich was ordered
System.out.println("Enter 1 for additional topping of lettuce or press 2");
int userInput1 = scanner.nextLine();
System.out.println("Enter 1 for additional topping of cheese or press 2");
int userInput2 = scanner.nextLine();
System.out.println("Enter 1 for additional topping of tomato or press 2");
int userInput3 = scanner.nextLine();
if (userInput1 == 1 && userInput2 == 1 && userInput3 == 1)
{
saladTotal = (sandwich + sandLet + sandChe + sandTom);
System.out.println("Your bill comes to a total of: " + sandTotal + " Thank you, Have a great day!");
if (userInput1 == 1 && userInput2 == 2 && userInput3 == 2)
{
sandTotal = (sandwich + sandLet);
System.out.println("Your bill for a salad with additional tomato toppings comes too: " + sandTotal + " Thank you, Have a great day!");
if (userInput1 == 1 && userInput2 == 1 && userInput3 == 2)
{
sandTotal = (sandwich + sandLet + sandChe);
System.out.println("Your bill for a salad with no additional toppings comes too: " + salad + " Thank you, Have a great day!");
if (userInput1 == 1 && userInput2 == 2 && userInput3 == 1)
{
sandTotal = (sandwich + sandLet + sandTom );
System.out.println("Your bill for a sandwich `enter code here`lettuce and tomato comes too: " + sandTotal + " Thank you, Have a great day!");
if (userInput1 == 2 && userInput2 == 1 && userInput == 1)
{
sandTotal = (sandwich + sandChe + sandTom);
System.out.println("Your bill for a sandwich with cheese and tomato comes too: " + sandTotal + " Thank you, Have a great day!");
if (userInput1 == 2 && userInput2 == 2 && userInput3 == 2)
{
System.out.println("Your bill for a sandwich comes too: " + sandwich + " Thank you, Have a great day!");
}// end if 1
}//end if 2
}//end if 3
}//end if 4
}//end if 5
}//end if 6
}
}
}
// switch case below
case 2: // a salad was ordered
{
System.out.println("Press 1 for additional topping of cheese or press 2");
int userInput1 = scanner.nextLine();
System.out.println("Press 1 for additional topping of tomato or press 2");
int userInput2 = scanner.nextLine();
if (userInput1 == 1 && userInput2 == 2)
{
saladTotal = (salad + salChe);
System.out.println("Your bill comes to a total of: " + saladTotal + " Thank you, Have a great day!");
if (userInput1 == 2 && userInput2 == 1)
{
saladTotal = (salad + salTom);
System.out.println("Your bill for a salad with additional tomato toppings comes too: " + saladTotal + " Thank you, Have a great day!");
if (userInput1 == 2 && userInput2 == 2)
{
System.out.println("Your bill for a salad with no additional toppings comes too: " + salad + " Thank you, Have a great day!");
if (userInput1 == 1 && userInput2 == 1)
{
saladTotal = (salad + salChe + salTom );
System.out.println("Your bill for a salad with Tomato and Cheese toppings comes too: " + saladTotal + " Thank you, Have a great day!");
}//end if 1
}//end if 2
}//end if 3
}//end if 4
}
}// end of class
In general, switch-case statements and if/else blocks are interchangeable. Switch-cases are a bit different because of the use of break (an example below). Though in most cases if-statements are used. I generally use switch-case for handling cases based on enumerations.
Lets say we have an enumeration FoodType:
public enum FoodType {
SANDWITCH,
SALAD,
FRUIT
}
So if i want to ask the user questions based on which food he chooses, I would probably do something like this:
FoodType chosenType = FoodType.SANDWITCH; // can be user input
switch (chosenType) {
case SANDWITCH:
System.out.println("you want cheese?");
case SALAD:
System.out.println("Sauce?");
break;
case FRUIT:
System.out.println("which one?");
break;
default:
throw new IllegalStateException();
}
Note here:
When SANDWITCH is chosen, questions 'you want cheese?' and 'Sauce?' are printed, because there is no break statement.
When FRUIT is chosen, only 'which one?' will be printed.
default would happen, if the user chose somthing else, which is not SANDWITCH or SALAD or FRUIT.
You could of course write this with if statements as well:
if (FoodType.SALAD.equals(chosenType)) {...}
When there are few cases I would rater use simple if statements. Also, the code inside a 'case' should not be overly long/complicated. I think if you want to know when to use which statement; there are for sure some very good blog posts or stackoverflow answers.
// Sidenote: I am aware that the default: is not be reachable code in the example.

A "Stick Game" program in Java not working correctly?

I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();

Categories