此 java 程序产生了不需要的结果

This java program produce unwanted results

我写了一个读取输入然后打印出来的程序。

public class inverse {


public static void main (String arg[]) throws IOException {
    int input1 = System.in.read();
    System.out.println(input1);
    String temp=  Integer.toString(input1);
    System.out.println(temp);
    int[] numtoarray =new int[temp.length()];
    System.out.println(temp.length());
    for (int i=0 ;i<temp.length(); i++)
    {numtoarray[i]= temp.charAt(i);
    System.out.println(numtoarray[i]+"*");
    }

}}

但是这里当我写 123456 时它打印 49。但它应该打印 123456。是什么导致了这个问题?

read() 不读取数字,它读取一个字节和 returns 它的值作为一个 int。如果您输入一个数字,您会得到 48 + 该数字,因为数字 0 到 9 在 ASCII 编码中的值是 48 到 57。

您可以改用扫描仪

这是代码

public static void main (String[] args) {

Scanner in = new Scanner(System.in);
int input1 = in.nextInt();
System.out.println(input1);
String temp=  Integer.toString(input1);
System.out.println(temp);
char[] numtoarray =new char[temp.length()];
System.out.println(temp.length());
for (int i=0 ;i<temp.length(); i++){
  numtoarray[i]= temp.charAt(i);
  System.out.println(numtoarray[i]+"*");
 }
}

DEMO

123456 是一个整数,但 System.in.read() 读取下一个字节作为输入,因此它不会按预期读取整数。使用Scanner#nextInt()方法读取一个整数:

Scanner input = new Scanner(System.in);
int input1 = input.nextInt();

您的 numtoarray 数组还将打印字节,而不是解析为字符串的整数的单个字符。要打印字符,请将类型更改为 char[]:

char[] numtoarray = new char[temp.length()];
System.out.println(temp.length());
for (int i = 0; i < temp.length(); i++) {
    numtoarray[i] = temp.charAt(i);
    System.out.println(numtoarray[i] + "*");
}