从方法返回布尔值
问题描述:
我的程序应该检查一个整数是否在一个随机整数中。它会返回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;
}
}
答
我不明白你为什么要指定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;
答
while循环永远不会退出:
while (first > 0) {
digi = first % 10;
first = first/10; // i believe this should be first instead of digit
}
您应该添加一个简单print
语句来检查你的digit
和first
变量的值是:
System.out.println("digi: "+digi);
System.out.println("first: "+first);
时间来学习如何使用调试器。 –
由于无限循环而永久运行。 'while(first> 0)'。 '第一个'总是大于0.它的'digi'值和'first'的值保持相同,即'> 0' –