我对如何调用格式方法非常困惑,因此在其中打印了一个带有int
的字符串。
//call
boatPrice = inputBoatPrice("Please enter the price of the boat, must be > :", 0.0);
//method
public static double inputBoatPrice(String messagePassed, double limitPassed) {
Scanner keyboard = new Scanner(System.in);
int userInput;
do {
System.out.printf("%1s %1.2f\n", messagePassed, limitPassed);
userInput = keyboard.nextInt();
} while(userInput < limitPassed);
return userInput;
} //end method
如何解决此问题,以便打印出来的电话:
“请输入船的价格,必须> 0.0:”
目前打印出来
“请输入船的价格,必须>> 0.00”
答案 0 :(得分:1)
只需将你的printf改编为:
System.out.printf("%1s %1.1f\n", messagePassed, limitPassed);
答案 1 :(得分:1)
您的格式字符串包含%1.2f,这意味着打印最少一位数字和2位数字。将其更改为%1.1f意味着打印最少1位数字和1位数字。
您可以在Formatter下的Javadoc中找到它。第一个数字是宽度,第二个数字是精度。来自Javadoc:
宽度是要写入输出的最小字符数。对于行分隔符转换,宽度不适用;如果提供,将抛出异常。
对于一般参数类型,precision是要写入输出的最大字符数。
对于浮点转换'e','E'和'f',精度是小数点分隔符后面的位数
答案 2 :(得分:0)
编辑:: 我想你想要做的就是以1.1的特定格式打印,最后用冒号。然后你需要这个:
public static void main(String[] args) {
inputBoatPrice("Please enter the price of the boat, must be >",0.0);
}
public static double inputBoatPrice(String messagePassed, double limitPassed) {
Scanner keyboard = new Scanner(System.in);
int userInput;
do {
System.out.printf("%1s %1.1f :\n", messagePassed, limitPassed);
userInput = keyboard.nextInt();
} while(userInput < limitPassed);
return userInput;
}
答案 3 :(得分:0)
尝试使用此功能,我会调整您的printf
和正确的返回类型:
public static double inputBoatPrice(String messagePassed, double limitPassed)
{
Scanner keyboard = new Scanner(System.in);
double userInput;
do {
System.out.printf("%1s %1.1f\n", messagePassed, limitPassed);
userInput = keyboard.nextDouble();
} while(userInput < limitPassed);
return userInput;
}
答案 4 :(得分:0)
只需更改
System.out.printf("%1s %1.2f\n", messagePassed, limitPassed);
到
System.out.printf(messagePassed, limitPassed);
和你的字符串
"Please enter the price of the boat, must be > %1.1f :"
这有助于纠正字符串的问题。
你还需要调整你的userInput
变量,因为你想读取oubles(至少你要求双值,因此你应该只接受双值)。这意味着将userInput
以及keyboard.nextInt();
的类型更改为keyboard.nextDouble();
答案 5 :(得分:0)
我对您的代码进行了一些调整:
double boatPrice = inputBoatPrice("Please enter the price of the boat, must be > ", 0.0);
public static double inputBoatPrice(String messagePassed, double limitPassed) {
Scanner keyboard = new Scanner(System.in);
int userInput;
do {
System.out.print(messagePassed + limitPassed + ":");
userInput = keyboard.nextInt();
} while(userInput < limitPassed);
return userInput;
}
您需要更改System.out.print:
System.out.printf("%1s %1.2f\n", messagePassed, limitPassed);
为:
System.out.print(messagePassed + limitPassed + ":");
还要编辑调用方法inputBoatPrice时传递的字符串:
("...must be > :") to ("...must be > ")