简体   繁体   English

如何接受用户输入到两个并行数组中

[英]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.我需要接受来自用户的String输入和double输入,并将它们存储到两个并行数组中以创建购物车。

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.我已将两个数组初始化为用户确定的大小Amount并创建了一个 for 循环来运行输入并将值存储在两个数组中,并设置了一个额外的input.nextLine()以便代码将吞下在以下位置创建的新行循环的结束。 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.然而,当程序运行循环时,它运行System.out.println命令跳过第一个input.nextLine() ,并且只接受整数输入。

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 // 使用两个扫描器类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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