0

Hi guys I am pretty new to coding as I only started a month ago in school. Our project is to build a game. For my game, I have questions I read from a text file into an array. I changed the tabs and new lines with \t and \n to format it. It works perfect when I just copy paste the code into System.out.println. But when I try to do it with a text file, it is coming out exactly as I typed it in with the \t and \n Please any help is appreciated:)

Example Text file(Just a single line of it)

How is a play on words commonly described? \n\t\tA) Pan\t\t \t\t\tB) Pin\n\t\tC) Pen\t\t \t\t\tD) Pun

The Output if put into print statement

How is a play on words commonly described?
A)Pan B) Pin
C)Pen D) Pun

Output from listed code

How is a play on words commonly described? \n\t\tA) Pan\t\t \t\t\tB) Pin\n\t\tC) Pen\t\t \t\t\tD) Pun

**import java.util.Scanner;
import java.io.*;
public class ImportFile {
    public static void main(String[] args) throws Exception{
        Scanner easyfile = new Scanner(new File("src/EasyQuestions.txt"));
        System.out.println(easyfile.nextLine());
    }
}**
Damian Kidon
  • 1
  • 1
  • 1
  • You're essentially asking to un-escape a string: [Howto unescape a Java string literal in Java](http://stackoverflow.com/questions/3537706/howto-unescape-a-java-string-literal-in-java) – trutheality May 04 '12 at 03:07
  • 1
    Consider using `String#replace(...)` or something similar to translate `\\t` into `\t` and similarly with `\\n` and `\n`. – Hovercraft Full Of Eels May 04 '12 at 03:08

3 Answers3

1

\n and \t are escape sequences used in Java strings to indicate a newline character and a tab character, respectively.

However, when you read in text from a file with those character sequences, you are not reading escape sequences, you are literally reading two characters each, '\' and 'n' in the former case, and '\' and 't' in the latter.

I think that you want to undo what you did, and remove the "\n"s and "\t"s from your file, and put the actual newlines and tabs back..

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
0

\t and \n are escape sequences that are necessary because you can't have a new line in the middle of a line of Java code.

// This doesn't work in Java.
String s = "One line
            the next line";

But files that you read in can have these characters without any problem:

One line
        the next line

So when you read text from a file, Java doesn't try to escape the characters that it finds: it assumes that when the file said \t it meant \t and not Tab.

If you want to replace \t with a tab character and \n with a newline character, you'll have to do it yourself. The String.replace() method is a good place to start.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
0

As I mentioned in a comment already, Java reads text like "\t" from the text as "\t". Consider using String#replace(...) to swap "\t" back to "\t"

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373