简体   繁体   中英

Printing coordinates from a .txt file in Java

My question is very simple. I'm learning via Oracle iLearning about simple and plain Java but they don't have solved questions and I'm messing around with my brain trying to solve this. I have a.txt file that looks like this:

128 3.141 Puppies!
Line2 This is Line2. 100002 This is still Line2.
Line3
Line4 444 BlueBumper 90 120*

And what I need is to find the two tokens (ie 90 and 120) following "BlueBumper".

My code looks similar to:


import java.util.Scanner;

public class Input04 {
    public static void main(String[] args){
        Scanner sc = new Scanner(Input04.class.getResourceAsStream("input04text.txt"));     
        //Edit these lines to advance the scanner
        sc.nextLine();
        System.out.println(sc.nextLine());
        //Does this line contain "BlueBumper"?
        System.out.println(sc.findInLine("BlueBumper"));
        //Store the next two numbers as xPosition and yPosition
        //Print these positions
        int x = sc.nextInt();
        int y = sc.nextInt();
        System.out.println("X: "+ x +", Y: " + y);
        sc.close();
    }    
}

I'm trying to store one variable x and one variable y with each token. I don't really know why the exercise offered the first couple of System.out.println's in order to find the instance "BlueBumper", since I don't need to print anything until the last line, but it feels like I don't quite understand how to make it work in this context.

I see only thing you are doing wrong is not going to line 4. you have to add a extra sc.nextLine();. the below is working fine for me.

public class Input04 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(Input04.class.getResourceAsStream("input04text.txt"));     
        //Edit these lines to advance the scanner
        // below will print, if you print : 128 3.141 Puppies!
        sc.nextLine(); 
        // will print : Line2 This is Line2. 100002 This is still Line2.
        System.out.println(sc.nextLine());
        // will print, if you print : Line3
        sc.nextLine(); 
        //Does this line contain "BlueBumper"?
        System.out.println(sc.findInLine("BlueBumper"));
        //Store the next two numbers as xPosition and yPosition
        //Print these positions
        int x = sc.nextInt();
        int y = sc.nextInt();
        System.out.println("X: "+ x +", Y: " + y);
        sc.close();
    }    
}

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