我正在尝试编写Java代码(方法)以验证用户ID。提示用户输入一个ID。如果用户以数字1开头-这将显示为无效!!!我将不胜感激!谢谢
public static void main(String[] args) {
//creating an array of 10
int[] num = new int[10];
//asking user to enter a number
Scanner kb = new Scanner(System.in);
System.out.println("Enter and id number : ");
num = kb.nextInt();
//calling method
GetValidInteger(num);
}
//method
static void GetValidInteger(int[] num) {
//looping through the array to get the numbers
for (int i = 0; i < num.length; i++) {
//if num at index 0 is 1 print out invalid
if (num[0] == 1) {
System.out.println("The number you have entered :" + num + " starts with 1 and is invalid");
}
//else print out valid
else {
System.out.println("The number you have entered :" + num + " is valid");
}
}
}
我遇到错误:int cannot be converted into int[]!
在此行:num = kb.nextInt();
答案 0 :(得分:1)
您将int
而不是int[]
传递给方法GetValidInteger
。
进行如下更改:
// Renamed with a starting lower case because a starting uppercase char is used
// normally for class and interface names.
public static void getValidInteger(int num) {
// Consider the string representation of that num
String str = String.valueOf(num);
// Get the first character of the string version of the int num
if (str.charAt(0) == '1') {
System.out.println("The number you have entered :" + num
+ " starts with 1 and is invalid");
} else {
System.out.println("The number you have entered :" + num + " is valid");
}
}
答案 1 :(得分:0)
您正在将一个int分配给一个int数组。那就是为什么你有一个错误。我不明白为什么要使用数组。使用循环,将要求用户输入ID,直到正确为止。
public class Test
{
public static void main(String[] args)
{
int currentId;
while (true)
{
//asking user to enter a number
Scanner kb = new Scanner(System.in);
System.out.println("Enter and id number : ");
currentId = kb.nextInt();
//calling method
if (GetValidInteger(currentId))
{
//If the id is valid, you re out from the loop, if not retry
break;
}
}
}
//method
static boolean GetValidInteger(int currentId)
{
boolean isValidId = false;
boolean doesIdStartWith1 = String.valueOf(currentId).startsWith("1");
//if num at index 0 is 1 print out invalid
if (doesIdStartWith1)
{
System.out.println("The number you have entered :" + currentId + " starts with 1 and is invalid");
}
else
{
//else print out valid
System.out.println("The number you have entered :" + currentId + " is valid");
isValidId = true;
}
return isValidId;
}
}