2012-12-10 68 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