从方法返回布尔值

时间:2015-11-19 22:08:16

标签: java if-statement boolean

我的程序应该检查整数是否是随机整数。它将返回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;
 } 

} 

3 个答案:

答案 0 :(得分:2)

如果您不受解决方案的限制,我可以在下面建议:

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

答案 1 :(得分: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 :(得分:1)

我不明白为什么要将first %10分配给digi,然后立即用digi覆盖first / 10

你的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;