2014-03-01 33 views
-5

我被要求检查团队名称在我的计算机上的文本的次数。我编写了代码,通过计算团队名称出现的次数,代码可以正常工作,但它只是一直询问团队的名称,就像我声明的数组大小是50次一样。请帮助我。谢谢。Again and Again打印相同的值

import java.util.*; 
import java.io.*; 
public class worldSeries 
{ 
    public String getName(String teamName) 
    { 
     Scanner keyboard = new Scanner(System.in); 
     System.out.println(" Enter the Team Name : "); 
     teamName = keyboard.nextLine(); 
     return teamName; 
    } 

    public int checkSeries1() throws IOException 
    { 
     String teamName=""; 
     Scanner keyboard = new Scanner(System.in); 


     String[] winners = new String[50]; 
     int i = 0 ; 
     File file = new File ("WorldSeriesWinners.txt"); 
     Scanner inputFile = new Scanner(file); 
     while (inputFile.hasNext() && i < winners.length) 
     { 
      winners[i] = inputFile.nextLine(); 
      i++; 
     } 
     inputFile.close(); 

     int count = 0; 
     for (int index = 0 ; index < winners.length ; index ++) 
     { 
      if (getName(teamName).equals(winners[index])) 
      { 
       count++; 

      } 
     } 
     return count; 

    } 

    public static void main(String[]Args) 
    { 
     String teamName = ""; 
     worldSeries object1 = new worldSeries(); 

     try 
     { 
      System.out.println(" The Number of times " + object1.getName(teamName) + "won the Championship is : " +object1.checkSeries1()); 
     } 
     catch (IOException ioe) 

     { 
      System.out.println(" Exception!!! "); 

      ioe.printStackTrace(); 
     } 

    } 
} 
+0

'对的getName(teamName)'..你期望什么? – m0skit0

+0

@ user3295442我删除了“多线程”标记。 –

+1

***非常类似的问题,由一个*不同的用户问*在这张贴之后20分钟:http://stackoverflow.com/questions/22120122/invoking-to-type-the-team-name-twice -instead-的一次 – aliteralmind

回答

4

调用getName()一次循环将导致程序的每个循环要求一个队名:

 int count = 0; 
     for (int index = 0 ; index < winners.length ; index ++) 
     { 
      if (getName(teamName).equals(winners[index])) 
      { 
       count++; 

      } 
     } 

通过移动getName()圈外的,它只会被调用一次(和一队名称将只被请求一次):

int count = 0; 
    String nameOfTeam = getName(teamName); // This line runs getName() once 

    for (int index = 0 ; index < winners.length ; index ++) 
    { 
     if (nameOfTeam.equals(winners[index])) 
     { 
      count++; 

     } 
    } 
1

不要在循环中调用'GetName',在循环前调用它并存储结果。

1

在该方法checkSeries1()去除方法调用的getName(teamName)总分for循环和调用的getName()仅一次外部for循环中,这样的:

int count = 0; 
String name = getName(teamName); 
for (int index = 0 ; index < winners.length ; index ++) 
{ 
    if (name.equals(winners[index])) 
    { 
     count++; 
    } 
}