2012-03-28 115 views
0

我現在正在開發一個程序,它可以分割,添加等等,但是,即時消息也可以爲其他人使用,因此,問題通常也包含字母。我可以執行哪些代碼,以便我的程序忽略字符,並只專注於數字?忽略字符

編輯

進口靜態文件java.lang.System.out; import java.util.Scanner;

公共類三叉{ 公共靜態無效的主要(最終字符串ARGS []){

final Scanner first = new Scanner(System.in); 
    out.print("Enter the first number: "); 
    final int First = first.nextInt(); 

    final Scanner second = new Scanner(System.in); 
    out.print("Enter the second number: "); 
    final int Second = second.nextInt(); 

    final Scanner third = new Scanner(System.in); 
    out.print("Enter the third number: "); 
    final int Third = third.nextInt(); 

    numFactors(First); 
} 

}

+1

好的解決方案在這裏:http://stackoverflow.com/questions/1102891/how-to-check-a-string-is-a-numeric-type-in​​-java – sikander 2012-03-28 21:34:37

+0

你可以使用'Character.isDigit( c)'如果給定的字符是數字? – twain249 2012-03-28 21:37:23

回答

0

首先,您將不得不使用掃描器的next()方法,因爲如果下一個標記包含非數字字符,則nextInt()將返回一個異常。這會將該標記讀取爲一個字符串。然後,通過創建一個空字符串(出於性能方面的原因,StringBuilder可以更好,但這使得它更復雜),循環遍歷原始字符串並使用已經提到的isDigit()方法,可以擺脫非數字字符以確定角色是否是數字。如果是,請將其添加到新字符串中。一旦你有一個只包含數字的字符串,使用Integer.parseInt(string)方法來獲得整數值。

我不太清楚,爲什麼你每次初始化一個新的掃描儀,我認爲你應該能夠在你的程序中使用第一個掃描儀。

1

你可以有你的程序檢查每個看起來人品是否使用Character.isDigit()一個數字

http://www.tutorialspoint.com/java/character_isdigit.htm

您可能還需要讓你的數學運算符通過例如

if (Character.isDigit(input) || input == '+' || 
    input == '-' || input == '/' || input == '*') 
{ 
    // Do something with input 
} 

如果這不是你要找的,請改善你的問題,以更具體。

+0

讓我改說一下。我的意思是,如果程序找到任何角色,忽略它。將它刪除,刪除它。 – 2012-03-28 21:41:19

+0

@AbrahamAndujo:你有現有的代碼可以發佈嗎?沒有更多的上下文很難給出一個好的答案。 – 2012-03-28 21:48:46

+0

那裏,編輯我的帖子 – 2012-03-28 22:12:12