2014-11-07 3 views
0

Я начинаю работать с java и работаю над программой, которая будет читать текстовый файл. Текстовый файл выглядит следующим образом:Чтение номеров в текстовом файле и вычисление всего в java

Chicago Fire : FC Dallas : 2 : 2 
LA Galaxy : Toronto FC : 1 : 3 
Real Salt Lake : DC United : 3 : 2 
Colorado Rapids : Columbus Crew : 0 : 0 
Sporting Kansas City : New York Red Bulls : 2 : 1 

Я хочу, чтобы мой код, чтобы прочитать все номера в файле, а затем отобразить общую сумму в конце так он выглядит:

Chicago Fire : FC Dallas : 2 : 2 
LA Galaxy : Toronto FC : 1 : 3 
Real Salt Lake : DC United : 3 : 2 
Colorado Rapids : Columbus Crew : 0 : 0 
Sporting Kansas City : New York Red Bulls : 2 : 1 

Total goals = 16 

мой код до сих пор:

public void showResults(){ 

     String separator = ":"; 
     File inputfile = new File ("result.txt"); 

     String[] StrArray; 
     String aLine = ""; 

     System.out.println ("Home team   "+"\tHome score" + "         " + "\t Away Team" + "\t Away Score \n============================================================================="); 

     try { 
      Scanner filescan = new Scanner(inputfile); 
      while (filescan.hasNext()){ 
       aLine = filescan.nextLine(); 
       StrArray = aLine.split(separator); 


       if (StrArray.length == 4){ 
        System.out.println (StrArray[0] +"\t" + StrArray [2] + StrArray[1] + "\t" + StrArray[3]); 
       } else { 
        throw new IllegalArgumentException("Invalid match count : "+ aLine); 
       } 

      } 

      filescan.close(); 


     } 

     catch (FileNotFoundException e) 
     { 
      System.out.println("problem "+e.getMessage()); 

     } 


    } 

} 

Iv пытался сделать это сам, но просто не могу понять, что любая помощь будет высоко ценится, спасибо!

+1

Используйте 'xml' вместо если возможно. вам будет легко поддерживать данные. –

+0

В чём проблема? Где ваш код не делает то, что вы ожидаете? – mkobit

ответ

0

Предлагаю вам сделать способ static, использовать try-with-resources, пройти в filePath для чтения, используйте форматированный вывод и шаблон, который комки пустое белое-пространство, как,

public static void showResults(String filePath) { 
    String separator = "\\s*:\\s*"; 
    File inputfile = new File(filePath); 
    String[] heading = { "Home team", "Home score", "Away team", 
      "Away score" }; 
    for (int i = 0; i < heading.length; i++) { 
     String fmt = "%20s "; 
     if (i % 2 != 0) 
      fmt = "%12s "; 
     System.out.printf(fmt, heading[i]); 
    } 
    System.out.println(); 
    for (int i = 0; i < 68; i++) { 
     System.out.print('='); 
    } 
    System.out.println(); 
    int goals = 0; 
    try (Scanner filescan = new Scanner(inputfile);) { 
     while (filescan.hasNext()) { 
      String aLine = filescan.nextLine(); 
      String[] tokens = aLine.split(separator); 
      if (tokens.length == 4) { 
       System.out.printf("%20s %12s %20s %12s%n", tokens[0], 
         tokens[2], tokens[1], tokens[3]); 
       goals += Integer.parseInt(tokens[2]); 
       goals += Integer.parseInt(tokens[3]); 
      } else { 
       throw new IllegalArgumentException("Invalid match count : " 
         + aLine); 
      } 
     } 
    } catch (FileNotFoundException e) { 
     System.out.println("problem " + e.getMessage()); 
    } 
    System.out.printf("%nTotal goals = %d%n", goals); 
} 

Когда я бег выше здесь я получаю (запрос) выход

  Home team Home score   Away team Away score 
==================================================================== 
     Chicago Fire   2   FC Dallas   2 
      LA Galaxy   1   Toronto FC   3 
     Real Salt Lake   3   DC United   2 
    Colorado Rapids   0  Columbus Crew   0 
Sporting Kansas City   2 New York Red Bulls   1 

Total goals = 16 
+0

Отлично работает, приветствует! – djchrisj

+0

@djchrisj Прекрати работать? –

0

Вот простой новичок решение:

int total=0; 
while (filescan.hasNext()){ 
     aLine = filescan.nextLine(); 
     StrArray = aLine.split(separator); 

     if (StrArray.length == 4){ 
      System.out.println (StrArray[0] +"\t" + StrArray [2] + StrArray[1] + "\t" + StrArray[3]); 
      total += Integer.parseInt(StrArray[3]); // will return the integer value of the s 
      total+= Integer.parseInt(StrArray[4]); 
     } else { 
      throw new IllegalArgumentException("Invalid match count : "+ aLine); 
     }     

     } 

} 

Подсказка: - не называйте переменные с заглавной буквы, которые должны быть зарезервированы для классов (StrArray)

0

Попробуйте это:

public void showResults(){ 

    String separator = ":"; 
    File inputfile = new File ("result.txt"); 
    int totalgoal=0; 
    String[] StrArray; 
    String aLine = ""; 

    System.out.println ("Home team   "+"\tHome score" + "         " + "\t Away Team" + "\t Away Score \n============================================================================="); 

    try { 
     Scanner filescan = new Scanner(inputfile); 
     while (filescan.hasNext()){ 
      aLine = filescan.nextLine(); 
      StrArray = aLine.split(separator); 


      if (StrArray.length == 4){ 
       System.out.println (StrArray[0] +"\t" + StrArray [2] + StrArray[1] + "\t" + StrArray[3]); 
       totalgoal+=Integer.parseInt(StrArray[2]); 
       totalgoal+=Integer.parseInt(StrArray[3]); 
      } else { 
       throw new IllegalArgumentException("Invalid match count : "+ aLine); 
      } 

     } 

     filescan.close(); 
     System.out.println ("Total goals ="+String.valueOf(totalgoal)); 

    } 


    catch (FileNotFoundException e) 
    { 
     System.out.println("problem "+e.getMessage()); 

    } 


} 

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