0

I have the following program below. I wanted it to only run if the input is a string, so I used hasNext() with an if statement.

Unfortunately, it will still return true when I enter numbers. I want the program to execute the else statement if a letter grade is not entered. Is there a way around this? Thank you.

import java.util.Scanner;

public class LetterGrade {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        System.out.print("Enter a letter grade: ");

        if (in.hasNext()) {
            String letterGrade = in.next();
            System.out.println(letterGrade);
        } else {
            System.out.print("Not a valid letter grade");
        }
    }
}
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80

2 Answers2

0

You may use,

Character.isLetter(char ch)

to determine whether the input is a letter.

When using the System.in as the InputStream source, you don't need to use hasNext() because it will not continue without an input.

And remember, next() method returns the user input as a String. It doesn't mean that it returns something only if the input is a String.


Scanner in = new Scanner(System.in);
System.out.print("Enter a letter grade: ");

String letterGrade = in.next();

if (Character.isLetter(letterGrade.toCharArray()[0])) {
    System.out.println(letterGrade);
} else {
    System.out.print("Not a valid letter grade");
}
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
0

The .next() method of your scanner always returns a String, no matter what you type. In your case, the number you type in will be read and hold as a String object. You have to read the input first and after that you have to check if your input is a valid letter grade or not. I´d do it like this:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a letter grade: ");
    String input = in.next();
    if (isLetterGrade(input)) {
        System.out.println(input);
    } else {
        System.out.print("Not a valid letter grade");
    }
}

public static boolean isLetterGrade(String input) {
    //check if your String is a letter grade

}
Don
  • 13
  • 5