问题
I have been asked to check the number of times a team's name is on the text that is on my computer. I wrote the code, the code works fine by counting the number of times the team name has appeared but it just keeps on asking the name of the team, like 50 times since the size of the array i declared is 50. Please help me out. Thanks.
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();
}
}
}
回答1:
Calling getName() once every loop will cause the program to ask for a team name every loop:
int count = 0;
for ( int index = 0 ; index < winners.length ; index ++ )
{
if ( getName(teamName).equals(winners[index]))
{
count++;
}
}
By moving getName() out of the loop, it will only be called once (and a team name will only be requested once):
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++;
}
}
回答2:
Don't call 'GetName' in the loop, call it once before the loop and store the result.
回答3:
In the method checkSeries1() remove the method call for getName(teamName) out of for loop and call getName() only once outside for loop, like this:
int count = 0;
String name = getName(teamName);
for ( int index = 0 ; index < winners.length ; index ++ )
{
if ( name.equals(winners[index]))
{
count++;
}
}
来源:https://stackoverflow.com/questions/22119883/again-and-again-prints-the-same-value