如何阻止用户在数字处输入字母,反之亦然?

问题描述 投票:0回答:1

如何阻止用户在数字处输入字母,反之亦然?

只是为了以后的学习而尝试理解。我尝试添加不同类型的代码来解决此问题,但我对此很陌生。任何帮助将不胜感激。Thnaks.


import java.util.Scanner;
public class Pro_4_extra {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        Scanner input = new Scanner (System.in);
        
        double max = 272.155;
        
        System.out.print("Enter team name: ");
        String team = input.nextLine();
        
        System.out.print("Enter the name of member 1: ");
        String name1 = input.nextLine();
        System.out.print("Enter the weight of member 1 in lbs: ");
        double pounds1 = input.nextDouble();
        input.nextLine();
    
        System.out.print("Enter the name of member 2: ");
        String name2 = input.nextLine();
        System.out.print("Enter the weight of member 2 in lbs: ");
        double pounds2 = input.nextDouble();
        input.nextLine();
        
        System.out.print("Enter the name of member 3: ");
        String name3 = input.nextLine();
        System.out.print("Enter the weight of member 3 in lbs: ");
        double pounds3 = input.nextDouble();
        
        double kilograms1 = pounds1 / 2.2046;
        double kilograms2 = pounds2 / 2.2046;
        double kilograms3 = pounds3 / 2.2046;
        double kilograms = kilograms1 + kilograms2 + kilograms3;
        
      
        
       System.out.println("Team " + team +" members: " + name1 + ", " 
                + name2 + ", and "+ name3);
     
       if (kilograms <= 272.155)                
           System.out.printf("The total weight of the team is %.2f"
                + " kg and is under the maximum. ", kilograms);
       else 
           System.out.printf("The total weight of the team is %.2f kg and is over the limit. "
                + "Your team is disqualified from competing until weight requirements are meet.", kilograms);
            
                
        input.close();
    }   
}
java
1个回答
0
投票

希望这就是您要问的。制作了 1 种输入方法并验证输入,以防输入无效,再次询问,或者如果需要,您也可以在两者之间中断。所以这取决于您的要求。

public static double getValidInput(Scanner scan) {
        while(!scan.hasNextDouble()){
            System.out.println("Please input valid weight !!!");
            scan.next();
        }
        return scan.nextDouble();
    }

将输入行替换为以下

double pounds1 = getValidInput(input);

© www.soinside.com 2019 - 2024. All rights reserved.