简体   繁体   中英

Turning a line from a java scanner(file) into an array

All I am writting a simple java method that reads a text file of place names and will then map them to some characteristics...

This is the first time in java that I have read from a file.

I have written the code below that works - it reads the first line.

But what I want to do is to turn this line into a character array so that I can compare each character to a unsorted file and then map the words.

But I am struggling with a very basic challenge. How do I map the sc.scanner to a character array

Or should I use BufferReader

       File file = new File ("c:/Users/Green/documents/places.txt");
                Scanner sc = new Scanner(file);

       //   while (sc.hasNextLine())

               System.out.println(sc.nextLine());

There is a method of String which is toCharArray() .

See the String documentation .

As documented the method Scanner. nextLine returns a String, you can transform it to a character array using String. tocharArray and after iterate over it like below:

String line = sc.nextLine();
char[] arr = line.toCharArray();
for (char ch: arr) {
  ...here your logic
}

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