0
Help me find my error in my code please. Try it in code playground called Friend or Fo.
import java.util.Scanner; class MyClass{ public static void main(String[] args) { Scanner br = new Scanner(System.in); String input; System.out.println("Hello user! I am Java. What is your name?"); input = br.nextLine(); System.out.println("Nice to meet you, "+input +"!"); System.out.println("Would you like to be friends?"); String playerAnswer = br.nextLine (); if(playerAnswer.equalsIgnoreCase("yes")){ System.out.println("Yay!"); } else if (playerAnswer.equalsIgnoreCase("no")){ System.out.println("aww... ok :("); } } }
10 Answers
+ 1
you must decide how you want to save the user's input. for instance, you can't say "input = be.next()"
after the .next you must write the "type" of the input.
and because your variable "input" is a String your code must be "input = be.nextLine()"
there other commands for other types of variables like ".nextInt" or ".nextDouble"
+ 1
and you didn't declare the playerAnswer variable. you can say "String playerAnswer = scan.nextLine()"
+ 1
"String playerAnswer = scan.nextLine();"
java don't know what do you mean by saying "scan." you must either declare a new scanner object using "Scanner scan = new Scanner(System.in);" before that line of code or just replace it by your old scanner object "String playerAnswer = br.nextLine()"
+ 1
remove if near else
ex.
if(playerAnswer.equalsIgnoreCase("yes")){
System.out.println("Yay!");
}
else (playerAnswer.equalsIgnoreCase("no")){
System.out.println("aww... ok :(");
}
+ 1
declare your String "playerAnswer" variable below "input" variable.. you didn't even have to declare two variables in this case ..one can do fine.
0
ok so do i change my input = br.next (); to input = br.nextString(); if so then what next?
0
ops. my bad. it's not .nextString it's .nextLine
0
now my code looks like this:
import java.util.Scanner;
class MyClass{
public static void main(String[] args) {
Scanner br = new Scanner(System.in);
String input;
System.out.println("Hello user! I am Java. What is your name?");
input = br.nextLine();
System.out.println("Nice to meet you, "+input +"!");
System.out.println("Would you like to be friends?");
String playerAnswer = scan.nextLine ();
if(playerAnswer.equalsIgnoreCase("yes")){
System.out.println("Yay!");
}
else if (playerAnswer.equalsIgnoreCase("no")){
System.out.println("aww... ok :(");
}
}
}
but its giving me an error still
0
ok i fixed that but my code only runs till the question "would you like to be friends?" it doesn't give yhe user the option to say yes or no. how do i fix that?
0
i declared my playerAnswer in a string but it still gives me an error, then i tried turning my else if statement to a else statement but it gave me an error. is it possible that code playground only lets the user give imput once? Because no matter what i do, i can fix an error and it gives me four more.