繁体   English   中英

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

[英]How to accept user input into two parallel arrays

我需要接受来自用户的String输入和double输入,并将它们存储到两个并行数组中以创建购物车。

我已将两个数组初始化为用户确定的大小Amount并创建了一个 for 循环来运行输入并将值存储在两个数组中,并设置了一个额外的input.nextLine()以便代码将吞下在以下位置创建的新行循环的结束。 到目前为止,这是我的代码,

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();

        }

     }
}

然而,当程序运行循环时,它运行System.out.println命令跳过第一个input.nextLine() ,并且只接受整数输入。

使用两个扫描仪类

     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();

// 使用两个扫描器类

暂无
暂无

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

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