2017-10-10 66 views
1

我有一個字符串輸入,其中,輸入有一個團隊名稱和分數由一個空格分隔。例如bb 3teamd 5贏家應該是teamd打印具體的字符

爲了得到冠軍隊拿下最高分,我做以下操作:

Scanner scanner = new Scanner(System.in); 
    int cases = scanner.nextInt(); 

    printWinnerTeam(cases); 



} 

public static void printWinnerTeam(int cases) { 
    Scanner scanner = new Scanner(System.in); 
    String str = ""; 
    String winnerTeam = ""; 
    int winnerScore = 0, countedChar = 0; 

    for (int i = 0; i < cases; i++) { 
     str += scanner.nextLine(); 
    } 
    char[] arr = str.toCharArray(); 
    for (int i = 0; i < arr.length; i++) { 
     countedChar++; 
     if (arr[i] == ' ') { 
      if (str.charAt(i + 1) > winnerScore) { 
       winnerTeam = ""; 
       winnerScore = (int) str.charAt((int) i + 1); 
       for (int j = 0; j < countedChar; j++) { 
        winnerTeam += str.charAt(j); 
       } 
       countedChar = 0; 
      } else { 
       //winnerTeam = ""; 
       countedChar = 0; 
      } 
     } 
    } 
    System.out.println(winnerTeam); 
} 

但它不工作知府,這是印刷佈線結果,如何按預期做到這一點?

+0

如何簡化它,但你只是去處理。如果輸入的分數最大,則存儲數字和團隊名稱 - 使用String.split(「,」); –

+1

我還沒有嘗試過你的代碼,但我會想象一個大問題是'str + = scanner.nextLine();'的連接問題''新行將被直接附加到前一行'number'的末尾 –

+0

@ScaryWombat確實是的,我想去外面的箱子,我的問題與'+ =',謝謝,隨時讓它接受回答 – user1058652

回答

1

我沒試過你的代碼,但我想一個很大的問題是str += scanner.nextLine();串聯新的生產線將被直接追加到以前的行數

到底還要看看這個

Scanner sc = new Scanner(System.in); 
    int bestScore = Integer.MIN_VALUE; 
    String team = "Nothing entered"; 
    System.out.println("how many teams"); 
    int count = sc.nextInt(); 
    sc.nextLine(); 
    while (count-- > 0) { 
     System.out.println("Entered team,score"); 

     String line = sc.nextLine(); 
     String arr [] = line.split(" "); 
     // check size - TBD 
     if (Integer.parseInt(arr[1]) > bestScore) { 
      bestScore = Integer.parseInt(arr[1]); 
      team = arr[0]; 
     } 
    } 

    System.out.println("nest team is " + team + " with a score of " + bestScore); 
+1

@AndyTurner謝謝,我需要清理我的屏幕 –

+0

對不起,你知道嗎?錯誤[這裏](https://ideone.com/tB1Akw),用我的代碼獲取runTimeError? – user1058652

+0

@android在Eclipse爲我工作得很好'多少案件多少球隊進入球隊,比分 test1的2 進入球隊,得分 我23支 我 多少球隊進入球隊,得分 test2 4 輸入球隊得分 me_again 23 me_again me me_again ' –

0

如果我不得不做這樣的事情,我會做這樣的:

import java.util.*; 
     public class winner { 
      public static void main (String args []) { 
      Scanner scanner = new Scanner(System.in); 
      int cases = scanner.nextInt(); 

      printWinnerTeam(cases); 
     } 

    public static void printWinnerTeam(int cases) { 
      Scanner scanner = new Scanner(System.in); 
      String winnerTeam = ""; 
      String Team=""; 
      int winnerScore = 0, score = 0; 

      for (int i = 0; i < cases; i++) { 
       Team = scanner.next(); 
       score = scanner.nextInt(); 
       if(score > winnerScore){ 
       winnerTeam = Team; 
       winnerScore = score; 
       } 

      } 
      System.out.println("Winner team" + winnerTeam + "Score:" + winnerScore); 
     } 
     }