2012-12-10 31 views
-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; 
    } 
} 

回答

1

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

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

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

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

+0

谢谢你的工作!这是伟大的...我尝试过,但我错了线..有时它只是需要另一套眼睛! – JavaNewGirl

+0

实际上已经正确解析了你正在使用的数字,所以你的格式类型永远不会输出字母。 –

+0

好的,谢谢你现在一切正常。 – JavaNewGirl