java中的'.class error'

问题描述 投票:0回答:3

您好,我是编码的新手,当我尝试运行下面的代码时,我不断收到'.class'错误。我错过了什么?

import java.util.Scanner;

import java.util.Scanner;


public class PeopleWeights {
    public static void main(String[] args) {
        Scanner scnr = new Scanner (System.in);
        userWeight = new int[5];
        int i = 0;

        userWeight[0] = 0;
        userWeight[1] = 5;
        userWeight[2] = 6;
        userWeight[3] = 7;
        userWeight[4] = 9;

        System.out.println("Enter weight 1: ");
        userWeight = scnr.nextInt[];

        return;
    }
}
java class
3个回答
1
投票

这就是问题

userWeight = scnr.nextInt[];

解决这个问题:

userWeight[0] = scnr.nextInt();        //If you intended to change the first weight

要么

userWeight[1] = scnr.nextInt();        //If you intended to change the value of userWeight at index 1 (ie. the second userWeight)

应该管用

PS:作为预防措施,请勿两次导入Scanner类。做一次就足够了


0
投票

我理解你的内涵,以下是实现你的想法的两种可能方式:

我看到你手动给出值为userWeight [0] = 0;如果您想手动提供,我建议不要使用扫描仪,如下所示。

public static void main(String[] args) {
     int[] userWeight={0, 5, 6,7,9};
         System.out.println("Weights are" +userWeight);//as you are giving values.
 }

如果您的意图是在运行时或用户获取值,请遵循以下方法

 public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("This is runtime and you need to enter input");

        int[] userWeight = new int[5];

            for (int i= 0; i < userWeight.length; i++) {
                userWeight[i] = sc.nextInt();
                System.out.println(userWeight[i]);
            }
        }

PS:

我看到你正在使用util package import两次,而你可以一次导入所有导入java.util。*;

你也试图回来。请注意,对于void方法,它不需要返回值。 VOID不包括任何回报。


0
投票

首先不要多次导入包,现在让我们去实际的“错误”。

这里:

import java.util.Scanner;

public class PeopleWeights {
    public static void main(String[] args) {
         Scanner scnr = new Scanner (System.in);
         int userWeight[] = new int[5];//You need to declare the type
         //of a variable, in this case its int name[]
         //because its an array of ints
         int i = 0;

         userWeight[0] = 0;
         userWeight[1] = 5;
         userWeight[2] = 6;
         userWeight[3] = 7;
         userWeight[4] = 9;

         System.out.println("Enter weight 1: ");
         userWeight[0] = scnr.nextInt();//I belive that you wanted to change
         // the first element of the array here.
         //Also nextInt() is a method you can't use nextInt[]
         //since it doesn't exists
         //return; You dont need it, because the method is void, thus it doesnt have to return anything.

    }

}

而不是这个:

userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;

你可以在声明一个数组时这样做:

int userWeight[] = {0,5,6,7,9};//instantiate it with 5 integers
© www.soinside.com 2019 - 2024. All rights reserved.