在使用BufferedReader方法使用Java获取用户输入时消除新行
在第一次分配中,我必须让用户输入一些数字(例如:312),然后添加每个数字,并输出类似于:“数字是3 1 2,总和是6。”以下是代码:在使用BufferedReader方法使用Java获取用户输入时消除新行,java,Java,在第一次分配中,我必须让用户输入一些数字(例如:312),然后添加每个数字,并输出类似于:“数字是3 1 2,总和是6。”以下是代码: public static void main(String[] args) { int Max_Size = 30; char[] myArray = new char [Max_Size]; String temp = " "; char parse; int sum = 0; int counter = 0;
public static void main(String[] args) {
int Max_Size = 30;
char[] myArray = new char [Max_Size];
String temp = " ";
char parse;
int sum = 0;
int counter = 0;
System.out.print("Please enter a non-negative integer: ");
try{
BufferedReader dataIn = new BufferedReader(
new InputStreamReader(System.in));
temp = dataIn.readLine();
} catch (IOException e) {
System.out.println("Error!");
}
System.out.print("The numbers are ");
//put each character of the string into a char array
for (int i = 0; i < temp.length(); i++){
myArray[i] = temp.charAt(i);
System.out.print(myArray[i] + " ");
}
//take sum of each character as an integer
while (counter != temp.length()){
sum = sum + (myArray[counter] - '0');
counter++;
}
System.out.println("with the sum of " + sum);
}
我怎样才能不为输入设置新行:312?意思是我想要它,就像“请输入一个非负整数:312”,312在同一行。还有,有没有更好的方法将输入解析为整数并将其放入整数数组?我不知道您为什么会看到这种情况-我刚刚尝试过并获得了以下输出:
Please enter a non-negative integer: 312
The numbers are 3 1 2 with the sum of 6
你在哪个站台上跑步
如果您只需要使用charAt()
,我会说您使用char数组是毫无意义的,如果您真的想将输入转换为char数组,我会使用String.tocharray()来代替
另外,如果您使用的是Java 1.6,我建议您:
String temp = System.console().readLine();
作为从用户处读取一行文本的一种更简单的方法。我怀疑这可能是由于NetBeans控制台,或者可能是因为您似乎通过Ant/Maven(可能是NetBeans的东西)执行此操作
(我假设Ant/Maven是因为最后的
“构建成功(总时间:7秒)”
。我已经做Java十多年了,但我觉得这很有趣,因为我还不知道答案!问得好。我在Ubuntu上使用Netbeans。谢谢关于console()的一个提示:允许它返回null,并且在我从Eclipse中运行代码时经常返回null,这很烦人。我只是在Mac OS X上运行了它,和Jon一样,它按照您的意愿工作。@kd304:好的观点:)@Kap Choi:我强烈怀疑Netbeans应该对此负责。尝试从命令行运行它。
String temp = System.console().readLine();