【问题标题】:how can loop be used in following code so that if user enters any alphabet program again ask to enter a nuumber rahter than terminating a program?如何在以下代码中使用循环,以便如果用户再次输入任何字母程序时要求输入数字而不是终止程序?
【发布时间】:2015-05-18 16:50:19
【问题描述】:

如何应用循环,以便当用户输入任何字母程序时,它会提示用户再次输入数字而不是终止程序?

public class prac{
    public static void main(String[] args) throws FileNotFoundException{
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your Cell Phone number : ");
        double phonenumber;

        phonenumber = in.nextDouble();                                
    }
}

【问题讨论】:

  • 你是怎么做到的?也许你应该拿起一本基本的编程书,这是通常描述的......

标签: java loops java.util.scanner


【解决方案1】:

按照下面的方法做

Pattern pattern = Pattern.compile("^[0-9]+$");
Scanner in = new Scanner(System.in);
double phonenumber = 0;
String input;
Matcher matcher;
boolean stop=false;

while (!stop) {
     System.out.println("Enter your Cell Phone number : ");
     input = in.nextLine();  
     matcher = pattern.matcher(input);
     if (matcher.find()) {
           stop=true;
           phonenumber=Double.parseDouble(input);
     }          
}

System.out.println("User phone number is "+phonenumber);

编辑:

^        match the beginning of the line
[0-9]    match a digit 
+        match 1 or more times
$        match the end of the line

【讨论】:

  • 但是为什么OP问题选择double来存储用户的电话号码? int 不是更好吗?
  • 我相信有些电话号码超出了 Integer 最大值 (2,147,483,647) 也就是 10 位数。在美国,我们使用 10。我对世界其他地方不太确定,但他本可以解释这一点……但是,double 仍然是这里的怪人……他本可以使用long,不是吗?它的最大值为 9223372036854775807,这肯定是很多字符。
  • 我以前从未真正使用过正则表达式,所以我查了一下。 "^[0-9]+$" 是否表示“行首 + 一个或多个介于 0 和 9(含)之间的数字 + 行尾”?只是想理解。
  • @MChaker 谢谢。那么匹配行首和行尾只是为了确保除了数字之外没有添加任何其他内容?
  • 是的,你知道了@pepers
猜你喜欢
  • 2023-02-23
  • 2022-09-27
  • 1970-01-01
  • 2017-07-16
  • 1970-01-01
  • 1970-01-01
  • 2020-04-13
  • 2020-05-12
  • 1970-01-01
相关资源
最近更新 更多