简体   繁体   中英

How to accept user input into two parallel arrays

I need to accept a String input and a double input from a user and store them into two parallel arrays to create a shopping cart.

I have initialized both arrays to a user determined size Amount and created a for loop to run for the inputs and store the values in the two arrays, and have set an extra input.nextLine() so the code will swallow the new line created at the end of the loop. This is my code so far,

import java.util.*;
import java.io.*;
public class Item
{
    public static void main(String[] args)
    throws java.io.IOException
    {
        int amount;
        String nextItem,I;

        Scanner input = new Scanner(System.in);

        System.out.println("Please enter the number of items you would like to add:");
        amount = input.nextInt();

        String cart[] = new String[amount];
        double price[] = new double[amount];

        for(int i = 0; i<amount; i++)
        {
            System.out.println("Please enter the name of an item:");
            cart[i] = input.nextLine();

            System.out.println("Price?");
            price[i] = input.nextDouble();
            input.nextLine();

        }

     }
}

However when the program runs the loop it runs both System.out.println commands skipping past the first input.nextLine() , and will only accept an integer input.

use two scanner class

     Scanner sc=new Scanner(System.in);   
     Scanner sc1=new Scanner(System.in);
      
    int p[] = new int[3];

    String n[] = new String[3];

    for(int i = 0; i < p.length; i++){

        System.out.print("Name: ");

        n[i] = sc.nextLine();

        System.out.print("Percentage: ");

        p[i]=sc1.nextInt();

// use two scanner class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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