简体   繁体   English

读取输入到一行

[英]Reading input to one line

Allow me provide more information with what I'm having trouble with.请允许我提供更多有关我遇到问题的信息。 Say I have some code说我有一些代码

int a;
System.out.print(Enter a number ");
a = keyboard.nextInt

The first statement will be第一个声明将是

Enter a number

the user then enters a number, say 12, the final statement is用户然后输入一个数字,比如 12,最后的语句是

Enter a number 12

Notice how this is all on one line.注意这一切是如何在一行上完成的。 Im trying to do the same thing, but with a float and I want it to only show 2 digits after the decimal.我试图做同样的事情,但有一个浮点数,我希望它只显示小数点后的 2 位数字。 I tried我试过

float money;
System.out.printf("Enter your money " + "%.2f\n", money);
money = keyboard.nextFloat();

but I get an error saying money hasn't been initialized.但我收到一条错误消息,指出资金尚未初始化。 However, if I write但是,如果我写

float money = 0.0f;
System.out.printf("%.2f\n", money + "Enter your money ");
money = keyboard.nextFloat();

The output isn't what I want, its输出不是我想要的,它的

Enter your money 0.00

The user then enters their money, say 1234.567.然后用户输入他们的钱,比如 1234.567。 The final output is最终输出是

Enter your money 0.00
1234.58

So, how can I display 1234.58 so that the final output is那么,我怎样才能显示 1234.58 以便最终输出是

Enter your money 1234.58

The user will always see what the user types.用户将始终看到用户键入的内容。 You can't hide that.你无法隐藏这一点。

When you first prompt, the user sees ( _ for cursor):当您第一次提示时,用户会看到( _表示光标):

Enter your money _

When a user then types a number, and presses enter, the display is:当用户输入一个数字并按回车键时,显示为:

Enter your money 3.14159
_

As you can see, the cursor is already at the next line.如您所见,光标已经在下一行。 You can't change the first line at this point.此时您无法更改第一行。 You can print another line, but the first one will always be there, eg您可以打印另一行,但第一行将始终存在,例如

System.out.printf("You entered %.2f%n", money);

will give the following result:将给出以下结果:

Enter your money 3.14159
You entered 3.14
_
System.out.print("Enter your money ");
float money = keyboard.nextFloat();
System.out.printf("%.2f", money);

EDIT编辑

You want an explanation so I will give it to you :D As java API states System.out.print method will print string to the console without entering new line.你想要一个解释,所以我会给你一个解释:D 因为 java API 声明System.out.print方法将在不输入新行的情况下将字符串打印到控制台。 So you will get "Enter your money" string on the screen without newline .所以你会在没有换行符的情况下在屏幕上看到“输入你的钱”字符串。 After user input keyboard.nextFloat() the rest of the string will be put on the string with System.out.printf("%.2f", money) .在用户输入keyboard.nextFloat()之后,字符串的其余部分将使用System.out.printf("%.2f", money)放在字符串上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM