if statement for scanner inputs in java [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I want the code to be if entered "shoot" then it'll print "Nice, you killed the zombie"
and if the user inputs "don't shoot" then it'll print "oh no, the zombie killed you"
this is what I've done so far but it won't print out anything.
public static void main(String[] args) {
System.out.println("ZOMBIE AHEAD!");
Scanner kb = new Scanner(System.in);
String action1 = "shoot";
String action2 = "don't shoot";
String str = kb.nextLine();
if (str == action1) {
System.out.println("Nice, you killed the zombie!");
} else if (str == action2) {
System.out.println("Oh no, the zombie killed you!");
}
}
}

Use the following:
public static void main(String[] args) {
System.out.println("ZOMBIE AHEAD!");
Scanner kb = new Scanner(System.in);
String action1 = "shoot";
String action2 = "don't shoot";
String str = kb.nextLine();
if (str.equals(action1)) {
System.out.println("Nice, you killed the zombie!");
} else if (str.equals(action2)) {
System.out.println("Oh no, the zombie killed you!");
}
}
}
You have to use .equals() to compare Strings.

Related

why wont my while loop break [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I can not figure out why my while loop won't break and it just keeps running I have tries making Lc 10 and I tried return but nothing will end the loop.
import java.util.Scanner;
public class BirthdayReminder
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] BDay = new String[10];
String[] friend = new String[10];
int Lc = 0;
String i;
while(Lc < 10) {
System.out.println("enter a friends name or zzz to quit");
i = input.nextLine();
if(i == "zzz") {
break;
}
else if(i != "zzz"){
friend[Lc] = i;
System.out.println("enter their birthday.");
i = input.nextLine();
BDay[Lc] = i;
Lc++;
return;
}
}
System.out.println("hi");
}
}
You need to check string equality using equals(), not ==. Neither block of code inside the if is getting entered, so Lc is never incremented.

inputmismatch exception [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
import java.util.*;
public class NGG {
static Scanner numberEntered;
static Scanner userInput = new Scanner(System.in);
static int guessedNumber;
static int randomNumber = (int) (Math.random()* 11);
static Scanner reply;
static String answer;
public static void main(String[] args) {
guessChecker(guessedNumber);
}
public static void guessChecker(int userGuess) {
while (userGuess != randomNumber) {
intro();
userGuess = intChecker();
if (userGuess == randomNumber) {
System.out.println("Congradulations!");
System.exit(0);
} else {
System.out.println("That was Incorrect!");
delay(1000);
retryChecker(reply, answer);
}
}
}
public static int intChecker() {
try {
return userInput.nextInt();
} catch (InputMismatchException e) {
userInput.next();
System.out.println("Your answer was Invalid!");
delay(2000);
retryChecker(reply, answer);
return 0;
}
}
public static void retryChecker(Scanner userReply, String userChoice) {
System.out.println("Would you like to try again?");
userReply = new Scanner(System.in);
userChoice = userReply.nextLine();
if (userChoice.equalsIgnoreCase("yes") || userChoice.equalsIgnoreCase("y")) {
guessChecker(guessedNumber);
} else {
System.exit(0);
}
}
public static void intro() {
System.out.println("I'm thinking of a number in my head...");
delay(1000);
System.out.print("Try to guess it: ");
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {}
}
}
and here's my problem:
I have a number guessing game, every time it says "try to guess it:"
it usually will let you type in a guess, unless your previous guess was a string, letter or number, followed by a space and then another string, letter or number, then instead of letting you write your own guess it will just print out "your answer was Invalid" and move on with the program.
How would I fix this? so that the userInput can also be a string, letter or number, followed by a space and then another string, letter or number and it'll move one with the program normally.
The problem is in the intChecker().
public static int intChecker() {
try {
return userInput.nextInt();
} catch (InputMismatchException e) {
userInput.nextLine(); // -> changed from .next() to nextLine()
System.out.println("Your answer was Invalid!");
delay(2000);
retryChecker(reply, answer);
return 0;
}
}
The reason is when you use next() it returns string when it encounters space or EOF.
So when you give input it's me!, first checks it's and says it's wrong. It asks whether to continue or not next. When you press y to goes to the method and reads the remaining string me!.
Here you have used different scanners userInput and userReply. As the userInput is static, the object doesn't dies and has the remaining string in it which is me! after returning its.
So using nextLine() returns the whole string.
For more info on how they both work, check out my other answer
I hope it helped.

If else statement not working JAVA [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
The line starting the if statement is causing me issues. When I run it it will ask me my gender, I say boy and it says 'you cannot enter'. It doesnt even ask for the age!
import java.util.Scanner;
class Apples {
//////Main Method
public static void main (String[] args) {
if (Apples.getGender() == "boy" && Apples.getAge() > 17) {
System.out.printf("You can enter");
}
else {
System.out.printf("You cannot enter");
}
}
/////Two Methods
public static String getGender() {
Scanner newGender = new Scanner(System.in);
System.out.println("What gender are you?");
String genderMF = newGender.nextLine();
return genderMF;
}
public static int getAge() {
Scanner newAge = new Scanner(System.in);
System.out.println("What age are you?");
int ageMF = newAge.nextInt();
return ageMF;
}
}
You have to compare strings with .equals function in Java, not with ==.
s1.equals(s2);

DoWhile in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
When I try to do a dowhile loop in Java with a string it just terminates the program without an error not giving me a chance to enter if I would like to continue. How do I make my program loop if requested using a string?
public static void main(String args[]) {
Scanner user_input = new Scanner (System.in);
Maths math = new Maths();
double firstNum, secondNum;
String calcAgain = null;
do{
System.out.println("Enter First Number: ");
firstNum = user_input.nextDouble();
System.out.println("Enter Second Number: ");
secondNum = user_input.nextDouble();
System.out.println("Please select an operation! (+,-,*,/)");
String operation = user_input.next();
if (operation.equals("+")) {
System.out.println(math.add(firstNum, secondNum));
}
else if (operation.equals("-")) {
System.out.println(math.subtract(firstNum, secondNum));
}
else if (operation.equals("*")) {
System.out.println(math.multiply(firstNum, secondNum));
}
else if (operation.equals("/")) {
System.out.println(math.divide(firstNum, secondNum));
}
else {
System.out.println("Invalid Function!");
}
System.out.println("Would you like to do another calculation? ");
calcAgain = user_input.nextLine();
}while(calcAgain == "yes");
You might want to look at string operations for equality. The condition while(calcAgain == "yes") will not execute ever, because you are comparing the object itself. String equality is done with the .equals() function.

Why is this if statement not performing how I want it too? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am making a Game of Life program, early stages of it. When I run the program and get to the "Do you want to make..." and i input "y", it will go to the else, print my test statement of test3, and end the program. What am I overlooking?
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String userInput = "";
char[][] initialGrid = new char[25][75];
char[][] world = makeInitialGrid(kb, userInput, initialGrid);
printGrid(world);
userInput = "y";
while (userInput == "y"){
System.out.println("Do you want to make a new generation? (y) yes (n) no");
userInput = kb.nextLine();
System.out.println(userInput);
if (userInput == "y"){
System.out.println("test1");
int numOfNeighbors = findNeighbors(world, 6, 2);
System.out.println("test2");
System.out.println(numOfNeighbors);
//makeNewGeneration(world);
} else {
System.out.println("test3");
break;
}
}
kb.close();
For string comparisons in Java, you need to use String#equals, not ==. Try if (userInput.equals("y")) { ... instead.

Categories

Resources