-3

I need these lines to output when a letter is typed instead of a whole number. I am not sure how to get it to do this: I have the code and what I need posted below if you can help me solve this issue, thank you.

This is what I am getting:
Input a valid whole number: abc
Input is not a valid number
Press any key to continue . . .

This is what I need:
Input a valid whole number: **ABC**
**ABC** is not a valid number
Press any key to continue . . .

below is what i have so far:

import java.io.PrintStream;
import java.util.Scanner;

public class FinalPractice
{
    public static void main(String [] args)
    {
        Scanner scanner = new Scanner( System.in );
        PrintStream out = System.out;

        out.print( "Input a valid whole number: " );

        String input = scanner.next();
        int number;

        try {
            number = Integer.parseInt(input);
        } catch (Exception e) {
            out.println("Input is not a valid number");
            return;
        }

        if (number < 0) {
            out.println(number + " is not a valid number");
            return;
        }

        printDivisors(number);
    }

    private static void printDivisors(int x){
        PrintStream out = System.out;
        for (int i=1; i<x; i++) {
            if (isDivisibleBy(x, i)){
                out.println(x + " is divisible by " + i);
            } else {
                out.println(x + " is not divisible by " + i);
            }
        }
    }

    private static Boolean isDivisibleBy(int x, int divisor){
        while (x > 0) {
            x -= divisor;
            if (x == 0){
                return true;
            }
        }
        return false;
    }
}
JavaNewGirl
  • 75
  • 1
  • 7

1 Answers1

1

If I'm understanding correctly, you want your error message to include what the user actually inputted. Change

out.println("Input is not a valid number");

to

out.println (input + " is not a valid number");

This takes your variable input, merges it with the rest of the String and it will then be displayed to the output console.

A--C
  • 36,351
  • 10
  • 106
  • 92
  • thank you that worked!! that is great... I tried that but I was on the wrong line.. sometimes it just takes another set of eyes! – JavaNewGirl Dec 10 '12 at 02:58
  • You were working with number after it was actually properly parsed,so your type of formatting would never have outputted for letters. – A--C Dec 10 '12 at 03:05