Consider the following program, which is supposed to repeatedly ask the user \"A
ID: 639846 • Letter: C
Question
Consider the following program, which is supposed to repeatedly ask the user "Are we there yes?" until the user enters yes (and in that case, it should print "Hooray!"). But there's a problem with this program. What will happen when this program is run? And how would you fix the program so that it does what it's suppose to?
import java.util.Scanner;
public class roadtrip {
public static void main(String[] args) {
Scanner s;
s = new Scanner(System.in);
System.out.println("Are we there yet?");
String userInput = s.nextLine();
while(userInput != "yes") {
System.out.println("Are we there yet?");
userInput = s.nextLine();
}
System.out.println("Hooray!");
}
}
Explanation / Answer
import java.util.Scanner;
public class roadtrip {
public static void main(String[] args) {
Scanner s;
s = new Scanner(System.in);
System.out.println("Are we there yet?");
String userInput = s.nextLine();
//while(userInput != "yes") {
while(!(userInput.equals("yes"))){
System.out.println("Are we there yet?");
userInput = s.nextLine();
}
System.out.println("Hooray!");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.