why cant i get out of this while loop? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
our project basically involves reading files about the premier league and returning 1. outcomes of games played, 2. fixtures yet to be played and 3. the leaderboard(table). I'm displaying a menu in the command line and also taking in the user input from there. I'm using a while loop to match the userinput with what output to display but I wanted to say if they don't enter 1,2 or 3 that there's an error and to display the menu again and ask them to enter another input. However now if I do enter 1,2 or 3, it doesn't display my results I can't get out of the while loop. Can anyone help me? This is my code!
while(userInput == false)
{
Scanner input = new Scanner(System.in);
String pattern = "[1-3]{1}";
String userChoice;
System.out.println(menuOptions);
userChoice = input.nextLine();
if(userChoice == "1")
{
System.out.print(outcomesResults);
userInput = true;
}
if(userChoice == "2")
{
System.out.print(fixturesResults);
userInput = true;
}
if(userChoice == "3")
{
System.out.print(leaderboardResults);
userInput = true;
}
else if(!userChoice.matches(pattern))
{
System.out.println();
System.out.println("Error: unidentified selection. Please choose 1,2 or 3");
userInput = false;
}
}

If you want to compare the String value, you should use equals():
if (userChoice.equals("1")) {
// do something
}

Related

how can you repeat a statement if a condition is not reached in java [duplicate]

This question already has answers here:
Loop user input until conditions met
(3 answers)
Closed 2 years ago.
I'm trying to make a program that asks you to input some data as a string then if the string is more than 6 characters long it will ask you to do it again until you input an answer with less than 6 characters then moves on to the next question, how can i do this?
You can do it without a break, using a boolean variable.
boolean flag = true;
String answer;
while(flag){
System.out.println("Enter a string with less than 6 characters:");
answer = input.nextLine();
if(answer.length() > 6){
System.out.println(answer + " has more than 6 characters. Please try again!");
}else {
flag = false;
}
}
I would recommend using a while loop that is always true, then break when condition is met.
while (true) {
System.out.println("Enter answer: ");
String answer = sc.nextline();
if(!answer.length() > 6) {
// do stuf
break;
}
}

How to end do while loop with user input with if statement [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
boolean a = true;
do {
Scanner input = new Scanner(System.in);
System.out.println("Press any on keyboard:");
String keys = input.nextLine();
System.out.println("You pressed:");
System.out.println(keys);
System.out.println("Your hash is:");
String B = "#B";
String hash = B+keys;
System.out.println(hash);
System.out.println("To end loop press f");
//End Loop
Scanner exit = new Scanner(System.in);
String end = exit.nextLine();
if (end=="f") {
a=false;
}
}
while(a);
}
}
I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}

Repeating the program for the user [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am a beginner in Java, I have written a simple input java program. I am giving the user the option to repeat the program with a do while, however it's not properly functioning. Can someone point my mistake please?
public static void main(String args[]){
char repeat = 0;
Scanner input = new Scanner(System.in);
do{
String word = null;
boolean oneWord = false;
while(!oneWord){
System.out.println("Please enter a word: ");
try{
word = input.nextLine().toLowerCase();
word= word.trim();
int words = word.isEmpty() ? 0 : word.split("\\s+").length;
if(words==1 && word.length()>1 && word.length()<100){
System.out.println("Success");
oneWord = true;
System.out.println("Continue(Y/N)");
repeat = input.next().charAt(0);
}else{
System.out.println("Failure.");
}
} catch (Exception e) {
System.out.println("Exception occurred");
}
}
}while(repeat=='Y'|| repeat=='y');
input.close();
}
I would suggest you using nextLine() function of Scanner class instead of next() function.
See the difference here
Even tho its a duplicate, have a look at the line
repeat = input.next().charAt(0);
and change it to
repeat = input.nextLine().charAt(0);
This will solve your problem. For further information regarding the problem, read the duplicate link.

Beginner here - java IF ELSE used with text [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
How can I read input from the console using the Scanner class in Java?
(17 answers)
Closed 5 years ago.
I just started reading about JAVA and I want to make a little program that when using Scanner is I type "yes", "no" or just something random I will get different messages.The problem if with the lines:
if (LEAVE == "yes") {
System.out.println("ok, lets go");
if (LEAVE == "no") {
System.out.println("you dont have a choice");
} else {
System.out.println("it's a yes or no question");
I receive the error : Operator "==" cannot be applied to "java.util.scanner", "java.lang.String". I saw on a site that it would be better if I replaced "==" with .equals,but I still get an error..
Help please :S
Code below:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner LEAVE = new Scanner(System.in);
System.out.println("do you want to answer this test?");
LEAVE.next();
System.out.println("first q: would you leave the hotel?");
LEAVE.next();
if (LEAVE == "yes") {
System.out.println("ok, lets go");
}
LEAVE.nextLine();
if (LEAVE == "no") {
System.out.println("you dont have a choice");
LEAVE.nextLine();
} else {
System.out.println("it's a yes or no question");
}
}}
Scanner LEAVE = new Scanner(System.in);
Implies that LEAVE is Scanner class object. Right.
if (LEAVE == "yes")
You are comparing the Scanner type object with String type object and hence you are getting
Operator "==" cannot be applied to "java.util.scanner", "java.lang.String"
Now consider
LEAVE.next();
you are calling next() which belongs to LEAVE object. That next function is suppose to read a value and return that to you. So what you do is receive this value in another String type object and then further compare it to 'YES' or 'NO' or whatever.
String response = LEAVE.next()
if(response.equalsIgnoreCase("yes")){
// do something
}else if(response.equalsIgnoreCase("no")){
// do something else
}
More about Scanner class
GeeksForGeeks

Else-if statement not working properly when evaluating Strings [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am writing a program for a school assignment to create one string array of 3 riddles and another string array of 3 answers to each riddle. However when I input the correct answer to the riddle it keeps on showing the else part of the if-else statement. Here's my code:
import java.util.Scanner;
import java.util.Random;
public class riddleProgram {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int index;
int chosenRiddles = rand.nextInt(2);
//declares the riddles in the program as well as choosing a random riddle from the three presented
String[]riddle = new String[3];
riddle[0] = "What starts with a T, ends with a T, and has T in it?";
riddle[1] = "The day before two days after the day before tommorrow is Saturday. What day is it today?";
riddle[2] = "What grows up while growing down?";
//declares the answers to the riddles
String[]answer = new String[3];
answer[0] = ("teapot");
answer[1] = ("friday");
answer[2] = ("goose");
//asks user to enter guessed answer for the randomly presented riddle
for (index=0; index<3; index++); {
System.out.println(riddle[chosenRiddles]);
System.out.print("Enter your answer for the presented riddle (lowercase): ");
String inputtedAnswer = input.nextLine();
//if user inputs right answer, congratulates user
//if user inputs incorrect answer, tells user the correct answer
if (inputtedAnswer == answer[chosenRiddles]) {
System.out.println("Congratulations, you have gotten the right answer!"); }
else {
System.out.println("Sorry you had the wrong answer. The right answer is " + answer[chosenRiddles] + ".");}
}
}
}
never compare strings with ==
you should always use .equals( )
if (answer[chosenRiddles].equals(inputtedAnswer)) {
you should also try to have the constant value (the one that will always exist) on the left of these, to prevent possible NullPointerExceptions.

Categories