Bart g
Bart g

Reputation: 585

Trying to get some words out of every line

I have been trying to get 2,3,4 words of a file and this is the code so far. But I am getting some error messages. Can anybody help me please? This is the code:

import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;

class PrintLines{
public static void main(String[] args) throws FileNotFoundException {

    Scanner me = new Scanner(System.in);

    System.out.print("File Name: ");
    String s = me.next();
    File inFile = new File(s);
    Scanner in = new Scanner(inFile);

    while(in.hasNextLine()){
        String[] split=in.split(" ");
        System.out.println(split[2]+split[3]+split[4]);

    }
    in.close();
}
}

But this is the error messages I am getting:

PrintLines.java:18: cannot find symbol
symbol  : method split(java.lang.String)
location: class java.util.Scanner
        String[] split=in.split(" ");
                         ^
1 error

Upvotes: 0

Views: 150

Answers (2)

IBBoard
IBBoard

Reputation: 969

If you read the docs then Scanner doesn't have a "split" method, so what you're getting is a compiler error telling you that you're calling a non-existent method.

Try swapping

String[] split=in.split(" ");

for:

String[] split=in.nextLine().split(" ");

The connection between the two methods is hinted at if you read the JavaDoc for hasNextLine(), where the nextLine() method is the next one documented.

Upvotes: 2

You are calling split on the Scanner itself; you should be calling it on the nextLine which returns the next line as a String:

String[] split = in.nextLine().split(" ");

Upvotes: 2

Related Questions