web-dev-qa-db-fra.com

Comment vérifier si la saisie de l'utilisateur est String, double ou long en Java

Je suis débutant en Java. Je veux d'abord vérifier si l'entrée de l'utilisateur est String ou Double ou int. S'il s'agit d'une chaîne, d'un nombre double ou d'un nombre moins, l'utilisateur doit être invité à entrer à nouveau un numéro int valide. Le programme ne doit essayer que lorsque l'utilisateur a entré un nombre valide. Cela fait des heures que je réfléchis et je ne trouve rien d'utile. Aidez-moi, merci!

import Java.util.InputMismatchException;
import Java.util.Scanner;

public class Fizz {

public static void main(String[] args) {

    System.out.println("Please enter a number");

    Scanner scan = new Scanner(System.in);

    try {

        Integer i = scan.nextInt();

        if (i % 3 == 0 && (i % 5 == 0)) {
            System.out.println("FizzBuzz");
        } else if (i % 3 == 0) {
            System.out.println("Fizz");
        } else if (i % 5 == 0) {
            System.out.println("Buzz");
        } else {
            System.out.println(i + "は3と5の倍数ではありません。");
        }
    } catch (InputMismatchException e) {
        System.out.println("");

    } finally {
        scan.close();
    }

}
7
user4799681

Une solution simple consiste à lire l'intégralité de la ligne/entrée de l'utilisateur sous forme de chaîne. Une telle opération devrait fonctionner. (Code non testé):

   String s=null;
   boolean validInput=false; 
   do{
      s= scannerInstance.nextLine();
      if(s.matches("\\d+")){// checks if input only contains digits
       validInput=true;
      }
      else{
       // invalid input
     }
    }while(!validInput);
8
TheLostMind

Vous pouvez également utiliser Integer.parseInt, puis vérifier que cet entier n'est pas négatif. Vous pouvez intercepter NumberFormatException si l'entrée est une chaîne ou un double.

Scanner scan = new Scanner(System.in);
try {
     String s = scan.nextLine();
     int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
1
Abhishek Chauhan

Essaye ça. Il demandera une entrée jusqu'à ce qu'une valeur int supérieure à 0 soit entrée:

System.out.println("Please enter a number");

try (Scanner scan = new Scanner(System.in)) {
    while (scan.hasNext()) {
        int number;
        if (scan.hasNextInt()) {
            number = scan.nextInt();
        } else {
            System.out.println("Please enter a valid number");
            scan.next();
            continue;
        }

        if (number < 0) {
            System.out.println("Please enter a number > 0");
            continue;           
        }

        //At this stage, the number is an int >= 0
        System.out.println("User entered: " + number);
        break;
    }
}
0
Ian2thedv

Essaye celui-là. J'ai utilisé certaines conditions pour indiquer l'entrée.

Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){   
   for(int y=0; y<10; y++){
       if(input.charAt(x)==Integer.toString(y))
          flag = true;
       else{
          flag = false;
          break;
       }
   }
}
if(flag){
   if(scan.hasNextDouble())
      System.out.println("Input is Double");
   else
      System.out.println("Input is Integer");
}   
else
   System.out.println("Invalid Input. Please Input a number");
0
Discern
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);

while(!valid){
    System.out.println("Enter the number: ");
    userInput = input.nextLine();

    try{
        n = Double.parseDouble(userInput);
        valid = true;
    }
    catch (NumberFormatException ex){
        System.out.println("Enter the valid number.");
    }
}
0
Daman Singh