user2148997
user2148997

Reputation: 11

How do I get scanner to work with the arrays

Create ten accounts in an array with id 0, 1, 2 ...9, and initial balance $50. The system prompts the user to enter an id. If the id is entered incorrectly, ask the user to enter a correct id

This is what I have so far am stuck as to how to get scanner to work with the arrays

package Object_1_Programs;
import java.util.Scanner;
/**
 *
 * 
 */
public class Accounts_Test {
    public static void main(String [] args){
        //declare arrays
        int [] a=new int[9];



        double balance=50;

        Scanner input=new Scanner(System.in);
        System.out.print("Enter Your ID:");
        a[id]=input.nextInt();



    }

}

Any help will do thanks

Upvotes: 0

Views: 173

Answers (1)

user1697575
user1697575

Reputation: 2848

First you need to get ID into a var:

int id = input.nextInt();

Then you need to iterate over your array to compare each element if it equals your received id e.g.

boolean idFound = false;
for(int arrayID : a)
{
  if (arrayID == id)
  {
    idFound=true;
    // found id in the array ... do your logic here
  }
}
if (!idFound)
{
  // ID not found...ask about new id
}

Upvotes: 1

Related Questions