简体   繁体   中英

Could anyone tell me why my program doesn't work?

The program reads values from scanner until the value 0 is given, which finishes the process. The program will compile the sum only if all the numbers given are integers. In all the other situations (where not all of the values are integers) the program won't give anything out. So i noticed my program gives out the sum of the integers even if there are other non integer values given and sometimes when they are all integers given it doesn't show the real sum just one of the numbers or something.

  import java.util.Scanner;
public class Testing3{
    public static void main(String[] args) {
        int sum1 = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter number");
        String number = input.nextLine();
        int value =Integer.parseInt(number);
        while(true) {
            if (value!=0) {
                number = input.nextLine();
                if (Math.round(value)==value)//condition to integer{
                    sum1 = sum1 + value;
            } else {
                System.out.println(sum1);
                break;
            }
        }
    }
}

First of all, use while(true) or for(;;) to make in infinite loop

Second use nextInt() to read integers instead of doubles because you have no use for doubles. Alternatively, read strings with readLine and check their validity with Integer.parseInt .

Thirdly, you have a syntax error (so it shouldn't compile). You have an unmatched close brace near the else.

Lastly, remove the if (number != 0) because that will cause your program to continuously repeat in the loop without doing anything forever. Change the inside of the loop to:

number = input.nextInt();
if (number != 0){
    sum1 = sum1 + number; //or use sum1 += number
} else {
    System.out.println(sum1);
    break;
}

I think your problem is at the place where you test for an integer. I don't think x mod 1 == 0 is correct suitable here. What I'll do when I am asked to check whether a number is an integer, I round the number and check if it equals to the original number.

Let's say we have a double variable called x and this evaluates to true if x is an integer:

Math.round(x) == x

I don't know whether there is a better way to do it but that's how I would do it and I like it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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