【问题标题】:Casting string into <Integer>ArrayList将字符串转换为 <Integer>ArrayList
【发布时间】:2015-07-22 19:13:03
【问题描述】:
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a sequence of numbers ending with 0.");

    ArrayList<Integer> list = new ArrayList<Integer>();

    String num = scan.nextLine();

    for(int x=0; x < num.length(); x++){
        System.out.println(num.charAt(x));

        int y = num.charAt(x);
        System.out.println(y);
        list.add(y);
        System.out.println(list);


    } 

我正在尝试将一串数字转换为数组。它没有添加正确的价值。我不断得到 49 和 50。我想将用户输入的数字存储到 ArrayList 中。有人可以帮忙吗?

【问题讨论】:

  • 那是因为它给了你ASCII值,int y = num.charAt(x)-48Character.valueOf(num.charAt(x)),因为'0'用48表示,参考:asciitable.com
  • @Thilo 我的回答会给你预期的结果。

标签: java string casting integer


【解决方案1】:
 int y = num.charAt(x);

这将为您提供字符的 Unicode 代码点。比如 A 的 65 或 0 的 48。

你可能想要

 int y = Integer.parseInt(num.substring(x, x+1));

【讨论】:

    【解决方案2】:

    你可以尝试使用:

    int y = Integer.parseInt(num.charAt(x));
    

    而不是

    int y = num.charAt(x);
    

    【讨论】:

    • Integer.parseInt 不适用于 char 作为方法参数。你的代码会给出编译错误。
    【解决方案3】:

    您没有将输入转换为整数,因此 JVM 将它们视为字符串。假设您在输入时是 1,它会打印 49(ASCII 等价物)的“1”。

    如果你想得到整数值,你需要使用解析它

    int y = Integer.parseInt(num.charAt(x));
    System.out.println(y);
    list.add(y);
    System.out.println(list);
    

    【讨论】:

    • Integer.parseInt 不适用于 char 作为方法参数。你的代码会给出编译错误。
    【解决方案4】:

    由于此代码int y = num.charAt(x); 正在造成问题。当您尝试将返回的字符存储为 int 值时,它正在存储字符的 ASCII 值。

    您可以参考其他答案中的建议。


    为简单起见,您可以像这样重写代码。

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a sequence of numbers ending with 0.");
    
    ArrayList<Integer> list = new ArrayList<Integer>();
    
    String num = scan.nextLine();
    
    char[] charArray = num.toCharArray();
    for (char c : charArray) {
        if (Character.isDigit(c)) {
            int y = Character.getNumericValue(c);
            System.out.println(y);
            list.add(y);
            System.out.println(list);
        } else {
             // you can throw exception or avoid this value.
        }
    }
    

    注意: Integer.valueOfInteger.parseInt 不会为 char 作为方法参数提供正确的结果。在这两种情况下,您都需要将 String 作为方法参数传递。

    【讨论】:

      【解决方案5】:

      您正在将 char 复制到 int 中。您需要将其转换为 int 值。

      int y = Character.getNumericValue(num.charAt(x));
      

      【讨论】:

      • 您的方法将整数作为输入 (Integer valueOf(int i)),因此在这种情况下它将返回 ASCII 值。
      • 检查一下docs.oracle.com/javase/7/docs/api/java/lang/… 除了 num.charAt(x) 不返回 int。
      • 那是字符串,不是字符。在您的代码中,它正在传递 char,因此在内部它将调用 valueOf(int i) 方法,并将 char 的 ASCII 值(由 num.charAt(x) 返回)作为方法参数传递。您可以通过执行代码来检查。
      • 你是对的,valueOf 方法没有给出正确的值;
      • 你的代码可以像int y = Integer.valueOf(String.valueOf(num.charAt(x)));这样工作。请参阅我对此问题的回答的注释部分。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 2013-01-07
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      • 2021-02-21
      • 2011-09-13
      相关资源
      最近更新 更多