mgibb
mgibb

Reputation: 15

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();
        }
    }
}

Upvotes: 1

Views: 127

Answers (3)

Peter Sutton
Peter Sutton

Reputation: 1223

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);
    }
}

Upvotes: 0

aProperFox
aProperFox

Reputation: 2174

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.

Upvotes: 1

rgettman
rgettman

Reputation: 178363

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.

Upvotes: 1

Related Questions