我是Java的初学者,我有一个问题要做: 问题提示用户5次输入,股票的名称,然后股票价格,然后股票的数量,我们应该计算所有股票价值的总和,我只用两个提示使用循环写,但我的问题是,在第二个提示时间循环跳过字符串输入为第二个股票名称而不是promting ...贝娄是代码:
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sharePrice =0,stockPrice = 0, temp = 0 ;
int i = 0;
double sum=0;
String name;
while (i < 2) {
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
stockPrice = sharePrice * (double)(numberOfshares);
sum += stockPrice;
i++;
}
System.out.println("the total stockprice owned is: " + sum );
}
}
这是我得到的输出:
Enter the Name of the Stock
nestle
Enter the Share price
2
Enter the number of owned shares
4
Enter the Name of the Stock
Enter the Share price
在第二次循环中输入跳过的原因是什么?
答案 0 :(得分:3)
根据我的评论,问题是您的代码在调用nextInt()
或nextDouble()
时不会处理行尾(EOL)令牌。
解决方案是在获取int和double之后使用input.nextLine()
以吞下EOL令牌:
sharePrice = input.nextDouble();
input.nextLine(); // add this
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
input.nextLine(); // add this
stockPrice = sharePrice * (double)(numberOfshares);
答案 1 :(得分:3)
问题是你上次打电话
int numberOfshares = input.nextInt();
在循环的第一次迭代中,您的第一次传递回车符作为下一个股票名称。你可以改用:
double sharePrice = Double.parseDouble(input.nextLine());
和
int numberOfshares = Integer.parseInt(input.nextLine());
答案 2 :(得分:0)
您应该在阅读股票价格和股票数量后读出换行符:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double sharePrice = 0, stockPrice = 0;
int i = 0;
double sum = 0;
String name;
while (i < 2)
{
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
// Read out the newline character after the share price.
input.nextLine();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
// Read out the newline character after the number of shares.
input.nextLine();
stockPrice = sharePrice * (double) (numberOfshares);
sum += stockPrice;
System.out.println(String.format("Name: %s, Price: %f, Shares: %d, Total: %f",
name,
sharePrice,
numberOfshares,
stockPrice));
i++;
}
System.out.println("the total stockprice owned is: " + sum);
}
请参阅上面带注释的行: