简体   繁体   English

Java中的数组和用户输入

[英]Arrays and user input in Java

So for arrays I'm trying to ask the user to input 10 numbers between 1 and 100 into an array. 因此,对于数组,我试图要求用户在数组中输入1到100之间的10个数字。 I'm having some trouble wrapping my head around this. 我在解决这个问题时遇到了一些麻烦。 I do not understand how to set an array size AND have it call from a variable associated with user input at the same time. 我不明白如何设置数组大小并同时从与用户输入关联的变量中调用它。 Is it even possible to do this? 甚至有可能这样做吗? I'm not asking for a solution but maybe just a better way to understand this. 我不是在寻求解决方案,而可能只是一种更好的理解方式。 My school book does not help much. 我的课本没有太大帮助。

You can try this: 您可以尝试以下方法:

int[] arr = new int[10];
int pos = 0;
Scanner in = new Scanner(System.in);
while (pos < 10) {
    System.out.print("input a number(1-100):");
    int a = in.nextInt();
    if (a > 0 && a <= 100) arr[pos++] = a;
}

And don't forget to import java.util.Scanner; 并且不要忘记import java.util.Scanner;

you need to provide more information with your question. 您需要提供有关问题的更多信息。 What language you are using? 您使用什么语言? How is your program structure? 您的程序结构如何?

Since you already know your array size and everything it is very easy to start. 由于您已经知道阵列大小和所有内容,因此非常容易启动。

Firstly declare your array. 首先声明你的数组。 Since i don't know what language you are using, i will just explain in c++ and java. 由于我不知道您使用的是哪种语言,所以我只会用C ++和Java进行解释。

C++ Example C ++示例

int array_numbers[10]; // Which is 0-9.

Then you go ahead and prompt the user for an input. 然后,继续并提示用户输入。

cout << "Please enter 10 numbers : ";

Once this is done, the user is now going to input 10 numbers. 完成此操作后,用户现在将输入10个数字。 For this you do a loop with the command to store the values. 为此,您可以使用命令循环存储值。

for(int x=0;x<=9;x++) //
{
       cin >> array_numbers[x]; //entering the input into the variable index x
}

finally to display the value: 最后显示值:

for(int x=0;x<=9;x++)
{
     cout << "array_numbers[" << x+1 << "] is : " << array_numbers[x]; 
     //x+1 to show the index to the user.
}

Java Example Java示例

and another example in java 还有java中的另一个例子

Declaring the variable and the scanner : 声明变量和扫描器:

int[] array_numbers = new int[10];
Scanner scan = new Scanner(System.in); 
//import java.util.Scanner; <- don't forget to do this in the beginning

Then the loop : 然后循环:

for(int x=0;x<=9;x++)
{
    array_numbers[x] = scan.nextInt();
}

and lastly to display the results: 最后显示结果:

for(int y=0; y<=9; y++)
{
    System.out.println("array_numbers["+ (y+1) +"] is : "+ array_numbers[y]);
}

Please do comment on this if you need further help. 如果您需要进一步的帮助,请对此发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM