ArrayList <integer>,试图找到输入值的平均值</integer>

时间:2014-11-26 14:06:11

标签: java for-loop arraylist

尝试查找作为输入输入到列表中的整数的平均值。 无法弄清楚如何,我得到一个错误,说它找不到符号 在行total = total + in;

import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;

public class Lists

{
    public static void main(String[] args)
    {
        PrintStream print = new PrintStream(System.out);
        Scanner scan = new Scanner(System.in);
        List<Integer> bag = new ArrayList<Integer>();
        print.println("Enter your integers");
        print.println("(Negative=sentinel)");
        int total = 0;
        int count = 0;

        for (int in = scan.nextInt(); in > 0; in = scan.nextInt());
        {
            total = total + in;
            count = count + 1;
        }

        double x = total / count;
        print.println("The average is: " + x);
    }
}

另外,有一种简单的方法可以输出高于平均值的数字除以逗号吗?

5 个答案:

答案 0 :(得分:4)

for循环后删除分号:

for (int in = scan.nextInt(); in > 0; in = scan.nextInt())

没有为编译器定义in的原因是分号会通过充当for循环的空体来解除其定义的范围。

答案 1 :(得分:2)

从循环中删除;

for (int in = scan.nextInt(); in > 0; in = scan.nextInt());

更改为

for (int in = scan.nextInt(); in > 0; in = scan.nextInt())

答案 2 :(得分:1)

你不应该;在循环之后......

for (int in = scan.nextInt(); in > 0; in = scan.nextInt())//remove ; here

答案 3 :(得分:1)

for循环的语法是:

for(initialization; Boolean_expression; update)
{
   //Statements
}

您已添加分号;,因此它会成为for循环的空体。您必须在代码中的for (int in = scan.nextInt(); in > 0; in = scan.nextInt())行后删除分号

修改后的代码:我在修改后提供代码。

public class Lists

{
    public static void main(String[] args)
    {
        PrintStream print = new PrintStream(System.out);
        Scanner scan = new Scanner(System.in);
        List<Integer> bag = new ArrayList<Integer>();
        print.println("Enter your integers");
        print.println("(Negative=sentinel)");
        int total = 0;
        int count = 0;

        for (int in = scan.nextInt(); in > 0; in = scan.nextInt()){
            total = total + in;
            count = count + 1;
        }

        double x = total / count;
        print.println("The average is: " + x);
    }
}

答案 4 :(得分:1)

上述代码需要进行两项更改:

1.你需要在for循环之后删除分号,这会使循环变得无用,并且你想要做的所有迭代都不会发生。

2.第二个变化是您需要将变量total或count之一转换为double以避免截断,否则结果将始终为整数。

修改后的代码如下:

&#13;
&#13;
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;

public class Lists

{
	public static void main(String[] args)
	{
		PrintStream print = new PrintStream(System.out);
		Scanner scan = new Scanner(System.in);
		List<Integer> bag = new ArrayList<Integer>();
		print.println("Enter your integers");
		print.println("(Negative=sentinel)");
		int total = 0;
		int count = 0;
		
		for (int in = scan.nextInt(); in > 0; in = scan.nextInt())
		{
			total = total + in;
			count = count + 1;
		}
		
		double x = (double)total / count;
		print.println("The average is: " + x);
	}
}
&#13;
&#13;
&#13;