-6

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

EJoshuaS - Reinstate Monica
  • 10,460
  • 46
  • 38
  • 64
trp
  • 11
  • 1
  • 1
  • 3

4 Answers4

2

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.

Shepherd
  • 150
  • 1
  • 13
1

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

 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

Mankdavix
  • 220
  • 3
  • 14
0

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.

AlwaysBTryin
  • 1,764
  • 11
  • 7
-1

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