【问题标题】:check string for integers?检查字符串的整数?
【发布时间】:2023-03-22 20:10:01
【问题描述】:

好的,我之前发布过一次,但由于没有表现出基本的理解而被锁定,并且在锁定之前我得到的答案对我没有帮助。我处于 Java 的超级初学者水平,这就是我希望我的程序做的事情(将在最后发布代码)。我希望用户输入他们想要的任何内容。然后,如果它不是数字,我希望它显示他们需要输入数字。然后,在他们输入一个数字后,我希望它显示该数字是偶数还是奇数。我阅读了有关 parseInt 和 parseDouble 的信息,但我不知道如何让它按我想要的方式工作。如果解析是我想要做的,我不再确定。我不想立即将其转换为数字,只是为了检查它是否是数字。然后我可以在程序确定它是字符还是数字后继续做事情。感谢您的帮助,如果您需要更多信息,请告诉我!

好的,我更改了一些内容并使用了很多来自 no_answer_not_upvoted 的代码。这就是我现在所拥有的。它运行良好,可以使用说明中指定的负整数和正整数。毕竟,唯一让我烦恼的是,我在 Eclipse 底部的编译框中得到了这个错误。该程序执行预期的操作并适当停止,但我不明白为什么会出现此错误。

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at monty.firsttry2.main(firsttry2.java:21)


public static void main(String[] args) {

    System.out.print("Enter a character or number. This program will run until you enter a whole number, then it will"
            + "tell you if it was even or odd.");

    while (true) {
    Scanner in=new Scanner(System.in);     

    int num;
    while(true)   {
        String input=in.nextLine();
    try {

        num=Integer.parseInt(input);

        break;
        }
    catch (NumberFormatException e) {System.out.print("That wasn't a whole number. Program continuing.");}



    }
    if (num==0) {System.out.print("Your number is zero, so not really even or odd?");} 
    else if (num%2!=0){System.out.print("Your number is odd.");}
    else {System.out.print("Your number is even");}
    in.close();






  } 

} }

【问题讨论】:

  • 我会尝试将它与一些表达数字含义的正则表达式进行匹配。那么,例如,它可以有一个负号吗?小数点?逗号隔三位数?指数符号的 E 怎么样?如果它以零开头,然后是另一个数字,它是一个数字吗?等等。弄清楚你认为“这个字符串是一个数字”是什么意思。然后为其设计正则表达式。
  • +1 对于 RegEx,OP 将使用以下大多数答案出现一堆异常。
  • @DavidWallace“正则表达式”与“超级初学者”不匹配;-) user2833276 您的答案如下。面对锁定的问题坚持 +1 问题:)
  • @DavidWallace 这是一个合理的观点,因为异常确实确实不直观。我不应该这么快就放弃正则表达式。
  • 是的,正如你所说,它将被阻止。但是OP不想要这个。所需的行为是显示一条消息,说明输入的不是数字。如果程序在等待整数时被阻塞,则无法执行此操作。

标签: java string parsing


【解决方案1】:

假设

如果字符串由数字序列 (0-9) 组成,并且没有其他字符(可能除了初始的 - 符号),则将其视为数字。虽然我知道这允许使用诸如 "-0""007" 之类的字符串,我们可能不想将其视为数字,但我需要一些假设才能开始。这个解决方案是为了演示一种技术。

解决方案

import java.util.Scanner;

public class EvensAndOdds {
    public static final String NUMBER_REGEXP = "-?\\d+";
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for(;;) {   // Loop forever
            System.out.println("Enter a number, some text, or type quit");
            String response = input.nextLine();
            if (response.equals("quit")) {
                input.close();
                return;
            }
            if (response.matches(NUMBER_REGEXP)) {   // If response is a number
                String lastDigit = response.substring(response.length() - 1);
                if ("02468".contains(lastDigit)) {
                    System.out.println("That is an even number");
                } else {
                    System.out.println("That is an odd number");
                }
            } else {
                System.out.println("That is not a number");
            }
        }
    }
}

理由

此解决方案将匹配多个任意长度,而不仅仅是适合intlong 的长度;所以它优于使用Integer.parseIntLong.parseLong,如果数字太长,它们都会失败。这种方法也可以适应关于什么构成数字的更复杂的规则;例如,如果我们决定允许使用逗号分隔符的数字(例如 "12,345",目前将被视为非数字);或者如果我们决定禁止带有前导零的数字(例如"0123",目前将被视为数字)。这使得该方法比使用Integer.parseIntLong.parseLong 更加通用,它们都带有一组固定的规则。

正则表达式解释

正则表达式是一种可用于匹配部分或全部字符串的模式。这里使用的正则表达式是-?\d+,这需要一些解释。符号? 的意思是“也许”。所以-? 的意思是“可能是一个连字符”。符号\d 表示“一个数字”。符号+ 表示“其中任意数量(一个或多个)”。所以\d+ 表示“任意位数”。因此,表达式-?\d+ 表示“一个可选的连字符,然后是任意数量的数字”。当我们在 Java 程序中编写它时,我们需要将 \ 字符加倍,因为 Java 编译器将 \ 视为转义字符。

在正则表达式中可以使用许多不同的符号。全部请参考http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

【讨论】:

    【解决方案2】:

    这告诉你怎么做

    import java.util.Scanner;
    
    public class EvenOdd {
      public static void main(String[] args) {
        System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");
        try (Scanner in = new Scanner(System.in)) {
          int n;
          while (true) {
            String input=in.nextLine();
            try {
              n = Integer.parseInt(input);
              break;
            } catch (NumberFormatException e) {
              System.out.println("you did not enter just an integer, please try again");
            }
          }
          if (n % 2 == 0) {
            System.out.println(n + " is even");
          } else {
            System.out.println(n + " is odd");
          }
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      正如其他答案中已经提到的,您需要使用

      静态调用 parseDouble
      Double theNumber = Double.parseDouble(numberString);
      

      接下来,您将需要查看将其包装在 try/catch 中,以便您可以执行偶数/奇数检查是否创建了 theNumber,或者如果捕获到异常则设置错误消息。

      【讨论】:

        【解决方案4】:

        由于你是初学者,你需要了解数字(整数、双精度、字符串、字符)之间的区别,所以下面将指导你。

        首先,一次读取一行输入, Java read line from file)

        然后扫描行查找构成您认为是整数的字符(允许前导空格?,然后是“+”或“-”,然后是数字 0-9,然后是尾随空格。

        这里是规则(整数)

        除了这个模式之外的任何东西都违反了“这是一个整数”的测试。 顺便说一句,Double 是扩展精度实数。

        import java.lang.*;
        import java.util.Scanner;
        
        public class read_int
        {
            public static boolean isa_digit(char ch) {
                //left as exercise for OP
                if( ch >= '0' && ch <= '9' ) return true;
                return false;
            }
            public static boolean isa_space(char ch) {
                //left as exercise for OP
                if( ch == ' ' || ch == '\t' || ch == '\n' ) return true;
                return false;
            }
            public static boolean isa_integer(String input) {
                //spaces, then +/-, then digits, then spaces, then done
                boolean result=false;
                int index=0;
                while( index<input.length() ) {
                    if( isa_space(input.charAt(index)) ) { index++; } //skip space
                    else break;
                }
                if( index<input.length() ) {
                    if( input.charAt(index) == '+' ) { index++; }
                    else if( input.charAt(index) == '-' ) { index++; }
                }
                if( index<input.length() ) {
                    if( isa_digit(input.charAt(index)) ) {
                        result=true;
                        index++;
                        while ( isa_digit(input.charAt(index)) ) { index++; }
                    }
                }
                //do you want to examine rest?
                while( index<input.length() ) {
                    if( !isa_space(input.charAt(index)) ) { result=false; break; }
                    index++;
                }
                return result;
            }
            public static void main(String[] args) {
                System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");
        
                Scanner in=new Scanner(System.in);
                String input=in.nextLine();
                if( isa_integer(input) ) {
                    System.out.print("Isa number.");
                }
                else {
                    System.out.print("Not a number.");
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-20
          • 1970-01-01
          • 1970-01-01
          • 2016-01-03
          • 2011-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多