简体   繁体   English

我的for循环有什么问题?

[英]What's wrong with my for-loop?

I am trying to print each digit of an integer and then sum of each digit like this. 我试图打印整数的每个数字,然后像这样打印每个数字的总和。 There is something wrong with the loops but I cant seem to figure it out. 循环有问题,但我似乎无法弄明白。 I want it to be like this: 我希望它是这样的:

Please enter a number: 194
1 * 100 = 100
9 * 10 = 90
4 * 1 = 4
import java.util.Scanner;
public class PrintEachDigits {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int num = scan.nextInt();
        String s = ""+num;
        double d = 0; 
        for(int i = 0; i < s.length(); i++) { 
            for(int j = s.length()-1; j >= 0; j--) { 
                d = Math.pow(10,j); 
                System.out.println(s.charAt(i) + " * " + d
                                   + " = " + (s.charAt(i)*d)); 
            }
        }
    }
}

This is the output of my code: 这是我的代码的输出:

Enter the number: 194
1 * 100.0 = 4900.0
1 * 10.0 = 490.0
1 * 1.0 = 49.0
9 * 100.0 = 5700.0
9 * 10.0 = 570.0
9 * 1.0 = 57.0
4 * 100.0 = 5200.0
4 * 10.0 = 520.0
4 * 1.0 = 52.0

There's a couple problems with your code. 您的代码存在一些问题。

The first problem is that you don't need two loops, you just need one. 第一个问题是你不需要两个循环,你只需要一个循环。

The second problem is confusing char s and int s. 第二个问题是混淆charint '0' is not the same as 0 ; '0'0 ; instead, '0' is a numeric value representing the encoding of that character (which turns out to be 48). 相反, '0'是表示该字符编码的数值(结果为48)。 So to get the correct value that you want, you should subtract '0' from the char before doing your math. 因此,为了获得您想要的正确值,您应该在进行数学运算之前从char减去'0'

for(int i = 0; i < s.length(); i++) { 
    d = Math.pow(10, s.length() - i - 1); 
    int value = s.charAt(i) - '0';
    System.out.println(value + " * " + d
                       + " = " + (value*d)); 
}

This will get it close to the output you wanted. 这将使它接近您想要的输出。 It's still showing the .0 at the end though, because d is a double . 尽管如此,它仍然显示.0 ,因为ddouble Make it an int to fix that. 使它成为一个int来解决这个问题。

//This can be scoped to inside the loop, so you don't need to declare it beforehand
int d = (int)Math.pow(10,j); 
import java.util.Scanner;
public class PrintEachDigits {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int num = scan.nextInt();
        String s = "" + num;
        int len = s.length() - 1;
        long d = 0;
        if (len < 2) {
            d = 1;//For single digit
        } else {
            d = (long)Math.pow(10, len);
        }

        for (int i = 0; i < s.length(); i++) {
            System.out.println(s.charAt(i) + " * " + d + " = "
                    + ((s.charAt(i) - '0') * d));
            d = d / 10;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM