简体   繁体   English

Integer.parseInt混淆

[英]Integer.parseInt Confusion

I am having difficulties trying to make an application I am coding to distinguish whether or not the args[] input of the user is a String or an int. 我在尝试编写要编码的应用程序时遇到困难,以区分用户的args []输入是String还是int。 If an int value is typed, it will be listed and added in common addition format. 如果输入一个int值,它将以通用加法格式列出并添加。 If a String value is typed into args[], a list of the ignored arguments is collected (Strin[] ignored) and will be printed for the user to see. 如果将String值键入args [],则将收集被忽略参数的列表(将Strin []忽略)并将其打印出来供用户查看。 I am trying to distinguish this through nested loops that parse the value inputted as an int value and checks to see if this args[] String value is indeed a int, but, being fairly new at programming, I have hit quite the roadblock. 我试图通过嵌套循环来区分这点,该循环分析输入为int值的值,并检查此args []字符串值是否确实是int,但是在编程时还很陌生,我遇到了很多障碍。 Any suggestions? 有什么建议么?

Here is my code: 这是我的代码:

public class Addition {


  public static void main(String args[]) {
    int sum = 0;
    String[] ignored = new String[args.length];
    if(args.length == 0) {
      System.out.println("No input values!");
    } else {
      for(int i = 0; i < args.length; i++) {
        if(Character.isDigit(Integer.parseInt(args[i]))) {
          sum += Integer.parseInt(args[i]);
          if(i == 0) {
            System.out.print(args[i]);
          } else if(Integer.parseInt(args[i]) >= 0) {
            System.out.print(" + " + args[i]);
          } else if(Integer.parseInt(args[i]) < 0) {
            System.out.print(" - " + (Integer.parseInt(args[i]) * -1));
          }
        } else if(!Character.isDigit(Integer.parseInt(args[i]))) {
            ignored[i] = args[i];
        }
      } System.out.print(" = " + sum);
    }
  }
}

I am getting this Interactions error: 我收到此互动错误:

   java.lang.NumberFormatException: For input string: "-"
   at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Addition.main(Addition.java:17)  

Ok I'm not that clear what you are trying to do with your numbers but you can actually use the NumberFormatException to achieve what you have to do (separate the numbers and non-numbers). 好的,我不清楚您要使用数字做什么,但是实际上您可以使用NumberFormatException实现必须要做的事情(将数字和非数字分开)。

ArrayList<Integer> numbers = new ArrayList<Integer>();
ArrayList<String> nonNumbers = new ArrayList<String>();

for(String s : args)
{
    try
    {
        int number = Integer.parseInt(s);
        numbers.add(number);
    }
    catch (NumberFormatException nfe)
    {
        nonNumbers.add(s);
    }
}

// rest of your code can use numbers and nonNumbers lists

Well, you can either A) determine it's a number, then parse it, or B) try to parse, and handle it gracefully if it fails. 好吧,您可以A)确定它是一个数字,然后解析它,或者B)尝试解析,并在失败时优雅地处理它。 Since you're summing things, I'm assuming they SHOULD be a number, and so let's go with B. 既然您正在对事物进行求和,那么我假设它们应该是一个数字,因此让我们来看B。

Something as simple as this would work in your case: 这样简单的方法适用于您的情况:

int badArgs = 0;
for(int i = 0; i < args.length; i++) {

  try {
    int value = Integer.parseInt(args[i]);
    // Do your main logic with value here
  } catch (NumberFormatException e) {
    ignored[badArgs++] = args[i];
  }

Current problems with your code: checking .isDigit as you are makes no sense - it's meant to check a character from a string - you've already parsed it at that point, so if it's going to throw a NumberFormatException, it will have already, before you finish the check. 您的代码当前存在的问题:检查.isDigit就没有意义了-它是要检查字符串中的字符-您已在该位置对其进行了解析,因此,如果要抛出NumberFormatException,它将已经存在,在完成检查之前。 Second: checking if it's a digit doesn't make sense anyhow, as -1 is a valid number, but would obviously fail whatever check you had in mind - and the rest of your code shows you intend to handle negaties. 第二:检查数字是否是没有意义的,因为-1是一个有效数字,但是无论您想出什么检查方法,显然都会失败-其余代码表明您打算处理负数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM