How do I check if my input is number or text?

Asked

Viewed 61 times

1

I wonder how I can check the kind of value that goes into my Scanner, to return to the user that that entry only receives a number and that he has typed a text or character.

public class WhileChallenge {
    
    public static void main(String[] args) 
    {
        double grades = 0.0;
        double grades_total = 0.0;
        int grades_amount = 0;
        
        Scanner input_value = new Scanner(System.in);
        
        while(grades != -1)
        {
            System.out.println("Insert a grade:");
            grades = Double.parseDouble(input_value.next().replace(",", "."));
            
            if(grades < 0.0 || grades > 10.0)
            {
                System.out.println("Out of range value");
            }else if(grades >= 0.0 && grades <= 10.0)
            {
                grades_total += grades;
                grades_amount++;
            }
            //Se a nota for diferente de um número; Pede pro usuário digitar um número
        }
        
        System.out.println("Average: " + ((grades_total)/grades_amount));
        
        input_value.close();    
    }
    
}
  • About your other doubt (which I removed because it has nothing to do with the question’s scheduling problem), the website applies the syntax Highlight according to the question tags, and since you already have the [tag:java], the correct syntax will be applied

1 answer

2


According to the documentation, Double.parseDouble makes an exception (a NumberFormatException) if the string does not have a valid number. Then just capture this exception to see if it went wrong:

Scanner input = new Scanner(System.in);
double gradesTotal = 0;
double gradesAmount = 0;
while (true) {
    double grade;
    System.out.println("Insert a grade:");
    while (true) { // enquanto não digitar um número válido, continua no while
        try {
            grade = Double.parseDouble(input.nextLine().replace(",", "."));
            break; // se chegou aqui é porque o número é válido, então posso sair do while
        } catch (NumberFormatException e) {
            // número inválido
            System.out.println("Digite um número válido");
        }
    }

    // se for -1, sai do while mais externo
    if (grade == -1)
        break;

    if (grade < 0.0 || grade > 10.0) {
        System.out.println("Out of range value");
    } else {
        gradesTotal += grade;
        gradesAmount++;
    }
}

Notice I made one while(true) external (to keep repeating everything, until finding a -1, which is the output condition you have placed), and another more internal one just to read the number (and it keeps asking you to type again, until the number is valid).

See also that in the else do not need to test all conditions again. If the number is between 0 and 10 it will not enter the if, then it came to else is because it is certainly not less than zero and not more than 10, so testing it again is redundant and unnecessary.

I also changed the names of the variables to match the java conventions, who prefers nomesAssim instead of nomes_assim.

  • When you talk about preferring names like that: nomesAssim instead of nomes_assim, implies that ? I just read the documentation and it just says: "Variable names should not start with underlined characters _ or dollar sign, although both are allowed." When I enter a: ?

  • @Matheusluis They are only conventions. Whether you follow or not, the code will continue compiling and running smoothly, will not give error. Conventions are only arbitrary definitions, but may be useful if they are followed: https://en.wikipedia.org/wiki/Coding_conventions#Software_maintenance

  • @Matheusluis And the link I passed says: "Mixed case with a lowercase first Letter. Internal words start with capital Letters" - that is, it starts with lowercase and internal words begin with uppercase - but as I said, they are conventions, there is no obligation to follow, although there are advantages in doing so. See more about it here: https://answall.com/q/153540/112052

  • @Matheusluis Just to finish, an excerpt that I find interesting (from the link I passed above): "Finally, the choice of the following conventions is at your discretion at the end of the day. In the case of identifier naming, I see little reason to escape the convention since, although it might actually have been better, you will already be using a lot of classes and library methods that follow the standard convention (even those of the java.lang package), which means that in trying to go against this, you would end up creating a code with a heterogeneous and de-standardized style"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.