简体   繁体   中英

Printing the last number only from a loop

If I have a while loop that goes through a file and prints the numbers, how would I make it to where it only prints the very last number.

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

This is the output I'm currently getting. How would I make get it to where it would just print out 19

And how would I get it to work to where the numbers start at 1 instead of 0?

Currently my loop looks like this:

if (math == last){
        System.out.println(Score++);
    }

math is another method which computes equations, and last is the answer inputed from a file, and the loop currently just checked if the math matches the inputed answer in order to "grade" the problems.

I can't use arrays, try/catch, or regex.

Just read through the file normally and store each line in a temporary variable. Once the reader finishes reading, print out the temporary variable.

public class ReaderExample {

    public static void main(String[] args) throws IOException {

        File file = new File("input.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));

        String line = "";
        String copy = "";
        while((line = br.readLine() )!= null){
                copy = line;
        }
        System.out.println(copy);
    }
}

Using a Scanner

The same principle applies with a Scanner :

public class ReaderExample {

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(new FileReader("input.txt"));

        String line = "";
        while(in.hasNext()){
            line = in.nextLine();
        }
        System.out.println(line);
    }
}

Without Invoking Scanner

public String getLast(Scanner scanner){
            String line = "";
            while(in.hasNext()){
                line = in.nextLine();
            }
            return line;
}

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