Java 将字符串转换为<;整数>;ArrayList Scanner scan=新的扫描仪(System.in); System.out.println(“输入以0结尾的数字序列”); ArrayList=新建ArrayList(); String num=scan.nextLine(); 对于(int x=0;x

Java 将字符串转换为<;整数>;ArrayList Scanner scan=新的扫描仪(System.in); System.out.println(“输入以0结尾的数字序列”); ArrayList=新建ArrayList(); String num=scan.nextLine(); 对于(int x=0;x,java,string,casting,integer,Java,String,Casting,Integer,我试图将一串数字转换成一个数组。它没有添加正确的变量。我总是得到49分和50分。我想存储用户在ArrayList中输入的数字。有人能帮忙吗 Scanner scan = new Scanner(System.in); System.out.println("Enter a sequence of numbers ending with 0."); ArrayList<Integer> list = new ArrayList<Integer>()

我试图将一串数字转换成一个数组。它没有添加正确的变量。我总是得到49分和50分。我想存储用户在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);


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

你可能想要

 int y = num.charAt(x);
您可以尝试使用:

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

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

您没有将输入转换为整数,因此JVM将它们作为字符串。假设您输入时为1,它将打印“1”的49(ASCII等效值)

如果您想要得到整数值,您需要使用

int y = num.charAt(x);

此代码
int y=num.charAt(x)正在产生问题。当您试图将返回的字符存储为int值时,它存储的是字符的ASCII值

你可以按照其他答案中的建议去做


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

int y = Integer.parseInt(num.charAt(x));
System.out.println(y);
list.add(y);
System.out.println(list);
Scanner scan=新的扫描仪(System.in);
System.out.println(“输入以0结尾的数字序列”);
ArrayList=新建ArrayList();
String num=scan.nextLine();
char[]charArray=num.toCharArray();
用于(字符c:charArray){
if(字符isDigit(c)){
int y=字符.getNumericValue(c);
系统输出打印项次(y);
列表。添加(y);
系统输出打印项次(列表);
}否则{
//您可以抛出异常或避免此值。
}
}


注意:
Integer.valueOf
Integer.parseInt
将不会为char作为方法参数给出正确的结果。在这两种情况下,您都需要将字符串作为方法参数传递。

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

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.
    }
}

这是因为它为您提供ASCII值,
int y=num.charAt(x)-48
Character.valueOf(num.charAt(x))
由于“0”由48表示,请参阅:@Thilo,我的答案将为您提供预期结果。您的方法将整数作为输入(),因此在本例中它将返回ASCII值。除了num.charAt之外,请检查此项(x) 不返回int。这表示字符串,而不是char。在代码中,它传递char,因此在内部它将调用valueOf(int i)方法,并传递char的ASCII值(由num.charAt(x)返回)作为方法参数。您可以通过执行代码进行检查。您是对的,valueOf方法没有给出正确的值;您的代码可以这样工作
int y=Integer.valueOf(String.valueOf(num.charAt(x)));
。请参阅我对这个问题的部分回答。Integer.parseInt不适用于作为方法参数的char。您的代码将给出编译错误。Integer.parseInt不适用于作为方法参数的char。您的代码将给出编译错误。
int y = Character.getNumericValue(num.charAt(x));