java - 从方法返回 boolean 值

标签 java if-statement boolean

我的程序应该检查一个整数是否是随机整数。它将返回 true 或 false。例如:45903包含4:true。因为某些原因;我输入数字后,我的代码继续运行。我的 containsDigit() 方法出了点问题,但我似乎无法弄清楚。我对 boolean 值很陌生。

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

} 

最佳答案

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

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

关于java - 从方法返回 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815253/

相关文章:

java - 我的 boolean 值对于任何等于或大于 1000 的值都会返回 false,为什么?

java - LibGDX ScrollPane 显示黑屏

java - 为什么顶级类在 Java 中不能是静态的?

JAVA试图寻找年度最佳职位。不工作

C++- If 语句问题。代码将不会运行 else 或 else if

list - 将 Mathematica 值列表转换为 boolean 值列表

java - 如何设置 JSP 页面的 URL?

java - Spring MVC 仅发布选定的数据

C: 嵌套的 Ifs 或 Gotos

php - Boolean和Integer是序列化后的字符串