2016-03-05 2 views
0

Первое сообщение здесь, поэтому я надеюсь, что не испортил.Проверка определенных целых чисел в массиве

Моя задача состоит в том, чтобы пользователь вводил массив из 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 
      } 

http://pastebin.com/U5PdJgr6

Спасибо заранее!

+2

Хорошо, но каков ваш вопрос? –

+0

На ваш вопрос ответили? Если да, выберите наиболее подходящий ответ. – 4castle

ответ

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."); 
    } 

} 

} 
1

Turn

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"); 

P.S. Вам не нужно проверять, чтобы numbers.length все еще 10. Длина массива всегда final и не может измениться.

+0

Спасибо, но у меня нет большого опыта работы с обработкой исключений. Eclipse дает мне «NumberNotFoundException не может быть разрешен для типа» – Walby

+0

Я написал 'NumberNotFoundException', потому что вы упомянули, что это часть вашего проекта. Это не построенное исключение, это класс, который вам нужно создать, что расширяет «Исключение». Теперь я изменил свой ответ, чтобы вам не пришлось об этом беспокоиться. – 4castle

+0

Я также изменил цикл for на цикл foreach. – 4castle

0

Вы пытаетесь использовать «индекс» переменную вне «для» цикла, где не существует ...

0

Там же петля без вести после ввода в сравнение значения:

for (index = 0; index < numbers.length; index++) {  
    if(numbers[index] == compare){ 
     System.out.print(compare); 
    } 
] 
2

Если вы используете , вы можете легко сделать это используя IntStream

boolean contained = IntStream.of(inputtedNumbers) 
          .anyMatch(x -> x == numberToSearch); 
+1

Лямбда-выражения - величайшие вещи всех времен! Это лучший ответ, но может быть слишком продвинутым, чтобы OP полностью понял. – 4castle

+0

'import java.util.IntStream;' – 4castle

+0

@ 4castle или CTRL + MAJ + O с Eclipse –

Смежные вопросы