如何解决Java中的字符和字符串输入
我是Java的新手,为不同数据类型的基本I / O操作编写了一个程序。我希望程序输入1 a abcd
并分别在三行中输出它们。但是,当我输入1 a
时,程序终止并输出1
,a
和三个不同行中的空行。我无法正确输入字符,这是问题的根源。
有人可以指导我哪里做错了吗?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
char c = ' ';
try {
c = (char)br.read();
}
catch (IOException e) {
e.printStackTrace();
}
return c;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
char c = in.nextChar();
String s = in.nextLine();
out.println(n);
out.println(c);
out.println(s);
out.close();
}
}
解决方法
按如下所示重构代码。
char c = in.nextChar();//Keep this line as same
in.nextLine();//(only add this line after the above line)Place this line otherwise your String abcd can't insert
输出:
1
a
abcd
,
您的意思是按照以下说明操作:
input: 1 a abcd
out:
1
a
abcd
您引用此代码:
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferedReader.readLine();
if (inputLine!=null && inputLine.length()>0) {
String[] splitInputLine = inputLine.split("\\ ");
for (String outLine : splitInputLine) {
System.out.println(outLine);
}
}
bufferedReader.close();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。