-3

当输入字母而不是整数时,我需要输出这些行。我不知道如何让它做到这一点:如果你能帮助我解决这个问题,我有代码和我需要的内容,谢谢。

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

1 回答 1

1

如果我理解正确,您希望您的错误消息包含用户实际输入的内容。改变

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

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

这需要您的变量input,将其与字符串的其余部分合并,然后将其显示到输出控制台。

于 2012-12-10T02:47:58.247 回答