通过用户输入指定精确的小数位数,Java
Specify exact number of decimal places by user input , Java
我正在编写一个计算器程序,其中用户在最后一个输入提示中写入小数点数(1、2、3 ...),例如 2 个数字之和的输出应该具有的小数点数。
import java.util.Scanner;
import java.util.Formatter;
public class Lab01 {
public void start(String[] args) {
double cislo1;
double cislo2;
int operacia;
String decimal;
String dec;
Scanner op = new Scanner(System.in);
System.out.println("Select operation (1-sum, 2-dev, 3- *, 4- / )");
operacia = op.nextInt();
if (operacia >= 1 && operacia <= 4) {
if(operacia == 1) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number one:");
cislo1=input.nextDouble();
System.out.println("Enter number two:");
cislo2=input.nextDouble();
System.out.println("Enter number of decimal points");
decimal=input.nextLine();
dec="%."+decimal+"f";
Formatter fmt = new Formatter();
fmt.format(dec, cislo2);
System.out.println( fmt);
}
} else {
System.out.println("wrong!");
}
}
}
我已尝试使用 Formatter 方法进行十进制输入,但错误显示为“Conversion = '.' “
System.out.println("Enter number of decimal points");
decimal = input.nextLine();
dec = "%." + decimal + "f";
Formatter fmt = new Formatter();
fmt.format(dec, cislo2);
System.out.println(fmt);
你的变量 decimal
应该是一个整数。所以你应该更改以下几行:
String decimal;
你应该改为:
int decimal;
并且:
decimal = input.nextLine();
你应该改为:
decimal = input.nextInt();
或者,如果您想将其保留为字符串,则可以在读取小数位数之前添加一个额外的 input.nextLine();
。发生这种情况是因为 nextLine() 消耗了您正在读取 cislo2
变量的行分隔符,而 nextInt()
只会读取一个 int.
我正在编写一个计算器程序,其中用户在最后一个输入提示中写入小数点数(1、2、3 ...),例如 2 个数字之和的输出应该具有的小数点数。
import java.util.Scanner;
import java.util.Formatter;
public class Lab01 {
public void start(String[] args) {
double cislo1;
double cislo2;
int operacia;
String decimal;
String dec;
Scanner op = new Scanner(System.in);
System.out.println("Select operation (1-sum, 2-dev, 3- *, 4- / )");
operacia = op.nextInt();
if (operacia >= 1 && operacia <= 4) {
if(operacia == 1) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number one:");
cislo1=input.nextDouble();
System.out.println("Enter number two:");
cislo2=input.nextDouble();
System.out.println("Enter number of decimal points");
decimal=input.nextLine();
dec="%."+decimal+"f";
Formatter fmt = new Formatter();
fmt.format(dec, cislo2);
System.out.println( fmt);
}
} else {
System.out.println("wrong!");
}
}
}
我已尝试使用 Formatter 方法进行十进制输入,但错误显示为“Conversion = '.' “
System.out.println("Enter number of decimal points");
decimal = input.nextLine();
dec = "%." + decimal + "f";
Formatter fmt = new Formatter();
fmt.format(dec, cislo2);
System.out.println(fmt);
你的变量 decimal
应该是一个整数。所以你应该更改以下几行:
String decimal;
你应该改为:
int decimal;
并且:
decimal = input.nextLine();
你应该改为:
decimal = input.nextInt();
或者,如果您想将其保留为字符串,则可以在读取小数位数之前添加一个额外的 input.nextLine();
。发生这种情况是因为 nextLine() 消耗了您正在读取 cislo2
变量的行分隔符,而 nextInt()
只会读取一个 int.