2016-08-30 7 views
-4

Я пытаюсь сделать передать свой код с кодом, который имеет методы вместоошибка: массив требуется, но строка найдено

Я переходила все вещи, но я получаю сообщение об ошибке во всем

редактировать 4 :

Мой Оригинальный код:

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

 
public class Testing1 
 
{ 
 
    public static void main(String[] myFile) 
 
    { 
 
    \t //This array will serve as the storage for the integers. 
 
     Integer [] listOfIntegers = new Integer[10000]; 
 
     Integer index = new Integer(0); 
 
     int count = 0; 
 
    \t \t  
 
     if(myFile.length == 0) 
 
     { 
 
      //This prompt will show when no input detected on the command line arguments. 
 
     System.out.println("Please input the file name."); 
 
     } 
 
     else 
 
     { 
 
      //Otherwise, it will read the text file. 
 
     File data = new File(myFile[0]); 
 
     Scanner inputData = null; 
 
     try 
 
     { 
 
      \t //This will create a connection to the file. 
 
      inputData = new Scanner(data); 
 
     } 
 
     catch (FileNotFoundException exception) 
 
     { 
 
      \t \t //This message will appear when the text file entered doesn't exist. 
 
      System.out.print("ERROR: File not found for: \""); 
 
      System.out.println(myFile[0]+ "\""); 
 
     } 
 
      //If the text file does exist, it will go through the file. 
 
     if (inputData != null) 
 
     { 
 
      System.out.print("number of integers in file " + " \""); 
 
      System.out.println(myFile[0] + "\""); 
 
      
 
      while (inputData.hasNextLine()) 
 
      { 
 
       try 
 
       { 
 
       \t //reads an integer in a line of text  
 
        Integer element = inputData.nextInt(); 
 
        listOfIntegers[count] = element; 
 
       \t \t //prints out the integer and and its index in the array 
 
        System.out.println("index = " + index + ", element = " + element); 
 
        index ++; 
 
        count ++; 
 
       } 
 
       catch (InputMismatchException e) 
 
       { 
 
        String word = inputData.next(); 
 
       } 
 
       catch (NoSuchElementException e) 
 
       { 
 
       \t \t //to avoid program crashing against this exception. 
 
       } 
 
      }//end of while 
 
      System.out.print("\nTotal number of integers in file: " + " \""); 
 
      System.out.println(myFile[0] + "\"" + " = " + count); 
 
     }//end of if \t 
 
     }//end of else  
 
    }//end of main 
 
}//end of class

рабочий код теперь, но нулевые значения, отображаемые для элемента, и не останавливаются на предполагаемом индексе входного файла.

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

 
public class Testing1 
 
    public static void main(String[] args)throws InputMismatchException 
 
    { 
 
     if(args.length == 0) 
 
     { 
 
      //This prompt will show when no input detected on the command line arguments. 
 
     System.out.println("Please input the file name."); 
 
     } 
 
     else 
 
     { 
 
     Integer[] array = Testing1.readFileReturnIntegers(args[0]); 
 
     Testing1.printArrayAndIntegerCount(array, args[0]); 
 
     } 
 
    }// end of main 
 
     
 
    public static Integer []readFileReturnIntegers(String inputData) 
 
    { 
 
     Integer [] listOfIntegers = new Integer[10000]; 
 
     Integer index = new Integer(0); 
 
     int count = 0; 
 
     
 
     File data = new File(inputData); 
 
     Scanner inputReader = null; 
 
     try 
 
     { 
 
      \t //This will create a connection to the file. 
 
     inputReader = new Scanner(data); 
 
     } 
 
     catch (FileNotFoundException exception) 
 
     { 
 
      \t \t //This message will appear when the text file entered doesn't exist. 
 
     System.out.print("ERROR: File not found for: \""); 
 
     System.out.println(inputData+ "\""); 
 
     } 
 
      //If the text file does exist, it will go through the file. 
 
     if (inputData != null) 
 
     { 
 
     System.out.print("number of integers in file " + " \""); 
 
     System.out.println(inputData + "\""); 
 
        while (inputReader.hasNextLine()) 
 
     { 
 
      try 
 
      { 
 
       \t //reads an integer in a line of text  
 
       Integer element = inputReader.nextInt(); 
 
       listOfIntegers[count]=element; 
 
       \t \t //prints out the integer and and its index in the array 
 
       System.out.println("index = " + index + ", element = " + element); 
 
       index ++; 
 
       count ++; 
 
      } 
 
      catch (InputMismatchException e) 
 
      { 
 
       String word = inputReader.next(); 
 
      } 
 
      catch (NoSuchElementException e) 
 
      { 
 
       \t \t //to avoid program crashing against this exception. 
 
      } 
 
     }//end of while 
 
     } 
 
       
 
     return listOfIntegers;    
 
    }//end of readFileReturnIntegers 
 
     
 
    public static void printArrayAndIntegerCount(Integer [] array, String inputData) 
 
    { 
 
     int count = 0; 
 
     System.out.print("\nTotal number of integers in file: " + " \""); 
 
     System.out.println(inputData + "\"" + " = " + count); 
 
     
 
    }//end of printArrayAndIntegerCount 
 
      
 
}//end of class

моя ошибка:

Testing1.java:81: error: cannot find symbol 
 
     return array;    
 
      ^
 
    symbol: variable array 
 
    location: class Testing1 
 
1 error

Я хотел вывести целые числа из входных файлов electricity.txt и 1000txt.

number of integers in file "electricity.txt" = 4 
 
    index = 0, element = 1877 
 
    index = 1, element = 1923 
 
    index = 2, element = 1879 
 
    index = 3, element = 2000

и этот

number of integers in file "1000.txt" = 1001 
 
    index = 0, element = 1000 
 
    index = 1, element = 2 
 
    index = 2, element = 3 
 
    index = 3, element = 5 
 
    index = 4, element = 7 
 
    index = 5, element = 11 
 
    index = 6, element = 13 
 
    index = 7, element = 17 
 
    index = 8, element = 19 
 
    index = 9, element = 23 
 
    to index 1000 and element 7919

+1

Непонятно, что вы просите. Пожалуйста, прочитайте [ask] и [mcve]. – xenteros

+2

Этот заголовок будет соответствовать 99% сообщений здесь. Можете ли вы придумать более описательное название? – Henry

+0

'public static Integer [] readFileReturnIntegers (String inputData)' является причиной ошибки 'File data = new File (inputData [0]);' (first errror) – emotionlessbananas

ответ

0

Вот обновленный ответ

Лучше использовать ArrayList в этот случай, поэтому мы можем создать динамический массив.
, где это невозможно с массивом.

import java.util.Scanner; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.InputMismatchException; 
import java.util.NoSuchElementException; 
import java.util.ArrayList; 

public class Testing1 { 
    public static void main(String[] args)throws InputMismatchException 
    { 
     if(args.length == 0) 
     { 
      //This prompt will show when no input detected on the command line arguments. 
     System.out.println("Please input the file name."); 
     } 
     else 
     { 
     ArrayList<Integer> array = Testing1.readFileReturnIntegers(args[0]); 
     Testing1.printArrayAndIntegerCount(array, args[0]); 
     } 
    }// end of main 

    public static ArrayList<Integer> readFileReturnIntegers(String inputData) 
    { 
     ArrayList<Integer> listOfIntegers = new ArrayList<Integer>(); 
     int count = 0; 

     File data = new File(inputData); 
     Scanner inputReader = null; 
     try 
     { 
       //This will create a connection to the file. 
     inputReader = new Scanner(data); 
     } 
     catch (FileNotFoundException exception) 
     { 
        //This message will appear when the text file entered doesn't exist. 
     System.out.print("ERROR: File not found for: \""); 
     System.out.println(inputData+ "\""); 
     } 
      //If the text file does exist, it will go through the file. 
     if (inputData != null) 
     { 
     System.out.print("number of integers in file " + " \""); 
     System.out.println(inputData + "\""); 
        while (inputReader.hasNextLine()) 
     { 
      try 
      { 
        //reads an integer in a line of text  
       Integer element = inputReader.nextInt(); 
       listOfIntegers.add(element); 
        //prints out the integer and and its index in the array 
       System.out.println("index = " + count + ", element = " + element); 
       count ++; 
      } 
      catch (InputMismatchException e) 
      { 
       String word = inputReader.next(); 
      } 
      catch (NoSuchElementException e) 
      { 
         //to avoid program crashing against this exception. 
      } 
     }//end of while 
     } 

     return listOfIntegers;    
    }//end of readFileReturnIntegers 

    public static void printArrayAndIntegerCount(ArrayList<Integer> array, String filename) 
    { 
     System.out.print("\nTotal number of integers in file: " + " \""); 
     System.out.println(filename + "\"" + " = " + array.size()); 

    }//end of printArrayAndIntegerCount 

}//end of class 
0

Testing1.java:40, удалить [0]

File data = new File(inputData); 

само ваше имя файла inputData, поэтому используйте inputData вместо inputData [0] всюду в System.out.println

+0

, вы должны объяснить, почему вы сделали это, чтобы обеспечить ясность. – emotionlessbananas

+0

Позвольте мне просто отредактировать в том, что я хотел сделать извините. – aldz24

+0

Lemme добавьте исходный код, который я пытался преобразовать в нужные методы а не то, что у меня было.мне пришлось реорганизовать формат, так как есть readfilereturnintegers, а затем printarrayreturnintegers stuff – aldz24

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