Java System.out.print-method不´;我不能正常工作
我在一本名为《Java,如何编程》的书中做练习。我创建了一个包含两个类的小程序。硬件商店应该使用该程序来表示所售物品的发票。它应该包括4条信息:商品编号的字符串值、描述产品的字符串值、销售商品数量的int值和商品价格的双倍值。我在一个包含main方法的类中创建了该类的两个对象。我应该为每个实例变量使用“set和get方法” 问题在于,当程序提示用户写入变量值时,它不会读取变量“第二个项目编号”的第一个值(下命令窗口副本中的第5行)。我真的无法读懂代码中为什么会发生这种情况。有人能帮我吗 这两个类别的代码如下:Java System.out.print-method不´;我不能正常工作,java,Java,我在一本名为《Java,如何编程》的书中做练习。我创建了一个包含两个类的小程序。硬件商店应该使用该程序来表示所售物品的发票。它应该包括4条信息:商品编号的字符串值、描述产品的字符串值、销售商品数量的int值和商品价格的双倍值。我在一个包含main方法的类中创建了该类的两个对象。我应该为每个实例变量使用“set和get方法” 问题在于,当程序提示用户写入变量值时,它不会读取变量“第二个项目编号”的第一个值(下命令窗口副本中的第5行)。我真的无法读懂代码中为什么会发生这种情况。有人能帮我吗 这两个类
public class aInvoice
{
private String number;
private String description;
private int quantity;
private double price;
public aInvoice(String pNumber, String pDescription, int pQuantity, double pPrice)
{
number = pNumber;
description = pDescription;
if (pQuantity < 0)
{quantity = 0;}
else
{quantity = pQuantity;}
if (pPrice < 0)
{price = 0;}
else
{price = pPrice;}
}
public String getNumber()
{
return number;
}
public String getDescription()
{
return description;
}
public int getQuantity()
{
return quantity;
}
public double getPrice()
{
return price;
}
double totalAmount;
public double getaInvoiceTotalAmount()
{
return quantity * price;
}
}
命令窗口中的读数为:
输入第一个项目编号:44
输入说明:pc
输入数量:1
输入价格:$10
输入第二个项目编号:输入说明:电话
输入数量:1
输入价格:$100
第1部分的项目编号:44
商品说明:pc
数量:1
价格每件$10.00
第2部分的项目编号:
商品说明:电话
数量:1
每件售价:$100.00
总额:$110.00这是因为在使用input.nextInt()或input.nextDouble()读取输入后,您需要在尝试读取其他字符串之前清除缓冲区 当用户输入5.0时,5.0将从输入缓冲区中提取,但回车符保留。您可以输入一个input.nextLine(),这将为您清除回车符 所以你的代码应该是
System.out.print( "Enter price: $");
partPrice1 = input.nextDouble();
input.nextLine();
System.out.print( "Enter second items number: ");
partNumber2 = input.nextLine();
System.out.print( "Enter description: ");
partDescription2 = input.nextLine();
System.out.print( "Enter quantity: ");
partQuantity2 = input.nextInt();
System.out.print( "Enter price: $");
partPrice2 = input.nextDouble();
基本上,问题是当您调用nextInt/nextDouble时,这些函数只获取输入流中实际存在的数字部分。他们不会读取按“回车”键输入的回车字符。只需输入一个
input.nextLine()每次input.nextInt()
等之后都要执行code>
这似乎是您看到的问题:很高兴这对您有用。请确保在您的问题上标记为“答案”,以便人们因回答而获得积分:)。我看你没有在你的问题上标出任何答案。非常感谢。
System.out.print( "Enter price: $");
partPrice1 = input.nextDouble();
input.nextLine();
System.out.print( "Enter second items number: ");
partNumber2 = input.nextLine();
System.out.print( "Enter description: ");
partDescription2 = input.nextLine();
System.out.print( "Enter quantity: ");
partQuantity2 = input.nextInt();
System.out.print( "Enter price: $");
partPrice2 = input.nextDouble();