簡體   English   中英

為什么我不能從另一個方法訪問我在 main 方法中創建的 int 數組值? (初學者Java編碼器)

[英]Why can't I access my int array values that I made in my main method from another method? (beginner Java coder)

我正在為我的學校項目制作一個簡單的程序,我要求一個列表,然后返回最大值、最小值或平均值。 我在 class 中創建了一個數組,然后在我的主要方法中編輯值,我試圖從我的其他方法中訪問新值,但不能,IDK 為什么。

導入 java.util.Scanner; 導入 java.util.Arrays;

公共 class numbersAreWeird {

    private static double[] thing;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        
        print("Hello");
        print("What is the length of your set of numbers?");
        int whyEven = in.nextInt();
        
        thing = new double[whyEven];
        
        for(int i = 0; i < thing.length; i++)
        {
            System.out.println("What do you want to place for " + i  + " ?");
            whyEven = in.nextInt();
            thing [i] = whyEven;
        }
             
        print("This is your arrray " + Arrays.toString(thing));
        
        print("Do you want to [1] Find the max [2] the min");
        print(" [3] find the average");
        int tree = in.nextInt();
        
        if(tree == 1)
        {
            getMax();
        }
        if(tree == 2)
        {
            getMin();
        }
        if(tree == 3)
        {
            getAve();
        }
            
    }

公共 static 字符串 getMax() {

        Double max = Double.MIN_VALUE;
        
        for(int i = 0; i < thing.length; i++)
        {
            if(max<thing[i])
                max = thing[i];
        }
        
        return ("The Max value of the list is ")+ max;
    }
    
    public static String getMin()
    {
        Double min = Double.MAX_VALUE;
        
        for(int i = 0; i < thing.length; i++)
        {
            if(min>thing[i])
                min = thing[i];
        }
        
        return ("The Min value of the list is ") + min;
    }
    
    public static String getAve()
    {
        int total = 0;
        int count = 0;
        
        for (int i = 0; i < thing.length; i++)
        {
            total += thing[i];
            count++;
        }
        
        return ("The average of the list is ") + total/count;
    }
        
    public static void print(String str)
    {
        System.out.println(str);
    }

}// class 結束

我認為您打算打印而不是返回,或者更確切地說,忘記打印返回的值。

您應該像這樣打印返回的值(這涉及較少的代碼修復):

if (tree == 1) {
    print(getMax());
}else if (tree == 2) {
    print(getMin());
}else if (tree == 3) {
    print(getAve());
}

另外,我用 1 個if和 2 個else if語句替換了 3 個if語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM