我最近正在查看一个计算器,由于我的计算器,该网站上的用户向我建议,坦率地说,吸吮。这是计算器的代码:
import java.util.Scanner;
class RealCalc {
// Declare the constants
private static final String YES = "YES";
private static final String MULTIPLY = "Multiply";
private static final String DIVIDE = "Divide";
private static final String SUBTRACT = "Subtract";
private static final String ADD = "Add";
public static void main(String args[]) {
// Using one only Scanner
Scanner sc = new Scanner(System.in);
double fnum, snum;
System.out.println("Hello, my name is Cortana,"
+ " would you like to perform operations with me?");
// Use equalsIgnoreCase to make it case-insensitive
if(sc.nextLine().equalsIgnoreCase(YES)) {
System.out.println("Good choice!\n");
System.out.print("Enter your first number: ");
fnum = sc.nextDouble();
System.out.print("Enter your second number: ");
snum = sc.nextDouble();
// This is used to clear the '\n' character following the previous
// integer input
sc.nextLine();
// Call the function to perform arithmetic operations
performOperation(sc, fnum, snum);
}
System.out.println("Thank you!");
}
public static void performOperation(Scanner sc, double fnum, double snum) {
System.out.println("\n" + MULTIPLY + ", " + DIVIDE + ", " + SUBTRACT + ", or " + ADD);
System.out.println("What do you want me to do with these numbers?");
String operation = sc.nextLine();
System.out.println();
if(operation.equalsIgnoreCase(MULTIPLY)) {
System.out.printf("%8.3f * %8.3f = %8.3f%n%n", fnum, snum, fnum * snum);
}
else if(operation.equalsIgnoreCase(DIVIDE)) {
System.out.printf("%8.3f / %8.3f = %8.3f%n%n", fnum, snum, fnum / snum);
}
else if(operation.equalsIgnoreCase(SUBTRACT)) {
System.out.printf("%8.3f - %8.3f = %8.3f%n%n", fnum, snum, fnum - snum);
}
else if(operation.equalsIgnoreCase(ADD)) {
System.out.printf("%8.3f + %8.3f = %8.3f%n%n", fnum, snum, fnum + snum);
}
else {
System.out.println("Sorry, I do not recognize this operation.\n");
// Call this function again to re-prompt the user for a valid operation
performOperation(sc, fnum, snum);
}
}
}
我遇到的问题是输出。每当用户输入两个数字时,它将它们保存为两个不同的变量,fNum和sNum。所以我在想,为什么你不能放
System.out.println("Your answer is: " + (fNum * sNUM));
//Assuming it is multiplication
那么所有这些%的迹象和8.3f在哪里进来?任何帮助将不胜感激,谢谢
答案 0 :(得分:0)
%
是格式化打印(printf()
)中使用的符号,作为将替换为值的占位符。常见示例包括浮点数%f
,十进制整数%d
和字符串%s
。例如:
String greet = "Hello"
System.out.printf("%s world!", greet); //prints "Hello world!"
%8.3f
表示浮点值的占位符,最小宽度为8,小数点后3位。如果该值包含少于8个字符,则默认情况下将在开头添加空格以填补空白。
虽然你可以使用你在答案中提到的连接,printf()
更强大,更简洁,所以它更适合复杂的字符串格式化。
有关详细信息,请参阅this参考页。
答案 1 :(得分:0)
简短的回答是肯定的,你可以简单地使用
System.out.println("Your answer is: " + (fNum * sNUM));
然而,这将显示您答案的所有小数位。 %8.3f字符串告诉字符串格式化程序将浮点数编号为宽度为8个字符,小数点后面有3个字符,请查看java文档here