簡體   English   中英

將字符串轉換為 <Integer> 數組列表

[英]Casting string into <Integer>ArrayList

    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);


    } 

我試圖將一串數字投射到一個數組中。 它沒有添加正確的vaule。 我一直得到49和50.我想將用戶輸入的數字存儲到ArrayList中。 有人可以幫忙嗎?

 int y = num.charAt(x);

這將為您提供角色的Unicode代碼點。 像65表示A或48表示0表示。

你想要的是什么

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

您可以嘗試使用:

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

代替

int y = num.charAt(x);

您沒有將輸入轉換為Integer,因此JVM將它們作為字符串。 假設您在輸入時為1,則打印49(ASCII等效值)為“1”。

如果要獲取整數值,則需要使用解析它

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

正如此代碼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作為方法參數傳遞。

您正在將char復制到int中。 您需要將其轉換為int值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM