Ryan H
Ryan H

Reputation: 85

Java using scanner to access array elements

I've created an array 8 elements long using the scanner class. I'm trying to accept user inputs via scanner and print out the value at that index location. eg if the user enters '2', it prints out the value at the second element. I've searched on google but all the resources are how to use the scanner to input data into an array, not using the scanner to retreive data back. the only way I thought of is by using a ridiculous amount of if else statements but there must be a cleaner way to do it in a loop?

This is my array, I've used the scanner to fill my array. Now, on prompt, the user must input a number from 1 to 8. If they input 1, print out solution[0]. Input 8, print out solution[7] etc. Hope its easier to understand now

    String[] solution = new String[8];
    Scanner scan = new Scanner( System.in );
    for( int i = 0; i < solution.length; i++ ){
        System.out.println( "Enter solution:" );
        solution[ i ] = scan.next();
    }
    scan.close();
    Scanner scan1 = new Scanner( System.in );
    String selection;

    System.out.println("Enter an int between 0 and 7 to retrieve the Selection: ");
    selection = scan1.next();
    int i = Integer.parseInt(selection);

    System.out.println( "The Selection is: " + solution[i] );

Upvotes: 0

Views: 6927

Answers (4)

Vijay
Vijay

Reputation: 1

 import java.util.Scanner;
 public class array1
 {
 public static void main(String args[])
 {
 int arr[]=new arr[100];
 int i;
 Scanner sc=new Scanner(System.in);
 System.out.pritln("Enter the Number of Element less than 100");
 int a=sc.nextInt();
 System.out.println("Enter the Number");
 for(i=0;i<a;i++)
 {
 arr[i]=sc.nextInt();
 }
 System.out.println("List of Elements in array");
for(i=0;i<a;i++)
{
System.out.println(arr[i]);
}
}
}

Upvotes: 0

Birb
Birb

Reputation: 866

You have to read an int, and use this when getting the value stored at the specified index.

A way to do this is the following:

yourArray[scanner.nextInt()];

Where scanner is the Scanner object.

To catch the excpetions you may receive when reading things you assume are numbers, you could do this:

Scanner scanner = new Scanner(System.in);
try {
    yourArray[scanner.nextInt()];

} catch(IllegalStateException | NoSuchElementException e) { // <--- Java 1.7 syntax, in case you wonder
    e.printStackTrace();
}

Upvotes: 0

vangelion
vangelion

Reputation: 255

This is difficult without any code, but basically, use the scanner to get the input into string selection, get the integer value into int i with int i = Integer.parseInt(selection);, then myArray[i].

Upvotes: 1

Neil Locketz
Neil Locketz

Reputation: 4318

Scanner input = new Scanner(System.in);

then output:

urArray[input.nextInt()];

Upvotes: 0

Related Questions