2014-11-13 3 views
-2

После ввода файла для обработки командная строка переходит к следующей строке, но остается пустой, а не для печати нужного массива. Я хочу вызвать метод getInputScanner() для создания сканера, который обращается к файлу, после того, как файл вводится пользователем, командная строка переходит к следующей строке, в отличие от обработки любого текста. Любые идеи почему?Командная строка Возврат пустой

import java.util.*; 
import java.awt.*; 
import java.io.*; 


public class Test { 
    public static void main(String [] args) { 

     Scanner console = new Scanner(System.in); 

     Scanner input = getInputScanner(console); 

     System.out.println("{" + nameArr(input) + "}"); 

    } 

    public static Scanner getInputScanner(Scanner console) { 

     System.out.print("Please enter a file to process: "); 
     File file = new File(console.next()); 
     while (!file.exists()) { 
     System.out.print("\nFile does not exists.\nPlease enter a new file name: "); 
     file = new File(console.next()); 
     } 
     try { 
     Scanner fileScanner = new Scanner(file); 
     return fileScanner; 
     } catch (FileNotFoundException e) { 
     System.out.println("File not found"); 
     } 
     return null; 
    } 

    public static String [] nameArr(Scanner input) { 

     int count = 0; 
     while (input.hasNextLine()) { 
     count++; 
     } 

     String [] nameArray = new String[count]; 

     while (input.hasNextLine()) { 

     String line = input.nextLine(); 

     for (int i = 0; i < nameArray.length; i++) { 
      nameArray[i] = lineProcess(input.nextLine()); 
     } 
     } 
     return nameArray; 
    } 

    public static String lineProcess(String line) { 
     Scanner lineScan = new Scanner(line); 

     String line2 = lineScan.nextLine(); 

     String lineString[] = line2.split(" "); 

     String name = lineString[0]; 

     return name; 

    } 


} 

ответ

0

Вы имеете и бесконечное loop, так как вы не опережения сканер призывающую input.nextLine():

while (input.hasNextLine()) { 
    count++; 
} 

я вижу другие части кода, который я вещь, что не правы, попробуйте использовать java.util.List вместо array собрать names в строках вашего обрабатываемого файла:

import java.util.*; 
import java.io.*; 

public class Test { 

    public static void main(String [] args) { 

     Scanner console = new Scanner(System.in); 

     Scanner input = getInputScanner(console); 

     List<String> nameList = nameArr(input); 
     for(String name : nameList){ 
      System.out.println("{ "+ name + " } "); 
     } 

    } 

    public static Scanner getInputScanner(Scanner console) { 

     System.out.print("Please enter a file to process: "); 
     File file = new File(console.next()); 
     while (!file.exists()) { 
      System.out.print("\nFile does not exists.\nPlease enter a new file name: "); 
      file = new File(console.next()); 
     } 
     try { 
      Scanner fileScanner = new Scanner(file); 
      return fileScanner; 
     } catch (FileNotFoundException e) { 
      System.out.println("File not found"); 
     } 
     return null; 
    } 

    public static List<String> nameArr(Scanner input) { 

     List<String> nameList = new ArrayList<String>(); 

     while (input.hasNextLine()) { 
      nameList.add(lineProcess(input.nextLine())); 
     } 
     return nameList; 
    } 

    public static String lineProcess(String line) { 

     return line.split(" ")[0]; 

    } 
} 
+0

Как так? Не будет input.hasNextLine() считать весь файл, который вводится в getInputScanner(), и тогда количество будет равно количеству строк в файле? – LeSexyNinja

+0

Если вы не продвигаете сканер, вызывающий 'nextLine()', метод 'hasNextLine()' всегда возвращает 'true'. – albciff

+0

@LeSexyNinja Я редактирую свой ответ, чтобы предложить альтернативный способ сделать это. – albciff

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