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