首先发布在这里,所以我希望我不要搞砸。
我的任务是让用户输入一个包含10个整数的数组,然后分别输入另一个整数,让程序检索该数字,如果它在数组中,或者如果没有则给出错误。
我无法将输入的整数与数组中的整数进行比较。
这是我的代码的一部分,其余部分在下面找到:
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt();
if(numbers.length==10){ //method doesnt work properly if you input over 10 integers, only if you input less
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
if(numbers[index] == compare){ //this is where the error is I believe
System.out.print(compare); //here too
}
提前谢谢!
答案 0 :(得分:2)
如果您正在使用java-8,则可以使用IntStream
boolean contained = IntStream.of(inputtedNumbers)
.anyMatch(x -> x == numberToSearch);
答案 1 :(得分:1)
打开
if (numbers[index] == compare) {
System.out.print(compare);
}
向
boolean found;
for (int number : numbers) {
found = number == compare;
if (found) break;
}
if (found) System.out.print(compare);
else throw new Exception("Number Not Found");
PS 您不需要检查以确保numbers.length
仍为10.数组的长度始终为final
且无法检查变化
答案 2 :(得分:0)
package integerarrayexceptions;
import java.util.Scanner;
import java.util.InputMismatchException;
public class IntegerArrayExceptions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numbers[] = new int[10];
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt(); //The loop only applies to this statement.
if(numbers.length==10){
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
for (int index2 = 0; index2 < numbers.length; index2++) {
if(numbers[index2] == compare){
System.out.print(compare);
}
}
}
}
catch (InputMismatchException MismatchException)
{
System.out.print("One or more values entered is not an integer.");
}
}
}
答案 3 :(得分:0)
您尝试使用变量&#34; index&#34; &#34; for&#34;循环,它不存在......
答案 4 :(得分:0)
输入比较值后,有一个循环缺失:
for (index = 0; index < numbers.length; index++) {
if(numbers[index] == compare){
System.out.print(compare);
}
]