我是一个java初学者,我有一个问题要做:这个问题提示用户输入5次,股票名称,股票价格,持有的股票数量,我们应该计算所有股票价值的总和,我只使用两个提示,使用一个循环来写,但我的问题是,在第二次提示时,循环跳过股票第二个名称的字符串输入,而不是提示…下面是代码:
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
是什么让输入在第二个循环中跳过?
3条答案
按热度按时间at0kjp5o1#
同样根据我的评论,问题是您的代码在调用时没有处理行尾(eol)标记
nextInt()
或者nextDouble()
.解决方法是使用
input.nextLine()
在获得int和double后,为了吞下eol令牌:brccelvz2#
读取股价和股数后,应读出换行符:
请参见上面带有注解的行:
knpiaxh13#
问题是你最后一次打电话
在循环的第一次迭代中,第一次传递回车符作为下一个股票名称。您可以使用:
以及