[英]Why I am getting “0” in front part of transforming digits into integer?
Example: when you type "1234567", it`s display "0 1 2 3 4 5 6 7". 示例:当您键入“ 1234567”时,其显示为“ 0 1 2 3 4 5 6 7”。 How can I rid of "0" in front part? 如何消除前面的“ 0”?
public static void main(String[] args){
int num = 0;
int eachNum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter your number here: ");
num = input.nextInt();
int num2 = num;
int length = String.valueOf(num).length();
while ( length >= 0 ) {
int substraction =(int) Math.pow(10, length);
int sub = (int) substraction;
eachNum = num2 / sub % 10;
System.out.print(eachNum + "\t");
length--;
}
}//end main method
You could solve this by doing: 您可以通过以下方法解决此问题:
while (length > 0) { // iterating one less time
int substraction = (int) Math.pow(10, length-1); // length-1 to get from first digit
...
}
Anyway you can improve your code and do little trick even, so you don't need the calculations: 无论如何,您都可以改进代码,甚至不做任何技巧,因此不需要计算:
Scanner input = new Scanner(System.in);
System.out.print("Enter your number here: ");
int num = input.nextInt();
String str = String.valueOf(num);
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i)+"\t");
}
Consider the first iteration. 考虑第一次迭代。
length
is 7
. length
是7
。
pow(10, 7)
is 10,000,000
(I've put commas in for clarity). pow(10, 7)
是10,000,000
(为清楚起见,我在其中加了逗号)。
num2 / sub % 10;
is evaluated as (num2 / sub) % 10
due to the precedence of /
and %
being the same so evaluation is from left to right. 由于/
和%
的优先级相同,所以将其评估为(num2 / sub) % 10
,因此评估是从左到右。
This is (1,234,567 / 10,000,000) % 10
which is 0 % 10
since integer division truncates the number. 这是(1,234,567 / 10,000,000) % 10
,它是0 % 10
因为整数除法会截断该数字。 So your first output is 0
. 因此,您的第一个输出是0
。
The simplest fix is probably to subtract 1 from the initial value of length
. 最简单的解决方法可能是从length
的初始值中减去1。
Try this code. 试试这个代码。 Now you will find your desire output 现在您将找到您想要的输出
public static void main(String[] args){
int num = 0;
int eachNum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter your number here: ");
num = input.nextInt();
int num2 = num;
int length = String.valueOf(num).length()-1;
while ( length >= 0 ) {
int substraction =(int) Math.pow(10, length);
int sub = (int) substraction;
eachNum = (num2 / sub) % 10;
System.out.print(eachNum + "\t");
length--;
}
}//end main
You should also skip case when num2 < substraction. 当num2 <减时,还应该跳过大小写。 I try changing while in this way: 我尝试以这种方式进行更改:
while ( length >= 0 ) {
int substraction =(int) Math.pow(10, length--);
int sub = (int) substraction;
if (num2 < substraction)
continue;
eachNum = num2 / sub % 10;
System.out.print(eachNum + "\t");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.