通过用户输入指定精确的小数位数,Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49255290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:18:47  来源:igfitidea点击:

Specify exact number of decimal places by user input , Java

javainputdecimalformatter

提问by Adam Beňko

I am writing a calculator program, where the user in the last input prompt writes the number of decimal points (1, 2 ,3...), that the output of for example sum of 2 numbers should have.

我正在编写一个计算器程序,用户在最后一个输入提示中写下小数点的数量(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!");
         }
     }
 }

I have tried Formatter method for the decimal input but the error says" Conversion = '.' "

我已经尝试了十进制输入的 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);

采纳答案by Bernardo Rocha

Your variable decimalshould be an int. So you should change the follow lines:

你的变量decimal应该是一个整数。所以你应该改变以下几行:

String decimal;

You should change to:

你应该改为:

int decimal;

And:

和:

decimal = input.nextLine();

You should change to:

你应该改为:

decimal = input.nextInt();

Or, if you want to keep it as a String, you can add an extra input.nextLine();before reading the number of decimals. It occurs because nextLine() consumes the line separator where you are reading your cislo2variable and nextInt()will only read an int.

或者,如果您想将其保留为字符串,则可以input.nextLine();在读取小数位数之前添加额外内容。发生这种情况是因为 nextLine() 消耗了您正在读取cislo2变量的行分隔符,并且nextInt()只会读取一个 int。