【问题标题】:need character to print in output lines需要字符在输出行中打印
【发布时间】:2012-11-27 11:17:32
【问题描述】:

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

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

【问题讨论】:

    标签: java class character boolean-logic divide-and-conquer


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 谢谢你的工作!!太好了……我试过了,但我走错了路……有时它只需要另一双眼睛!
    • 您在实际正确解析后使用数字,因此您的格式类型永远不会输出字母。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多