我有3个错误,我无法解决我的授权,低水平的技能。
我只是试图将第一年的销售数据计算在内,这可行,但我试图将销售额总计低于产出并收到错误。
C:\ Users \ Steven \ Documents \ assignment2.java:21:错误:' .class' 预计
System.out.println(int counter +" \ t \ t \ t \ t" + sales [counter]);C:\ Users \ Steven \ Documents \ assignment2.java:21:错误:不是声明
System.out.println(int counter +" \ t \ t \ t \ t" + sales [counter]);C:\ Users \ Steven \ Documents \ assignment2.java:21:错误:';'预计
System.out.println(int counter +" \ t \ t \ t \ t" + sales [counter]);
代码:
import java.util.Scanner;
public class assignment2
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome\n");
System.out.println("Sales Month\t\tSales made");
int sales[]={60,54,62,67,54,67,51,50,62,55,49,70};
int sum=0;
for(int counter=0;counter < sales.length;counter++)
{
sum+=sales [counter];
}
System.out.println("The sum of the sales is " +sum);
System.out.println(int counter + "\t\t\t\t" + sales[counter]);
}
}
答案 0 :(得分:3)
我认为你需要这样的东西:
import java.util.Scanner;
public class assignment2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome\n");
System.out.println("Sales Month\t\tSales made");
int sales[] = { 60, 54, 62, 67, 54, 67, 51, 50, 62, 55, 49, 70 };
int sum = 0;
for (int counter = 0; counter < sales.length; counter++) {
sum += sales[counter];
System.out.println(counter + "\t\t\t\t" + sales[counter]);
}
System.out.println("The sum of the sales is " + sum);
}
}
答案 1 :(得分:2)
从int
counter
前面移除int counter + "\t\t\t\t" + sales[counter]
此外,计数器已在你的for循环中声明,但你在它之外使用它。在for循环之前声明它或将该行放在for循环中。
我刚编译并运行我的更改,它的工作原理。这是输出:
Sales Month Sales made
0 60
1 54
2 62
3 67
4 54
5 67
6 51
7 50
8 62
9 55
10 49
11 70
The sum of the sales is 701
答案 2 :(得分:1)
你的问题在这里..
class assignment2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome\n");
System.out.println("Sales Month\t\tSales made");
int sales[] = { 60, 54, 62, 67, 54, 67, 51, 50, 62, 55, 49, 70 };
int sum = 0;
int counter;
for (counter = 0; counter < sales.length; counter++) {
sum += sales[counter];
System.out.println("\t\t\t\t" + sales[counter]);
}
System.out.println("The sum of the sales is " + sum);
}
}
您无法在 println 语句中声明任何变量,只需删除它并在for循环之前声明它(使其变为实例变量)
答案 3 :(得分:1)
首先,如@Olivier Poulin所述,请移除int
关键字。
此外,counter
变量不是范围。它在for循环中定义,不存在在其外部。
为了避免这种情况,只需在for
循环之外声明它。
最后,计数器只相当于sales.length
,因为你总是递增1.因此,你的代码应如下所示:
int counter;
for (; counter < sales.length; counter++) { // initialization is done outside the for loop
sum += sales[counter];
System.out.println("\t\t\t\t" + sales[counter]);
}
System.out.println(sales.length + "\t\t\t\t" + sales[sales.length - 1]);
查看java教程here。
答案 4 :(得分:0)
从这一行
System.out.println(int counter + "\t\t\t\t" + sales[counter]);
删除int
只有在声明变量时才会给出数据类型,你无法在那里声明它。事实上,你必须删除整行,因为在循环中声明了计数器,这个语句是在循环外循环。之后删除int放在里面for loop body