2013-03-12 2 views
0

Это простая программа, которую я написал для выполнения вычислений по целым числам из txt-файла. После нескольких часов попыток отладки я надеялся, что свежий набор глаз обнаружит некоторые из моих проблем. EDIT: data.txt содержит целые числа 1-5. Одно целое в строке.NoSuchElementException Java

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Scanner; 

public class Calculator { 

public static int[] NUMBERS; //global value for the array 

public static void main(String[] args) throws FileNotFoundException { 
    File file = new File("data.txt"); 
    Scanner sc = new Scanner(file); 

    List x = new ArrayList(); 

    while (sc.hasNextInt()) { 
     x.add(sc.nextInt()); 
    } 

    NUMBERS = new int[x.size()]; 
    Iterator<Integer> iterator = x.iterator(); 
    for (int i = 0; i < NUMBERS.length; i++) { 
     NUMBERS[i] = iterator.next().intValue(); 
    } 

    sc.close(); 

    Scanner sc2 = new Scanner(file); 

    System.out.println("Welcome to Calculation Program!\n"); 
    startMenus(sc2); 

} 

private static void startMenus(Scanner sca) throws FileNotFoundException { 
    while (true) { 
     System.out.println("(Enter option # and press ENTER)\n"); 

     System.out.println("1. Display the average of the list"); 
     System.out.println("2. Display the number of occurences of a given element in the list"); 
     System.out.println("3. Display the prime numbers in a list"); 
     System.out.println("4. Display the information above in table form"); 
     System.out.println("5. Save the information onto a file in table form"); 
     System.out.println("6. Exit"); 

     int option = sca.nextInt(); 

     sca.nextLine(); 

     switch (option) { 
      case 1: 
       infoMenu1(sca); 
       break; 
      case 2: 
       infoMenu2(sca); 
       break; 
      case 3: 
       infoMenu3(sca); 
       break; 
      case 4: 
       infoMenu4(sca); 
       break; 
      case 5: 
       infoMenu5(sca); 
       break; 
      case 6: 
       System.exit(0); 
      default: 

       System.out.println("Unrecognized Option!\n"); 
     } 

    } 
} 

private static void infoMenu1(Scanner sc2) { 
    System.out.println("The average of the numbers in the file is: " + avg(NUMBERS)); 
} 

public static double avg(int[] numbers) { 
    int sum = 0; 

    for (int i = 0; i < numbers.length; i++) { 
     sum = (sum + numbers[i]); 
    } 

    return (sum/numbers.length); 
} 

public static int occr(int[] numbers, int x) { 
    int count = 0; 

    for (int n : numbers) { 
     if (n == x) { 
      count = count + 1; 
     } 
    } 

    return count; 
} 

public static boolean prime(int x) { 
    boolean answer = true; 

    if (x == 0 || x == 1) { 
     return false; 
    } 

    for (int i = 2; i <= x/2; i = i + 1) { 
     if (i != x) { 
      if (x % i == 0) { 
       answer = false; 
      } 
     } 
    } 

    return answer; 
} 

public static int[] primes(int[] numbers) { 
    int primesCount = 0; 

    for (int i : numbers) { 
     if (prime(i)) { 
      primesCount = (primesCount + 1); 
     } 
    } 

    if (primesCount == 0) { 
     return null; 
    } 

    int[] result = new int[primesCount]; 
    int index = 0; 

    for (int i : numbers) { 
     if (prime(i)) { 
      result[index] = i; 
      index = index + 1; 
     } 
    } 

    return result; 
} 

private static void infoMenu2(Scanner sc) { 
    sc = new Scanner(System.in); 
    System.out.println("Which integer would you like to check for number of occurences?"); 
    int choice = sc.nextInt(); 

    System.out.println("The number of occurence(s) of " + choice + " are/is " + occr(NUMBERS, choice)); 


} 

private static void infoMenu3(Scanner sc2) { 
    int[] myPrimes = primes(NUMBERS); 

    System.out.println("The prime number(s) in the file are/is: "); 

    for (int j = 0; j < myPrimes.length; ++j) { 
     System.out.println(myPrimes[j] + " "); 
    } 

} 

private static void infoMenu4(Scanner kb) throws FileNotFoundException { 
    File file = new File("data.txt"); 
    Scanner sc = new Scanner(file); 

    int counter = 0; 
    while (sc.hasNextInt()) { 
     counter = counter++; 
    } 

    int lenth = counter; 

    int[] column1 = new int[lenth]; 
    while (sc.hasNextInt()) { 
     column1 = new int[sc.nextInt()]; 
    } 

    int[] column2 = new int[occr(NUMBERS, sc.nextInt())]; 

    boolean column3 = prime(sc.nextInt()); 

    System.out.printf("Average: " + "%20.2f", column1); 
    System.out.println(); 
    System.out.printf("Occurences: " + "%14d", column2); 
    System.out.println(); 
    System.out.printf("Primes:" + "%19s : %s", column3); 
    System.out.println(); 
} 

private static void infoMenu5(Scanner kb) throws FileNotFoundException { 
    File file = new File("data.txt"); 
    Scanner sc = new Scanner(file); 
    PrintWriter pw = new PrintWriter(new File("results.txt")); 

    int counter = 0; 
    while (sc.hasNextInt()) { 
     counter = counter++; 
    } 

    int lenth = counter; 

    int[] column1 = new int[lenth]; 
    while (sc.hasNextInt()) { 
     column1 = new int[sc.nextInt()]; 
    } 

    int[] column2 = new int[occr(NUMBERS, sc.nextInt())]; 

    boolean column3 = prime(sc.nextInt()); 

    pw.printf("Number: " + "%-10d", column1); 
    pw.println(); 
    pw.printf("Occurences: " + "%12d", column2); 
    pw.println(); 
    pw.printf("Primes:" + "%24s : %s", column3); 
    pw.println(); 

    pw.close(); 
} 

}

+1

Можете ли вы пост 'data.txt' контента? –

+1

Где у вас проблема? Номер строки – zdesam

+0

Поскольку ваша основная программа показывает только основные (String [] args), выдает FileNotFoundException, вам нужно показать нам всю программу. Потому что мы должны понять, где происходит исключение NoSuchElementException. –

ответ

1

Вы используете неправильный сканер в коде (строка 49). Я полагаю, вы пытаетесь получить пользовательский ввод. Однако вы используете Scanner для ввода данных из файла data.txt.

Обновлено в соответствии с комментариями. На самом деле вам не нужен сканер из data.txt в startMenus. Вам нужен пользовательский ввод. Поэтому измените sc2 на Scanner из System.in.

Оригинальная линия 31:

// Scanner sc2 = new Scanner(file); 
Scanner sc2 = new Scanner(System.in); 
+0

Это исправляет серьезную проблему. огромное спасибо – lancer

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