2016-08-29 65 views
1
... 
    else if(choice == 3) { 

     ArrayList<Integer> shares = new ArrayList<Integer>(); 
     System.out.print("Type in quantity: "); 
     int quantity = Integer.parseInt(reader.nextLine()); 
     System.out.println("Enter total quantity either as a single number or many numbers by pressing enter after each: "); 
     while (reader.hasNextInt()) { 
      int share = reader.nextInt(); 
      shares.add(share); 
     } 
     System.out.println("Enter total price: "); 
     Scanner reader1 = new Scanner(System.in); 
     double price = Double.parseDouble(reader1.nextLine()); 
     int sum = 0; 
     System.out.println((price*quantity)/sum); 
     for(Integer d : shares){ 
      sum += d; 
     return; 
    } 

在这里,我试图计算的单个值进行3值(price*quantity)/sum的这是主要的公式,但总和值是通过首先进入一系列的整数然后将其相加,并用于在主计算式。 的问题:计算体积加权价格

  1. 我不能让While循环时,用户输入Null值停下来,我只设法使它停止当用户输入一个字母而不是数字

  2. 目前我运行这个程序我得到一个结果Infinity为什么?

回答

1
  1. 因为你正在检查reader.hasNextInt(),表示将返回唯一的非整数输入错误。

如果你想利用输入到文件结束,你可以这样说:

String input = null; 
while(!(input = sc.nextLine()).isEmpty()) { 
    int share = Integer.parseInt(input); 
    shares.add(share); 
} 
  • 你得到Infinity,因为你是和谁分值为零。
  • 我想你可能会试图做到这一点:通过打印出来

    int sum = 0;   
    for(Integer d : shares){ 
        sum += d; 
    } 
    System.out.println((price*quantity)/sum); 
    
    +0

    我想通了,总和为0,但我不知道它为什么是0和我做循环检查如果输入的值是一个整数,因为我无法使其以任何其他方式工作......来吧你的答案根本没有帮助 – likyy2

    +0

    你正在得到因为你已经完成了这个'int sum = 0;' – Shahid

    +0

    如何解决它? – likyy2