如何读取以零开头的整数?

Beg*_*mer 0 java

这是一个读取整数的程序:

public static void main(String argv[]) {
    Scanner input = new Scanner(System.in);
    int x = input.nextInt();
    System.out.println(x);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我输入这样的输入:000114它将被读取为114.How to read integer 从零开始?

Bet*_*ise 5

开头的零被忽略int。如果您需要显示零,请将数字存储为 a String。如果以后需要使用它进行计算,可以将其转换为intusing Integer.parseInt(),因此您的代码应如下所示:

String x = input.next();
System.out.println(x);

//if you need x to be an int
int xInt = Integer.parseInt(x);
Run Code Online (Sandbox Code Playgroud)

请记住,在此示例中,xInt将丢失零。