This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I know this code is terribly written (first day of Java and programming), but I am writing a code in Java that will take an input from the user (the dice) and produce a random number from that dice. I have added a while loop to ask if the user would like to restart the program, but everytime I run it it tells me that it is an invalid input before I have inputted anything. Please help.
import java.util.Scanner;
import java.util.Random;
public class Java {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String restartChoice = "y";
while (restartChoice == "y" || restartChoice == "Y"){
int choice;
System.out.println("Please choose which dice you would like to roll. 4/6/12 ");
choice = input.nextInt();
while (choice != 4 && choice != 6 && choice != 12){
System.out.println("That is not a valid input, please try again... ");
choice = input.nextInt();
}
Random rand = new Random();
int value = rand.nextInt(choice) + 1;
System.out.print("You chose to roll the ");
System.out.print(choice);
System.out.print(" sided dice. The number is ");
System.out.println(value);
System.out.println("Would you like to restart? Y/N ");
restartChoice = input.nextLine();
while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){
System.out.println("That is not a valid input. Please try again. ");
restartChoice = input.nextLine();
}
}
}
}
Scanner#nextInt() does not consume newline characters resulting in the character being passed through to the loop
while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){
System.out.println("That is not a valid input. Please try again. ");
restartChoice = input.nextLine();
}
Add a nextLine statement after every nextLine statement to consume this newline character.
choice = input.nextInt();
input.nextLine();
Also the == operator compares Object references. Use String#equals:
while (restartChoice.equals("y") || restartChoice.equals("Y")) {
to protect against NullPointerException you can place the String literal first. Also equalsIgnoreCase can be used to give a shorter if statement expression:
while ("y".equalsIgnoreCase(restartChoice)) {
This change is required in for while statement expression.
Use String.equals(otherString)
Strings are objects, not primitives. You are currently comparing the addresses of your strings.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
I've created a program that asks students' names, years, and the courses they have. The idea is if I press y(yes) it should loop back and ask another student, but in my case, if I enter y, it doesn't ask me. Any tips for beginners?
import java.util.Scanner;
public class Practice{
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
String studentName, another;
int year,choice;
do{
System.out.println("Student name: ");
studentName = scan.nextLine();
System.out.println("Year: ");
year = scan.nextInt();
System.out.println("\t1.BSIT \n\t2.BSCS \n\t3.BSCpE \n\t4.BSN");
System.out.print("Choice: ");
choice = scan.nextInt();
scan.nextLine();
if(choice == 1) {
System.out.println("Course is BSIT");
}
else if(choice == 2 ) {
System.out.println("Course is BSCS");
}
else if(choice == 3 ) {
System.out.println("Course is BSCpE");
}
else if(choice == 4) {
System.out.println("Course is BSN");
}
System.out.println("Another Student? type Y if yes, and N if no");
another = scan.nextLine();
}while((another == "Y") || (another == "y"));
if ((another == "N") || (another == "n"))System.out.println("You are the last student.");
}
}
My suggestion would be to set 'another' to be a boolean
boolean anotherStudent = false;
do
{
if((another.equals("Y") || (another.equals("y") ){
anotherStudent = true;
else if((another.equals("N") || (another.equals("n") ){
anotherStudent = false;
}while(!anotherStudent)
I would also do a else if for if they dont enter a Y or an N.
you must change the comparison operator == to string equals ex
another.equals("Y"). or u cant site the same case
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
public static void getSolve(Scanner s) {
boolean validInput = false;
while(validInput == false) {
System.out.println("Would you like to try to solve the word? (yes or no)");
String input = s.nextLine();
if(input == "yes" || input == "Yes") {
validInput = true;
System.out.println("Enter your full guess: ");
String guess = s.nextLine();
if (guess == secretWord) {
System.out.println("You guessed the word!");
displayString = secretWord;
}
else {
System.out.println("Sorry, that is not the word");
NUM_LIVES --;
}
}
else if (input == "no" || input == "No") {
validInput = true;
}
else {
System.out.println("Sorry, that is not a valid input");
}
}
}
This is the code that I am using for a solve method for a java project for my class in which I am coding a hangman game. I am trying to add a feature that asks the user if they would like to try to solve the word and then checks to see if they got that guess correct. Right now what is happening is that no matter what the user puts in, even if it is "yes" or "no", the program thinks that it is an invalid input and asks the question again, putting the code into an infinite loop. I'm not quite sure how to fix this and I'm not sure what I am doing wrong. Any help is greatly appreciated!
Looks good to me except this one:
input == "yes" || input == "Yes"
should be
"yes".equalsIgnoreCase(input)
And others:
guess == secretWord -> guess.equals(secretWord)
input == "no" || input == "No" -> "no".equalsIgnoreCase(input)
You need to compare strings using .equals in java.
if(input.equals("yes") || input.equals("Yes"))
You can also use .equalsIgnoreCase() so you don't have to write all forms of the word yes.
.equals() is used to compare objects.
The code below is from a game in which I need to generate 2 random numbers in java, and the user is presented with one of them. They then have to guess if the second number is higher or lower than the first. I created a while loop to check for errors in their input and the loop is executed even if the condition is not true. Entering H means their guess is the next number is higher, and L means they believe its lower
// Input
System.out.println ("Do you think the second number is higher or lower (enter 'H' or 'L' respectively): ");
char userGuess = Character.toUpperCase(input.next().charAt(0));
// Input error check (and immediate output of second number)
while (userGuess != 'H' || userGuess != 'L') {
System.out.println ("Sorry, I didn't understand that. Please try again: ");
userGuess = Character.toUpperCase(input.next().charAt(0));
}
System.out.println ("The second number was " + secondRandomNumber);
Use && not ||. Of course it's not going to be H or not going to be L
while (userGuess != 'H' && userGuess != 'L') {
System.out.println ("Sorry, I didn't understand that. Please try again: ");
userGuess = Character.toUpperCase(input.next().charAt(0));
}
Hey guys I'm trying to create a loop until a correct character choice is entered by the user. When I enter a wrong choice I get the error java.lang.NullPointerException. It might be with the way I'm inputing but I don't want to change that if I don't have to. choice is a private member of the class.
char wf() {
Scanner input = new Scanner(System.in);
System.out.println("What is your choice? (x/o)");
choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') {
System.out.println("You must enter x or o!");
choice = input.findInLine(".").charAt(0);
}
return choice;
}//end wf
Change the function as below (I have tested this code):
char wf() {
Scanner input = new Scanner(System.in);
System.out.println("What is your choice? (x/o)");
char choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') {
System.out.println("You must enter x or o!");
choice = input.next().charAt(0);
}
return choice;
}//end wf
Check input.findInLine(".") to see if it null. If you don't have the expected input, it won't return anything..
change your code like below
char wf() {
Scanner input = new Scanner(System.in);
System.out.println("What is your choice? (x/o)");
if(input.findInLine(".") !=null){
choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') {
System.out.println("You must enter x or o!");
choice = input.findInLine(".").charAt(0);
}
}
return choice;
}//end wf
In the code below, when I input anything other than an integer value the code does not ask for my input again and just loops the string outputs infinitely. A little help...
int choice = 0;
while(choice == 0)
{
try
{
System.out.println("Start by typing the choice number from above and hitting enter: ");
choice = input.nextInt();
}
catch(Exception e)
{
}
if ((choice == 1) || (choice == 2) || (choice == 3))
{
break;
}
else
{
System.out.println("Invalid choice number. Please carefully type correct option.");
choice = 0;
}
}
When you input a non-integer it will not be consumed. You need to scan past it. This can be done by, for example, adding a input.nextLine() statement to your catch block. This will consume the invalid input and allow your program to read new data.
This will solve your problem:
catch(Exception e)
{
input.nextLine(); // Consume the invalid line
System.out.println("Invalid choice number. Please carefully type correct option.");
}
You could also read the line as a string and try to parse it as a number using Scanner.nextLine and Integer.parseInt, but I prefer using nextInt for integers. It makes the purpose of the code more clear (in my opinion).
When nextInt is used and the next input is not an int, it will throw an exception but not consume the data, i.e. the next call will return immediately because the data is still present.
You can fix this by calling the skip method with a pattern like [^0-9]* to skip all invalid input. Then an input like "aaa3" would work. If you want to ignore everything, use .* as pattern.
The trouble is that you are not consuming the remaining data in the stream. I solved it with the following code, although you will want to document you code better before you use it in a program:
int choice = 0;
while(choice == 0)
{
try
{
System.out.print("Start by typing the choice number from above and hitting enter: ");
choice = input.nextInt();
}
catch(Exception e)
{
input.next();
System.out.println("Invalid choice number. Please carefully type correct option.");
}
if ((choice == 1) || (choice == 2) || (choice == 3))
{
break;
}
choice = 0;
}
You can simplify and reduce your code as follows:
int choice;
System.out.println("Start by typing the choice number from above and hitting enter: ");
while(true)
{
try {
choice = input.nextInt();
if ((choice == 1) || (choice == 2) || (choice == 3))
break;
} catch(InputMismatchException e) { // handle only the specific exception
input.nextLine(); // clear the input
}
System.out.println("Invalid choice number. Please carefully type correct option.");
}
Are you using Scanner(system.in); from the import java.util.Scanner; package?
Try adding input.nextLine(); in the catch to clear the value to stop the infinite loop.
public static void main(String[] args) {
int choice = 0;
Scanner input = new Scanner(System.in);
while(choice == 0)
{
try
{
System.out.println("Start by typing the choice number from above and hitting enter: ");
choice = input.nextInt();
}
catch(Exception e)
{
input.nextLine();
System.out.println("Invalid choice number. Please carefully type correct option.");
}
if ((choice == 1) || (choice == 2) || (choice == 3))
{
break;
}
else
{
System.out.println("Invalid choice number. Please carefully type correct option.");
choice = 0;
}
}
}
Looks like in the line choice = input.nextInt();
choice value is always 0. Print choice soon after that.
Also for non integer value add a condition to break from the loop.