2015-11-08 3 views
1

Это мой калькулятор и устройство чтения файлов, которое я создал. Но когда я ввожу имя файла для своей программы для чтения, он читает файл, который представляет собой текстовый документ, содержащий 24 суммы, например «10 10 +». Однако моя программа читает только около 11 из них, а затем возвращает ошибку, говоря:нужна помощь с подтверждением для моего калькулятора

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 
    at Calculator.main(Calculator.java:104) 

Что я упускаю, чтобы иметь возможность исправить ошибку? Благодарю.

import java.util.Scanner; 
import java.io.File; 
import java.io.FileNotFoundException; 

public class Calculator { 


    public static void main(String[] args) { 
     String option; 
     while(true){ 
      Scanner scanner3 = new Scanner(System.in); 
      System.out.println("Please input the letter K for keyboard or F for file entry:"); 
      option=scanner3.nextLine();  

      switch(option) 
      { 

      case "K": 
       Scanner scanner = new Scanner(System.in); 
       System.out.println("Please enter an expression:"); 
       String line = scanner.nextLine(); 

       if (line.equals("")) 
       { 
        System.out.println("Calculator Closing"); 
        System.exit(0); 

       } 

       char letter; 
       String [] elements = line.split(" "); 
       double number1 = 0, number2 = 0; 

       if (elements.length == 3)   // 3 elements entered validation 
       { 

        try{ 

         number1 = Double.parseDouble(elements[0]); 
         number2 = Double.parseDouble(elements[1]); 
        } 

        catch (NumberFormatException e) { 

         System.out.println("Error"); 
        } 


        if (elements[2].equals("-"))   //validation for when the expressions are entered 
        { 
         System.out.println("Result as follows:" + (number1 - number2)); 
        } 
        else if (elements[2].equals("/")) 
        { 
         System.out.println("Result as follows:" + (number1/number2)); 
        } 
        else if (elements[2].equals("*")) 
        { 
         System.out.println("Result as follows:" + (number1 * number2)); 
        } 
        else if (elements[2].equals("+")) 
        { 
         System.out.println("Result as follows:" + (number1 + number2)); 
        } 


       } 
       else if(elements.length != 3){   //validation to check that all 3 elements have been entered 
        System.out.println("Invalid number of elements entered"); 



       } 
       break;    // separates the code 
      case "F": 
       try{ 


        System.out.println("Please enter the filename:"); 
        Scanner file = new Scanner (System.in); 
        String filename = file.nextLine(); 
        Scanner s = new Scanner(new File(filename)); // creates a scanner which scans from a file 


        boolean value = true; 
        while (value){ 
         while (s.hasNext()) { 

          line = s.nextLine();  // reads the next line of text from the file 

          String [] fileinput = line.split(" "); 
          double expression1 = 0, expression2 = 0; 

          try{ 

           expression1 = Double.parseDouble(fileinput[0]); 
           expression2 = Double.parseDouble(fileinput[1]); 
          } 

          catch (NumberFormatException e) { 

           System.out.println("error"); 
          } 
          if (fileinput[2].equals("-")) 
          { 
           System.out.println("Result as follows:" + (expression1 - expression2)); 
          } 
          else if (fileinput[2].equals("/")) 
          { 
           System.out.println("Result as follows:" + (expression1/expression2)); 
          } 
          else if (fileinput[2].equals("*")) 
          { 
           System.out.println("Result as follows:" + (expression1 * expression2)); 
          } 
          else if (fileinput[2].equals("+")) 
          { 
           System.out.println("Result as follows:" + (expression1 + expression2)); 
          } 


         } 
         System.out.println("\nEOF");   // Outputs the End Of File message 
         value = false;  
        } 
       } 
       catch(FileNotFoundException ef) { 
        System.out.println("Error, please enter a correct file name."); 
       } 
       break; 
      default: 
       System.out.println("invalid letter entered"); 

      }   
     } 
    }} 
+0

проверить длину массива 'fileinput'. –

+0

Убедитесь, что ваш файл отформатирован правильно. Также вы должны сделать '.split (" \\ s + ");' вместо '.split (" ");' – 3kings

+0

файл, который я хочу, чтобы моя программа читала, - это текстовый документ, содержащий это: – Whitaker96

ответ

0

Я проверить свой код с моим собственным текстовым файлом один после операции исправления в каждой строке, она работает без Exception (без проблем), вы должны проверить файл, если есть какая-то ошибка в вашей операции вводе.

Но в вашем коде есть некоторые замечания: -Вы должны использовать один сканер для каждого источника, например System.in или new File("name of file"). - Для сканера с клавиатуры (System.in) рекомендуется использовать статическую переменную Scanner, например: private static Scanner scanner = new Scanner(System.in);.

0

На ваш вход отсутствует один положительный вход в строке, которую он пытается прочитать. Это означает, что ваш String [] fileinput не будет содержать 3 элемента в строке, которая не будет печататься. Я взял на себя смелость разделить ваш вклад в группы по 3:

44 3 + 
9.99 + 0.09 
12 0 * 
. 10 - 
10.2 2 * 
12 4/
66.1 0.12 - 
.0 99.10 + 
300 4.0 + 
* 20 10 
/10 20 
5.2 + 1 
2 & 100 
139 - - 
80 2 9 
5 2 4 
/3 3 
A - 200.5 
10 * 2 
* 4 8 
2 * 10 
20 - 8 
16/-4 
12 + + 
4 2 x 
y z 

Вы можете ясно видеть на последней строке, что есть один вход отсутствует. Исключение будет выбрано при вызове fileinput[2].

0

Здесь вы решите вашу проблему.


import java.util.Scanner; 
import java.io.File; 
import java.io.FileNotFoundException; 

public class Calculator { 

    public static void main(String[] args) { 
     String option; 
     while (true) { 
      Scanner scanner3 = new Scanner(System.in); 
      System.out.println("Please input the letter K for keyboard or F for file entry:"); 
      option = scanner3.nextLine(); 

      switch (option) { 

       case "K": 
        Scanner scanner = new Scanner(System.in); 
        System.out.println("Please enter an expression:"); 
        String line = scanner.nextLine(); 

        if (line.equals("")) { 
         System.out.println("Calculator Closing"); 
         System.exit(0); 

        } 

        char letter; 
        String[] elements = line.split(" "); 
        double number1 = 0, 
        number2 = 0; 

        if (elements.length == 3) // 3 elements entered validation 
        { 

         try { 

          number1 = Double.parseDouble(elements[0]); 
          number2 = Double.parseDouble(elements[1]); 
         } catch (NumberFormatException e) { 

          System.out.println("Error"); 
         } 

         switch (elements[2]) { 
          //validation for when the expressions are entered 
          case "-": 
           System.out.println("Result as follows:" + (number1 - number2)); 
           break; 
          case "/": 
           System.out.println("Result as follows:" + (number1/number2)); 
           break; 
          case "*": 
           System.out.println("Result as follows:" + (number1 * number2)); 
           break; 
          case "+": 
           System.out.println("Result as follows:" + (number1 + number2)); 
           break; 
         } 

        } else if (elements.length != 3) {   //validation to check that all 3 elements have been entered 
         System.out.println("Invalid number of elements entered"); 

        } 
        break;    // separates the code 
       case "F": 
        try { 

         System.out.println("Please enter the filename:"); 
         Scanner file = new Scanner(System.in); 
         String filename = file.nextLine(); 
         Scanner s = new Scanner(new File(filename)); // creates a scanner which scans from a file 

         boolean value = true; 
         while (value) { 
          while (s.hasNext()) { 

           line = s.nextLine();  // reads the next line of text from the file 

           String[] fileinput = line.split(" "); 
           double expression1 = 0, expression2 = 0; 

           try { 
            expression1 = Double.parseDouble(fileinput[0]); 
            expression2 = Double.parseDouble(fileinput[1]); 
            switch (fileinput[2]) { 
             case "-": 
              System.out.println("Result as follows:" + (expression1 - expression2)); 
              break; 
             case "/": 
              System.out.println("Result as follows:" + (expression1/expression2)); 
              break; 
             case "*": 
              System.out.println("Result as follows:" + (expression1 * expression2)); 
              break; 
             case "+": 
              System.out.println("Result as follows:" + (expression1 + expression2)); 
              break; 
            } 
           } catch (Exception e) { 
            System.out.println("Syntax error in the expression - \"" + line + "\". Proceeding to next expression."); 
           } 
          } 
          System.out.println("\nEOF");   // Outputs the End Of File message 
          value = false; 
         } 
        } catch (FileNotFoundException ef) { 
         System.out.println("Error, please enter a correct file name."); 
        } 
        break; 
       default: 
        System.out.println("invalid letter entered"); 
      } 
     } 
    } 
} 

Если это работает, любезно пометить его как принято.

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