2016-10-05 50 views
0

嗨,那裏我是超新的編碼,當我嘗試運行下面的代碼時,我總是收到'.class'錯誤。我錯過了什麼?在java中的'.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; 
    } 
} 
+4

「'userWeight = scnr.nextInt [];'」 - 這些是括號中的錯誤類型。使用'()'。這將解決你的一個問題。 – resueman

回答

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 
1

這是問題

userWeight = scnr.nextInt[]; 

解決這個由:

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

OR

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

應工作

PS:作爲預防措施不導入Scanner類的兩倍。做一次就足夠了

+0

導入一次不是「預防措施」,只是一次清理。 –

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包導入兩次看出,相反,您可以一次導入全部導入java.util。*;

此外,您正在嘗試返回。請注意,無效方法不需要返回值。 VOID除了沒有任何回報。