简体   繁体   中英

Loop won't terminate Java

I am a beginner programmer, so apologies in advance if the answer to this question is obvoius! I'm trying to create a simple program that counts the number of digits in different integers repeatedly and ends if i enter -1, but when i enter -1 it counts the digits in the integer and doesn't stop. I've been trying out different loops but I always seem to end up with similar problem so any help would be appreciated!

import java.util.Scanner;

public class NumberCount { 

public static void main (String [] args) {
    Scanner input = new Scanner (System.in);

    System.out.print("Enter Number: ");
    String num = input.nextLine();


    int number = Integer.parseInt(num);
        if (number == -1) {
            System.out.print("Program Terminated. . .");
        } 

        while (number != -1) {
            System.out.println("Number of digits in " + num + " is " + num.length());
            System.out.print("Enter Number: ");
            num = input.nextLine();
            num.length();
        }
    }
}

You never change number inside the while loop, so even if you enter -1 , number won't change to -1 . Parse num into an int and assign it to number after the call to nextLine() inside the while loop.

Additionally, this call on a line by itself inside the while loop does nothing.

num.length();

It evaluates to the length of the num String , but it isn't assigned to anything. It can be deleted.

Change all instances of 'num' to 'number'. You're defining the variable 'num' in the while loop but using the variable 'number' to compare to -1. Since the only variable being changed is 'num', the while loop won't ever break unless 'number' was declared as -1 before the while loop.

Others have explained the problem, so I've just included a minimal solution. I use a Console rather than a Scanner because it's slightly nice to use. The do-while loop works as follows:

  1. Ask the user for a number and parse it
  2. Nice bit of maths to calculate the number of digits in a positive (non-zero) integer
  3. Print out the number and digits to the user
  4. If the user entered -1 stop

The code:

import java.io.Console;

public class CountNumbers {
    public static void main(String[] args) {
        Console console = System.console();
        int number;
        do {
            number = Integer.parseInt(console.readLine("Enter number: "));
            int numDigits = (int) (Math.log10(number) + 1);
            console.format("Number of digits in %d is %d\n", number, numDigits);
        } while (number != -1);
    }
}

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