Kylian Murphy Kylian Murphy - 11 days ago 6
Java Question

Printing characters for individual file lines in Java

I'm trying to print the 4th and 5th character from each line in a file.

This was a question on an online test. It was the one I couldn't figure out in time. I am just doing this for learning purposes.

Anyways, I'm trying to iterate through the lines and print those characters. Obviously I'm doing something wrong!

The file contains:

1001XXXXYYYYZZZZ
2002AAAABBBBCCCC
3003LLLLMMMMNNNN
4004SSSSTTTTUUUU


output should be:

1X
2A
3L
4S


Here is my code

import java.io.PrintWriter;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Quiz9 {
public static void main (String [] args) throws FileNotFoundException{
Scanner in = new Scanner("/Users/abc/input.txt");
PrintWriter out = new PrintWriter("/Users/abc/output.txt");
String a;
while (in.hasNextLine()) {
for(int i=0;i<4;i++) {
a = in.next();
char b = a.charAt(5);
char c = a.charAt(6);
out.println(b +""+ c +"hello");
}
}
in.close();
out.close();
}
}


I've had gotten it to produce some output, but it only says "\s" which isn't even on the list! I don't see where I am going wrong.

Answer

You need to use Scanner(File source) not the file name. You are getting \s because the 5th and 6th character of your file name is s and \.

try this...

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

public class Quiz9 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(new File("/Users/abc/input.txt"));
        PrintWriter out = new PrintWriter("/Users/abc/output.txt");
        String a;
        while (in.hasNextLine()) {
            a = in.nextLine();
            char b = a.charAt(3);
            char c = a.charAt(4);
            out.write(b + "" + c + "\n");
        }
        in.close();
        out.close();
    }
}
Comments