0
I need the user to input a grade A B C or D and i have assigned int to these var so that i can use it to multiple another variable and the output final answer, how do i write the code please
3 Answers
+ 1
see the below.
Note that I have used the regular expression (?=[A-Da-d]). to make sure the program only accepts a letter from a to d
Ex:
import java.util.Scanner;
import java.util.regex.Pattern;
public class Program
{
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int grade=0;
int base=10;
int score=0;
String input;
while(true){
System.out.print("Enter a grade(A B C or D): ");
try{
input = scanner.next(Pattern.compile("(?=[A-Da-d])."));
break;
}catch(Exception e){
scanner.nextLine();
continue;
}
}
switch(input.toUpperCase()){
case "A":
grade = 1;
break;
case "B":
grade = 2;
break;
case "C":
grade = 3;
break;
case "D":
grade = 4;
break;
}
score = grade * base;
System.out.println();
System.out.println("Your score is " + score);
}
}
+ 1
Tanks it worked
0
I needed something similar but for Python