循环不会重复只进行一次而不是重复进行

时间:2015-11-10 19:38:46

标签: java

我最近被分配了一个功课,用不同的语言编写代码,这是我在python中使用的唯一语言。我的代码应该做的是询问用户输入,然后首先将其设置为高,低并开始计算平均值。但是,我现在遇到了两个问题。一,我的第24行说字符串不能转换为整数。但是,我虽然已经告诉程序允许它。如果有人可以帮助我,我将不胜感激。

package hgp.pkg13.pkg16;

import java.util.Scanner;
public class HGP1316 {
//Declaration of variables
static int Running_total = 0;
static double Average = 0.0;
static int User_input = 0;
static double counter = 0.0 ;
static int Highest_input = -1;
static int Lowest_input = -1; 
public static void main(String[] args) {
    //Intro Program (Optional)
    {
  System.out.println("This program will give you the highest, lowest, and average of the integers you \n"
          + "enter. To end enter a negative number ");       
}
//2. Ask user to enter a positive integer (or a negative integer to stop)
//3. Record the user's input
//4. Test the input >= 0
while (User_input >=0){
Scanner user_input = new Scanner( System.in );
Integer User_input;
System.out.print("Please enter an integer: ");
 User_input = user_input.nextInt();
//4a. If it is true that input >= 0
if (User_input >= 0)
{

    //4a1Add the input to "running total"
Running_total = Running_total + User_input;
    //4a2. Increment "number of inputs counter"
counter = counter + 1;  
//4a3. Test if "number of inputs counter" is equal to 1
if (counter == 1)
{
     //4a31. If true, replace both "highest input" and "lowest input" with the input
Highest_input = User_input;
Lowest_input = User_input; }

//4a5. If the input > "highest input" then replace "highest input" with input
if (User_input > Highest_input)
{
    Highest_input = User_input;
}
//4a6. If the input < "lowest input" then replace "lowest input" with input
if (User_input < Lowest_input)
{
    Lowest_input = User_input;
}
//4b. If false
    //4b1. Goto step 5
 else;
{
 //5. Calculate average (formula: "running total" /"number of inputs counter" )
    Average = (Running_total / counter);
 //6. Display/communicate "highest input", "lowest input" and average
   System.out.println ("The Highest value entered was : "+ Highest_input);
   System.out.println ("The Lowest value entered was : " + Lowest_input);
   System.out.println("The Average of enteries was : "+ Average);
//7. Terminate
}


 }
}
}
}    

我现在遇到的问题是它遍历整个循环而不是重新分配用户输入。这可能与我的{}有关,但我不确定

1 个答案:

答案 0 :(得分:-1)

您将用户输入作为User_input = user_input.next();,而在java中则需要使用User_input = user_input.nextInt();。这告诉程序正在期待一个Integer输入而不是另一个数据类型/ string /参数。

希望这有帮助