2015-09-20 74 views
-3

允许我提供更多有关我遇到问题的信息。说我有一些代码将输入读入一行

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

的第一个语句将

Enter a number 

然后用户输入一个号码,说12,最后的说法是

Enter a number 12 

注意这是怎么在一条线上。我试图做同样的事情,但有一个浮点数,我希望它只显示小数点后两位数字。我试过

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

但我得到一个错误,说钱还没有初始化。但是,如果我写

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

输出是不是我想要的,那么它的

Enter your money 0.00 

用户输入他们的钱,说1234.567。最终输出是

Enter your money 0.00 
1234.58 

所以,我怎么能显示1234.58使最终输出

Enter your money 1234.58 
+0

你知道什么是'\ N'指在一个字符串? –

+1

你想在这一行上做什么:'输入你的钱0.00 1234.567'?或'输入你的钱1234.567'?或'输入你的钱1234.56'(尽管用户输入1234.567)? – RealSkeptic

回答

1

用户将总是看到用户输入的内容。你不能隐藏它。

当第一个提示,用户看到(_为光标):

Enter your money _ 

当用户然后类型的数,并且按下回车,显示的是:

Enter your money 3.14159 
_ 

正如你可以看到,光标已经在下一行。此时您无法更改第一行。您可以打印另一行,但第一行将始终存在,例如

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

将给予以下结果:

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

编辑

你想要一个解释,所以我会给它给你:D由于java API的状态System.out.print方法将打印字符串到控制台而不输入新行。所以你会得到“输入你的钱”字符串在屏幕上没有换行。在用户输入keyboard.nextFloat()后,字符串的其余部分将被放在与System.out.printf("%.2f", money)的字符串中。