2015-11-19 124 views
0

我的程序應該檢查一個整數是否在一個隨機整數中。它會返回true或false。例如:45903包含4:true。因爲某些原因;我輸入數字後,我的代碼仍在運行。有些事情是我的containsDigit()方法錯了,但我似乎無法弄清楚。我對布爾非常新。從方法返回布爾值

import java.util.Scanner; 
import java.util.*; 

public class checkNum { 


public static void main(String[] args) { 

    // Create a new Scanner object 
    Scanner console = new Scanner(System.in); 
    // Create a new Random objects 
Random rand = new Random(); 

    // Declare a integer value that is getting the value in the range of[10000, 99999] 
    int randomNum = rand.nextInt(90000)+10000; 

    // Show the random value to user by using of System.out.println 
System.out.println(randomNum); 

    // Type a prompt message as "Enter a digit" 
System.out.println("Enter a digit: "); 

    // Assign user input to integer value 
    int digit = console.nextInt(); 

    // Define a boolean value that is assigned by calling the method "containDigit(12345,5)" 

    // Show the output 
    System.out.println(randomNum+ " contains" + 
        digit+" " + containDigit(randomNum,digit)); 

} 

public static boolean containDigit(int first, int second) { 
    int digi = 10000; 

    // Define all statements to check digits of "first" 
    while (first > 0) { 
    digi = first % 10; 
    digi = first/10; 
} 

    if (digi == second){ 
    return true; 
    }else { 
    return false; 
    } 
    // If it has "second" value in these digits, return true, 
    // If not, return false 

    // return a boolean value such as "return false"; 
    return false; 
} 

} 
+0

時間來學習如何使用調試器。 –

+0

由於無限循環而永久運行。 'while(first> 0)'。 '第一個'總是大於0.它的'digi'值和'first'的值保持相同,即'> 0' –

回答

1

我不明白你爲什麼要指定first %10digi,然後立即用first/10覆蓋digi

while循環可能永遠不會退出的first可能總是大於0。這可能永遠不會被輸入爲first可能等於0您可能要做到這一點:

while (first/10 == 0) { 
    first = first % 10; 
    if (first == second) 
     return true; 
    } 
    if(first%10 == second) 
    return true; 

return false; 
1

while循環永遠不會退出:

while (first > 0) { 
    digi = first % 10; 
    first = first/10; // i believe this should be first instead of digit   
} 

您應該添加一個簡單print語句來檢查你的digitfirst變量的值是:

System.out.println("digi: "+digi); 
System.out.println("first: "+first); 
2

如果你不限於解決方法,我可以在下面建議:

return (randomInt + "").contains(digit + ""); 
+0

你的意思是'return(String.valueOf(randomInt))。contains String.valueOf(digit))',對嗎? – Suvitruf

+0

是的,你寫的是正確的方法。你也可以使用Integer.toString(i)。當你用字符串連接int時,編譯器將int轉換爲字符串,然後做concat,result是一個新的字符串。 – hsnkhrmn