从方法返回布尔值

Returning a Boolean from a method

我的程序应该检查一个整数是否在随机整数中。它将 return 真或假。例如:45903 包含 4:true。因为某些原因;输入数字后,我的代码保持 运行。我的 containDigit() 方法有些问题,但我似乎无法弄清楚。我是布尔值的新手。

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 循环永远不会退出:

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);

如果你的解决方法不受限制,我可以建议如下:

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

我不明白你为什么要将 first %10 分配给 digi 然后立即用 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;