Java:创建一个方法将5个数字输入静态数组中。

huangapple go评论62阅读模式
英文:

Java : Create 1 method to enter 5 numbers into a static array

问题

我遇到了一个练习的问题。我需要创建两个方法。

第一个方法,我想要输入5个数字(通过输入方式)。

public static void enterNumber(int[] tab, int numeral){
        Scanner input = new Scanner (System.in);
        
        int number = 0;
        int y = 0;
        
        for(int i = 0; i<tab.length; i++){
            System.out.print("输入第 " + (i+1) + " 个数字:");
            number = input.nextInt();
            tab[y++] = tab[i];
        }   
        
    }

然后,我创建了display方法来显示这些数字。

public static void display(int[] tab, int numeral){
        for(int x = 0; x<tab.length; x++){
            System.out.println(tab[x]);
        }
    }

我调用了这些方法:

int[] tab = new int[5];
int number = 0;
        
enterNumber(tab, number);
display(tab, number);

在我的输入中,我有以下内容:

输入第 1 个数字:2
输入第 2 个数字:4
输入第 3 个数字:3
输入第 4 个数字:9
输入第 5 个数字:1

然而,在我的显示中,我只得到了值 0,为什么?我应该得到值 2,4,3,9,1
我不明白。

0
0
0
0
0

谢谢你的帮助。

英文:

I am stuck about an exercise. I have to create 2 methods.

For the first method, I would like to enter 5 numbers (via an input)

public static void enterNumber(int[] tab, int numeral){
        Scanner input = new Scanner (System.in);
        
        int number = 0;
        int y = 0;
        
        for(int i = 0; i&lt;tab.length; i++){
            System.out.print(&quot;Entrer number &quot; + (i+1) + &quot; : &quot;);
            number = input.nextInt();
            tab[y++] = tab[i];
        }   
        
    }

Then, I create display method to display the numbers.

public static void display(int[] tab, int numeral){
        for(int x = 0; x&lt;tab.length; x++){
            System.out.println(tab[x]);
        }
    }

I called my methods:

int[] tab = new int[5];
int number = 0;
        
enterNumber(tab, number);
display(tab, number);

In my input I have this:

Entrer number 1 : 2
Entrer number 2 : 4
Entrer number 3 : 3
Entrer number 4 : 9
Entrer number 5 : 1

However, in my display, I only get the value 0 why ? I have to retrieve the values 2,4,3,9,1.
I don't understand.

0
0
0
0
0

Thank you for your help

答案1

得分: 1

你实际上从未将输入值分配到数组中。

tab[y++] = tab[i];

应更改为

tab[i] = input.nextInt();

您可以摆脱数字参数、y 和 numebr 变量,因为您没有使用它们。您还应该关闭扫描器。

英文:

You're never actually assigning the input value into your array.

tab[y++] = tab[i];

should be

tab[i] = input.nextInt();

You can get rid of the numeral parameter and the y and numebr variables, you're not using them. You should also close the scanner.

huangapple
  • 本文由 发表于 2020年3月4日 05:27:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/60515780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定