我收到有关我的编码的错误消息。我知道 Scanf 不是 java 函数,所以我希望得到转换它的帮助

I am getting error messages concerning my coding. I know Scanf is not a java function, so I am hoping to get help converting it

我知道 scanf 不是 java 函数,所以我希望有人能帮助我了解如何转换它。关于这个主题的研究很难拼凑起来。

这是我的代码:

import java.util.Scanner;

public class Average {

    Scanner Scanner = new Scanner (System.in);

    int main (){
        int counter;
        int number;
        int total;

        float average;

        total = 0;
        counter = 0;

        System.out.println("Enter the number 0 to end: ");
        Scanf("%d", &number);

        While (number != 0) {
            total = total + number;
            counter = counter + 1;
            System.out.println("Enter the number 0 to end: ");
            Scanf("%d", &number);
        }

        if(counter != 0) {
            average = (float) total / counter;
            System.out.println("Average is %.2f\n", average);
        } else {
            System.out.println("No valid numbers have been entered.");
            return 0;
        }
    }
}

您不能为对象使用与 class 相同的名称。更改 Scanner 初始化如下:

Scanner scanObj = new Scanner(System.in);

将所有 scanf 语句替换为以下内容:

number = scanObj.nextInt();

像这样使用输入`

public class seting{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);`
int total = 0;
System.out.printlnln("Enter the value of total :");
total = scan.nextInt(); // use  integer input
}
}

这些是对您的代码所做的更改:

import java.util.Scanner;
public class one {


    public static void main(String[] args) {
    Scanner Scanner = new Scanner (System.in);

        int counter;
        int number = 1;
        int total;
        float average;
        total = 0;
        counter = 0;



        while(number != 0){
             System.out.println("Enter the number 0 to end: ");
             number = Scanner.nextInt();
             System.out.printf("%d", number);

            total = total + number;
            counter = counter + 1;


    }
        if(counter != 0){

        average =  ((float)total /(float)counter);

             System.out.printf("Average is %.2f\n", average);
        }
        else{
            System.out.println("No valid numbers have been entered.");
            //return 0;
         }
     }
}

首先扫描器获取用户输入的值。 number = Scanner.nextInt(); 这必须在您的 while loop 内部完成,因为它会检查条件。

接下来我更改的是 average = (float) total / counter;

这仅将总值转换为浮点数。两端用括号。

average = ((float)total /(float)counter); 像这样