我的程序應該檢查一個整數是否在一個隨機整數中。它會返回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;
}
}
時間來學習如何使用調試器。 –
由於無限循環而永久運行。 'while(first> 0)'。 '第一個'總是大於0.它的'digi'值和'first'的值保持相同,即'> 0' –