2016-03-17 6 views
0

Я пытаюсь написать программу, которая может обнаружить самую большую сумму, которая может быть сделана с любым подмножеством чисел в ArrayList, и сумма должна быть ниже целевого номера пользователя. Моя программа работает безупречно до сих пор, за исключением одной строки (каламбур не предназначен). Имейте в виду, что этот код еще не завершен.Зачем нужна InputMismatchException? (Java)

По какой-то причине я продолжаю получать необычное исключение InputMismatchException в строке, указанной ниже, при вызове моего сканера. Когда я запускаю программу и попросить его применить список по умолчанию (как вы увидите в коде), я получаю необычный выход

Enter integers (one at a time) to use, then type "done" 
OR 
You can just type "done" to use the default set 
done //User Input here 
Done 
Enter your target number 

После этой линии, исключение, и я выгнал из программа (записывается и запускается в BlueJ). Вы, ребята, думаете, что можете мне помочь? Я предполагаю, что это просто «грамматическая» ошибка, если вы знаете, что я имею в виду. Код ниже:

import java.util.*; 
/** This program will provide the largest sum of numbers within a set that is less than a user-implied target number. This is done by asking for a user input of integers (or none, for a default set), sorting the list, and calulating the highest sum starting with the largest number and moving downward on the set 
    @param input A Scanner used to detect user input 
    @param user A placeholder for user-implied integers 
    @param target The user-implied target number 
    @param index A reference to the currently "targeted" index on "list" 
    @param splitIndex Used if the list needs to be checked in non-adjacent indexes 
    @param finalOutput The final product of this program 
    @param list An ArrayList of Integers used as the set*/ 
class LargestSum{ 
    public static void main(String[] args){ 
     Scanner input = new Scanner(System.in); 
     int user = 0, target = 0, index = 0, finalOutput = 0, splitIndex = 0; 
     ArrayList<Integer> list = new ArrayList<Integer>(); 
     System.out.println("Enter integers (one at a time) to use, then type \"done\" \nOR\n You can just type \"done\" to use the default set"); 
     /** A try-catch block is used to detect when the user has finished ading integers to the set*/ 
     try{ 
      user = input.nextInt(); 
      list.add(user); 
     } 
     catch(InputMismatchException e){ 
      System.out.print("Done"); 
      if (list.size() == 0){ 
       list.add(1); 
       list.add(2); 
       list.add(4); 
       list.add(5); 
       list.add(8); 
       list.add(12); 
       list.add(15); 
       list.add(21); 
      } 
      if (list.size() > 0){ 
      Collections.sort(list); 
      System.out.println("\nEnter your target number"); 
      target = input.nextInt();   //EXCEPTION IS THROWN HERE 
      index = list.size() - 1; 
      while (list.get(index) > target){     
       list.remove(index); 
       index = index - 1; 
       if (index == -1){ 
        System.out.println("No sum can be made that is lower than the target number"); 
        System.exit(0); 
       } 
      }   
      while (finalOutput < target){ 
       if(list.get(index) + list.get(index - 1) < target){ 
        finalOutput = list.get(index) + list.get(index - 1); 
        list.remove(index); 
        list.remove(index - 1); 
        list.add(finalOutput); 
        index = list.size() - 1; 
       } 
       else{ 
        for (int i = index; i >= 0; i--){ 
         if (list.get(i) + list.get(index) < target){ 
          finalOutput = list.get(i) + list.get(index); 
          list.remove(i); 
          list.remove(index); 
          list.add(finalOutput); 
          index = list.size() - 1; 
          i = index; 
         } 
        } 
       } 
      } 
     } 
      System.out.println("Done!"); 
      System.out.println("Largest Sum is: " + finalOutput); 
     } 
    }   
} 

Спасибо, ребята, и вы можете игнорировать комментарии к документации. Как я уже сказал, программа еще не совсем завершена, и я планирую добавить больше.

~ AndrewM

+1

Как только вы получите InputMismatchException, вам нужно использовать эту фразу 'done'. См. Это [ответ] (http://stackoverflow.com/questions/3572160/how-to-handle-invalid-input-using-scanner-and-try-catch-currently-have-an-infin) – Bunti

+0

Это сделало это ! Спасибо, приятель, если вы ответите, я с радостью дам вам чек. –

+0

Рад, что это вам помогло. Я не безумно участвую в гонке за баллы. Моя цель - помочь людям всеми возможными способами. – Bunti

ответ

0

вам нужно позвонить input.nextLine(); для того, чтобы позволить сканеру взять в другой строке ввода. Прямо сейчас input.nextInt() пытается преобразовать Done в int, вызывая InputMismatchException, потому что он использует ту же строку ввода, которую вы ввели ранее.

input.nextLine(); 
System.out.println("\nEnter your target number"); 
target = input.nextInt();   //EXCEPTION IS THROWN HERE 
+0

Это дает мне ошибку Несовместимого типа. «Строка не может быть преобразована в int» –

+0

@AndrewM Вы должны помещать ее в неправильное место. Я обновил свой ответ с помощью примера кода, это работает для меня. –

0

вопрос здесь - пользователь = input.nextInt(); Пока вы не зацепите целые числа через nextInt(), ваш код будет прекрасным. Но вы получаете inputMistmathexception, когда предоставляете «сделанную» для этой функции, которая явно InputMismatchException.Hope, которая помогает.

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