【问题标题】:scanner skips double type numbers扫描仪跳过双重类型的数字
【发布时间】:2023-02-04 03:16:56
【问题描述】:

你好,我是 Java 新手,当我制作一个练习输入/输出方法的程序时,我遇到了这个错误:

当我输入一个 int 值时,程序运行良好,但是当我输入一个 double 值时,它会显示以下内容:

这是我的代码:

import java.util.Scanner;

public class InpOutp
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);  // creates a scanner

        System.out.print("Enter price of a six-pack beer: ");
        double packPrice = in.nextDouble();

        System.out.print("Give the ml of a can: ");
        double canMl = in.nextDouble();

        final double CANS_PER_PACK = 6;
        double packMl = canMl * CANS_PER_PACK;

        // find the price per ml of a pack
        double pricePerMl = packPrice / packMl;
        System.out.printf("Price per ml: %8.3f", pricePerMl);
        System.out.println();
    }
}

【问题讨论】:

  • 您是否尝试过使用逗号作为小数点?
  • 我刚刚做到了并且成功了:)

标签: java input double


【解决方案1】:

问题是分隔符。如果你想使用期间试试这个

Scanner in = new Scanner(System.in).useLocale(Locale.US);

编辑:

另外值得一提的是,你应该使用in.nextLine(); 在每个 nextInt()nextDouble() 之后,否则在输入文本时,您将遇到 nextLine 的编码问题。

尝试这个

    System.out.print("Enter price of a six-pack beer: ");
    double packPrice = in.nextDouble();
    System.out.println("this will be skipped" +  in.nextLine());

    System.out.print("Give the ml of a can: ");
    double canMl = in.nextDouble();
    in.nextLine();
    System.out.print("And now you can type: ");
    System.out.println(in.nextLine());

【讨论】:

    【解决方案2】:

    错误是我用 . (5.4) 我应该用 , (5,4) 键入它们。

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 2019-04-04
      • 2014-10-26
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      相关资源
      最近更新 更多