I have to use Scanner
, so is there a nextChar()
instead of nextLine()
method that I could use?
我必须使用Scanner,那么我可以使用nextChar()而不是nextLine()方法吗?
Thanks!
4 个解决方案
#1
2
You can convert in an array of chars.
您可以转换为一组字符。
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("yourFile.txt")));
while (s.hasNext())
{
String str = s.next();
char[] myChar = str.toCharArray();
// do something
}
} finally {
if (s != null) {
s.close();
}
}
}
#2
6
If you have to use a Scanner
(as you noted in your edit), try this:
如果您必须使用扫描仪(如编辑中所述),请尝试以下操作:
myScanner.useDelimiter("(?<=.)");
Now myScanner
should read character by character.
现在myScanner应逐字逐句阅读。
You might want to use a BufferedReader
instead (if you can) - it has a read
method that reads a single character. For instance, this will read and print the first character of your file:
您可能希望使用BufferedReader(如果可以) - 它有一个读取单个字符的read方法。例如,这将读取并打印文件的第一个字符:
BufferedReader br = new BufferedReader(new FileReader("somefile.txt"));
System.out.println((char)br.read());
br.close();
#3
2
Split the line into characters using String.toCharArray()
.
使用String.toCharArray()将行拆分为字符。
#4
0
If you're committed to using Scanner
then you can use next(String pattern)
.
如果您致力于使用Scanner,那么您可以使用next(String pattern)。
String character = scanner.next(".");
The above returns a String
of length 1 -- that is, you get a character, but as a string.
上面返回一个长度为1的String - 也就是说,你得到一个字符,但是作为一个字符串。
#1
2
You can convert in an array of chars.
您可以转换为一组字符。
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("yourFile.txt")));
while (s.hasNext())
{
String str = s.next();
char[] myChar = str.toCharArray();
// do something
}
} finally {
if (s != null) {
s.close();
}
}
}
#2
6
If you have to use a Scanner
(as you noted in your edit), try this:
如果您必须使用扫描仪(如编辑中所述),请尝试以下操作:
myScanner.useDelimiter("(?<=.)");
Now myScanner
should read character by character.
现在myScanner应逐字逐句阅读。
You might want to use a BufferedReader
instead (if you can) - it has a read
method that reads a single character. For instance, this will read and print the first character of your file:
您可能希望使用BufferedReader(如果可以) - 它有一个读取单个字符的read方法。例如,这将读取并打印文件的第一个字符:
BufferedReader br = new BufferedReader(new FileReader("somefile.txt"));
System.out.println((char)br.read());
br.close();
#3
2
Split the line into characters using String.toCharArray()
.
使用String.toCharArray()将行拆分为字符。
#4
0
If you're committed to using Scanner
then you can use next(String pattern)
.
如果您致力于使用Scanner,那么您可以使用next(String pattern)。
String character = scanner.next(".");
The above returns a String
of length 1 -- that is, you get a character, but as a string.
上面返回一个长度为1的String - 也就是说,你得到一个字符,但是作为一个字符串。