The sequence of events should be:
1) I enter two.
2) I am prompted to choose a name.
3) I choose either Washington/ Franklin/ Hamilton.
4) I'm asked which denomination does this name appear on.
5) I give the answer.
However, when I enter Washington for part three - I am told that is an invalid number. I cannot see why this would be.
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Type 1 to enter a denomination, 2 to enter a last name");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
if(x==1){
System.out.println("Choose a denomination");
int y = in.nextInt();
in.nextLine();
if(y==1){
System.out.println("Which person appears on the 1 bill?");
String answer = in.nextLine();
if(answer.equals("Washington")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y==10){
System.out.println("Which person appears on the 10 bill?");
String answer = in.nextLine();
if(answer.equals("Hamilton")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y==100){
System.out.println("Which person appears on the 100 bill?");
String answer = in.nextLine();
if(answer.equals("Franklin")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else{
System.out.println("That is an invalid number.");
}
}
else if(x==2){
System.out.println("Choose a name");
String y = in.nextLine();
in.nextLine();
if(y.equals("Washington")){
System.out.println("Which denomination does this name appear on?");
int answer = in.nextInt();
if(answer==1){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y.equals("Hamilton")){
System.out.println("Which denomination does this name appear on");
int answer = in.nextInt();
if(answer==10){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y.equals("Franklin")){
System.out.println("Which denomination does this name appear on");
int answer = in.nextInt();
if(answer==100){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else{
System.out.println("That is an invalid number.");
}
}
}
The problem is with the x==2 segment. x==1 works fine.
The problem does not lies with the seemingly extra in.nextLine().
I will advise you to change all your in.nextInt() to in.nextLine() followed by parsing them to the actualy type such as int
Example:
int answer = Integer.parseInt(in.nextLine());
Reason for the suggested change: When you use nextInt(), there is a tendency that nextline still lingers around there until you do an additional nextLine() to clear it.
To prevent this sort of problems, it is advisable to receive all inputs with nextLine(), then parse it to the actual type (int, double..etc).
This is also how Microsoft deals with integer input in C#.
Edited Working Codes:
public static void main(String[] args) {
System.out.println("Type 1 to enter a denomination, 2 to enter a last name");
Scanner in = new Scanner(System.in);
int x = Integer.parseInt(in.nextLine());
if(x==1){
System.out.println("Choose a denomination");
int y = Integer.parseInt(in.nextLine());
in.nextLine();
if(y==1){
System.out.println("Which person appears on the 1 bill?");
String answer = in.nextLine();
if(answer.equals("Washington")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y==10){
System.out.println("Which person appears on the 10 bill?");
String answer = in.nextLine();
if(answer.equals("Hamilton")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y==100){
System.out.println("Which person appears on the 100 bill?");
String answer = in.nextLine();
if(answer.equals("Franklin")){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else{
System.out.println("That is an invalid number.");
}
}
else if(x==2){
System.out.println("Choose a name");
String y = in.nextLine();
//in.nextLine();
if(y.equals("Washington")){
System.out.println("Which denomination does this name appear on?");
int answer = Integer.parseInt(in.nextLine());
if(answer==1){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y.equals("Hamilton")){
System.out.println("Which denomination does this name appear on");
int answer = Integer.parseInt(in.nextLine());
if(answer==10){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else if(y.equals("Franklin")){
System.out.println("Which denomination does this name appear on");
int answer = Integer.parseInt(in.nextLine());
if(answer==100){
System.out.println("That is correct");
}
else{
System.out.println("That is incorrect");
}
}
else{
System.out.println("That is an invalid number.");
}
}
}
String y = in.nextLine();
in.nextLine();
if(y.equals("Washington")){
You're calling in.nextLine() one too many times. Remove that second line.
When you do String y = in.nextLine(), the next token is the leftover newline from the previous nextInt() call, so y ends up being equal to \n.
Place a call to nextLine() after you use nextInt():
int x = in.nextInt();
in.nextLine();
Afterwards you should be able to call nextLine only once when getting the user input:
String y = in.nextLine();
if(y.equals("Washington")){
You have to skip the line after nextInt() then take user input(in y==2 case) because nextInt() doesnot consume the whole line it consume the token.
in.nextLine();
String y = in.nextLine();
with your code the in.nextLine() in String y = in.nextLine(); is reading the same line where you entered value of x getting the value y to be "" and hence the output "That is an invalid number"
Related
This question is similar to a question I had previously about loops taking my enter key as input. For my class, I need to write a program that is a number-guessing game that whenever the user enters correctly, the loop ends. But I run into the problem as the enter key being taken as input. How can I stop this from occurring? Here is my code I have so far.
String secretNumber = "6";
String guess = "";
while(!guess.equals(secretNumber)) {
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
if(guess == "6") {
System.out.println("You Win!");
}
else if(guess == "5") {
System.out.println("Try again!");
}
else if(guess == "4") {
System.out.println("Try again!");
}
else if(guess == "3") {
System.out.println("Try again!");
}
else if(guess == "2") {
System.out.println("Try again!");
}
else if(guess == "1") {
System.out.println("Try again!");
}
else if(guess == "7") {
System.out.println("Try again!");
}
else if(guess == "8") {
System.out.println("Try again!");
}
else if(guess == "9") {
System.out.println("Try again!");
}
else if(guess == "10") {
System.out.println("Try again!");
}
else {
System.out.println("You did not enter a number between 1 and 10");
}
}
}
}
If you use == operator it doesn't compare the value of the string. So to check if a string's value equals to another, you must use string.equals(anotherString) method. In your case your code should be like :
String secretNumber = "6";
String guess = "";
while(!guess.equals(secretNumber)) {
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
if(guess.equals("6")) {
System.out.println("You Win!");
}
else if(guess.equals("5")) {
System.out.println("Try again!");
}
..........
Also to refactor the code this version is more readable and simpler.
String secretNumber = "6";
String guess = guess = scan.next();
System.out.println("Guess a number between 1 and 10");
while(!guess.equals(secretNumber)) {
if(guess.equals(secretNumber)) {
System.out.println("You Win!");
break;
}
else{
System.out.println("Try again!");
}
First Strings are compared by equals second you need to learn how to reduce your code because while(!guess.equals(secretNumber)) will continue until 6 is entered so it will print anything inside it you we just print Try Again
public class GuessIt{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String secretNumber = "6";
String guess = "";
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
while(!guess.equals(secretNumber)) {
System.out.println("Try again");
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
}
System.out.println("You guessed it");
}
}
While your code is not the best way to implement a guessing game, I will play along if it helps you.
I don't entirely know what you mean by the enter key being taken as input. Are you typing a value into the terminal before you press enter?
String secretNum = 6;
String guess = "";
System.out.println("Guess a number between 1 and 10");
while(!guess.equals(secretNum)) {
guess = scan.next();
if(Integer.parseInt(guess)>10 || Integer.parseInt(guess)<1) {
System.out.println("Re-enter a number between one and ten");
}
}
System.out.println("You guessed it!");
so i made a game, in which user needs to guess the random number or letter. I want to make it so that when the user writes 'end game' during the game (when he guesses the number), he is being redirected to the menu (using the main(args); method). In fact, String value cannot be writen in int input. So when i write 'end game' during the game cycle, it just crashes. What should i do?
Heres code of my game:
import java.util.Scanner;
public class TwoGames {
public static void main(String[] args) { // main menu
Scanner scan = new Scanner(System.in);
System.out.println("Choose the game\n Type 'letter' or 'number' to choose the game");
String UserAnswer = "";
UserAnswer = scan.next();
if (UserAnswer.equalsIgnoreCase("number")) {
number(args);
}else if(UserAnswer.equalsIgnoreCase("letter")){
letter(args);
}
scan.close();
}
public static void letter (String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";
int numberOfTries = 0;
do {
System.out.println("Guess the Letter");
char randomLetter = (char) (Math.random() * 26 + 65);
char enteredLetter = 0;
while(true){
enteredLetter = Character.toUpperCase(scan.next().charAt(0));
numberOfTries = numberOfTries + 1;
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
break;
}
else if(enteredLetter>randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too high");
}
else if(enteredLetter<randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too low");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
public static void number(String[] args) { //heres the number guessing game
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";//variable to stop game
do {
int theNumber = (int)(Math.random() * 100 + 1);
int numberOfTries = 0;
do {
int guess = 0;
while (guess != theNumber) {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt();
numberOfTries = numberOfTries + 1;
if (guess < theNumber)
System.out.println(guess + " is too low. Try again.");
else if (guess > theNumber)
System.out.println(guess + " is too high. Try again.");
else {
System.out.println(guess + " is correct. You win!");
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
}
}
} while (Stop.equalsIgnoreCase("end game"));
main(args);// this sends user to main menu
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
}
I am novice programmer, so yeah, thats might be a dumb question, because im learning. Anyway, any help and explanation would be useful.
To solve this problem, you should input a string, check if it equals to "End game" message and if not continue your code.
For example, replace this line:
guess = scan.nextInt();
In this code:
String input = scan.next();
if(input.equals("End game")){
main(args);
return;
}
guess = Integer.parseInt(input);
That code get a String input called input, check if he equals to "End game" and if not continue your guess loop.
import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.
This is the output of the program
I was able to do till to get this result by doing this program below
import java.util.Scanner;
public class aLittleQuiz {
public static void main(String[] args) {
// declaring varibles
String quizStart;
int quizAns1, quizAns2, quizAns3;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
} else {
System.out.println("");
}
// if (quizAns == 3 && quizAns == ) {
// }
}
}
but how I can program this part?
"Overall, you got 2 out of 3 correct.
Thanks for playing!"
Declare a variable like int marks and increment it by one inside if\else block(which made for correct answer). And at the end print
System.out.println("Overall, you got" +marks+" out of 3 correct. Thanks for playing!");
Assuming your no of question is fixed( 3 )
String quizStart;
int quizAns1, quizAns2, quizAns3;
int marks=0;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
++marks;
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
++marks;
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
++marks;
} else {
System.out.println("");
}
System.out.println("Overall, you got " +marks+" out of 3 correct. Thanks for playing!");
I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here