简体   繁体   中英

Trouble reading from text file in Java

Text file:

3 2 3
4 5 5
5 6 6
4 3 4
4 3 4
4 4 5
5 5 6
3 3 3
4 4 5

First number (in each row): par

Second number (in each row): player 1's score

Third number (in each row): player 2's score

I need the program to read all the par's, first player's scores, and second players's scores. The program will have to read the first number of every column and add it up.

for (int roundNum = 1; roundNum < 10; roundNum++)
{
    int par;
    int firstPlayer;
    int secondPlayer;
    int totalPar;

    par = in.nextInt();
    firstPlayer = in.nextInt();
    secondPlayer = in.nextInt();

    totalPar = par * 9;

    System.out.println(totalPar);
    System.out.println(firstPlayer);
    System.out.println(secondPlayer);
}

I put in the scanners and stuff to read the text file. The for loop is used to read all 9 lines of the text file. At the end, I tried using totalPar to get the sum of all the par's, but it did not work well for me. I would also like to be able to put the totalPar outside of the for loop, but it did not work for me, because the bracket already closed up where the integer par was initalized.

在for循环之前声明totalPar,并在循环内每次使totalPar + = par?

Instead of...

totalPar = par * 9;

I think you want...

totalPar += par * 9;

or...

totalPar += par;

I'm not sure what the "* 9" is meant to do, but, regardless, you won't have any sort of sum without using += instead of =. By using =, you're setting the total to the par in every iteration, but with +=, you're setting the total to the par plus the previous total.

Before all this, though, you need to declare totalPar outside of the for-loop like this:

int totalPar = 0;

You definitely need to declare the variables:

int par;
int firstPlayer;
int secondPlayer;
int totalPar;

before the loop; otherwise you're going to keep getting just the last value each time you run the loop.

With your int par declared before the loop you can use:

totalPar += par;

inside of the loop to add each new par value. After the loop you'll have the total par.

Use

String[] array = yourstring.split(" ");

for each line. then

total = total + Integer.ParseInt(array[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM