我不太确定这里发生了什么。
代码应该根据固定ID号数组验证输入。但每当我故意输入错误的数字时,就会说"数组超出范围"。
对导致问题的原因不太确定,也许有人可以指出我的错误?
import java.util.Scanner;
public class isValid
{
static int accNum[] = {11111, 22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999, 10101, 20202, 30303, 40404, 50505, 60606, 70707, 80808, 90909};
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int conti = -99;
int search = 0;
do
{
System.out.print("Enter 5-digit account number you want to validate: ");
search = keyboard.nextInt();
sequentialSearch(accNum, search);
System.out.println("");
System.out.print("Enter -9 to exit program, or any other number to validate another ID: ");
conti = keyboard.nextInt();
} while (conti != -9);
}
public static void sequentialSearch(int[] array,int value)
{
int index = 0;
int element = -1;
boolean found = false;
while (!found && index < array.length)
{
if (array[index] == value)
{
found = true;
element = index;
break; //prevent index addition if value found
}
index++;
}
if (array[index] == value)
{
System.out.println("Account " + value + " is valid.");
}
else
{
System.out.println("Account " + value + " is invalid.");
}
}
}
答案 0 :(得分:1)
我修改了代码,它应该是这样的:
import java.util.Scanner;
public class isValid
{
static int accNum[] = {11111, 22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999, 10101, 20202, 30303, 40404, 50505, 60606, 70707, 80808, 90909};
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int conti = -99;
int search = 0;
do
{
System.out.print("Enter 5-digit account number you want to validate: ");
search = keyboard.nextInt();
sequentialSearch(accNum, search);
System.out.println("");
System.out.print("Enter -9 to exit program, or any other number to validate another ID: ");
conti = keyboard.nextInt();
} while (conti != -9);
}
public static void sequentialSearch(int[] array,int value)
{
int index = 0;
int element = -1;
boolean found = false;
while (!found && index < array.length)
{
if (array[index] == value)
{
found = true;
element = index;
break; //prevent index addition if value found
}
index++;
}
if (found)
{
System.out.println("Account " + value + " is valid.");
}
else
{
System.out.println("Account " + value + " is invalid.");
}
}
}
注意在sequentialSearch函数的while循环之后if条件的变化。
为什么?由于索引等于超出数组索引的值,以防数组中不存在该值。
答案 1 :(得分:1)
好的,我真的很抱歉我以前的解决方案有点愚蠢,但现在我可以建议你解决方案的第二种方式就是这样做,
while (!found && index < accNum.length)
{
if (accNum[index] == value)
{
found = true;
element = index;
System.out.println("Account " + value + " is valid.");
}
else
{
System.out.println("Account " + value + " is invalid.");
break;
}
index++;
}
描述: - 您的值将匹配一次并打印valid
消息。如果它与值不匹配,那么它将打印无效消息并且循环将中断。