'I wrote a code in java and i got error for some reason [duplicate]
/*The code should pick up your gander (m\f)
you have to fill in your results.
If you are female you fill in seven results and if you are male you fill ten.
At the end, the code writes you the amount of all your results together
*/
import java.util.*;
public class gameScore {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
int i=0, place=0, finalScore=0;
//askes you for your gender until you inserting valid answer
while (i==0) {
System.out.println("Please insert your gender (M\F): ");
char gender = scanner.next().charAt(0);
if (gender=='f' || gender=='F' || gender=='m' || gender=='M') {
i++;
}
}
//if you inserted m\M:
if (gender == 'm' || gender == 'M') {
for (i=0; i<10; i++) {
System.out.println("Please insert your score in game number " + (i+1) + ": ");
int score = scanner.nextInt();
finalScore += score;
}
}
//if you inserted f\F:
if (gender == 'f' || gender == 'F') {
for (i=0; i<7; i++) {
System.out.println("Please insert your score in game number " + (i+1) + ": ");
int score = scanner.nextInt();
finalScore += score;
}
}
//prints the final score
System.out.println("your final score is: " + finalScore);
} }
/* the error i get: File: C:\Users\avino\Documents\java_project\gameScore.java [line: 14] Error: Invalid escape sequence (valid ones are \b \t \n \f \r " ' \ ) */
Solution 1:[1]
Your problem is here
System.out.println("Please insert your gender (M\F): ");
escape sequence is (\n,\b,\t etc) you used (M\F) as your required and java is thinking that "\F" is an escape sequence. So, make your (M\F) like below
System.out.println("Please insert your gender (M\\F): ");
Solution 2:[2]
Use \\ instead of \ in this line:
System.out.println("Please insert your gender (M\F): ");
So :
System.out.println("Please insert your gender (M\\F): ");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mussi |
