Java 如何打印数组索引号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50094404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print array index number?
提问by trp
How to print the number of Array?
如何打印数组的数量?
import java.util.Scanner;
public class ArrayTest {
public static void main(String[] args) {
String[] fruit = new String[5];
Scanner scan = new Scanner(System.in);
for(int i=0;i<fruit.length;i++)
{
System.out.print("Fruit number "+ Math.addExact(i, 1)+ ": ");
fruit[i] = scan.nextLine();
}
for(String a : fruit) {
System.out.println(a);
/*How do i add Like the number like this
1.Banana
2.Apple
instead of Banana
Apple
}
}
}
How do i add Like the number like this 1.Banana 2.Apple instead of Banana Apple
我如何添加像这样的数字 1.Banana 2.Apple 而不是 Banana Apple
采纳答案by Shepherd
Though your question is not very clear, it seems you just want o print the array index with contents, in that case you can follow the below code:
虽然您的问题不是很清楚,但您似乎只想打印包含内容的数组索引,在这种情况下,您可以按照以下代码进行操作:
for(int i=0;i<fruit.length;i++){
System.out.println((i+1)+"."+fruit[i]);
}
Or if you want the number to store the index in the array contents, then you can go with:
或者,如果您希望数字将索引存储在数组内容中,那么您可以使用:
for(int i=0;i<fruit.length;i++)
{
System.out.print("Fruit number "+ Math.addExact(i, 1)+ ": ");
fruit[i] = (i+1)+"."+scan.nextLine();
}
Hope it helps.
希望能帮助到你。
回答by Mankdavix
Take a counter variable
取一个计数器变量
int k=1;
then when you are printing the names just add it in front of the string inside System.out.print() and increment k after it
然后当您打印名称时,只需将其添加到 System.out.print() 内的字符串前面并在其后增加 k
for(syntax)
{
System.out.println(k+"."+a);
k++;
}
or you can use
或者你可以使用
for(int k=0;k<fruit.length;k++){
System.out.println((k+1)+"."+fruit[k]);
}
and if you want to take input like that use
如果你想接受这样的输入,请使用
for(int k=0;k<fruit.length;k++)
{
System.out.print("Fruit number "+ Math.addExact(k, 1)+ ": ");
fruit[k] = (k+1)+"."+scan.nextLine();
}
i hope it will sollve ur problem
我希望它能解决你的问题
回答by AlwaysBTryin
You can either (1) use a for(int i=0...)
loop like you did when scanning input, or (2) use a ListIterator. See How to get the current loop index when using Iterator?for an example.
您可以 (1)for(int i=0...)
像扫描输入时那样使用循环,或者 (2) 使用 ListIterator。请参阅如何在使用迭代器时获取当前循环索引?举个例子。
回答by user11913306
This code will show the index no with value.
此代码将显示带值的索引号。
int a[] = {2,9,8,5,7,6,4,3,1};
for(int i=0;i<a.length;i++)
{
System.out.println((i)+"."+a[i]+" ");
}
Output:0.2 1.9 2.8 3.5 4.7 5.6 6.4 7.3 8.1
输出:0.2 1.9 2.8 3.5 4.7 5.6 6.4 7.3 8.1