【问题标题】:How to accept user input into two parallel arrays如何接受用户输入到两个并行数组
【发布时间】:2019-04-07 00:59:41
【问题描述】:

我需要接受来自用户的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(),并且只接受整数输入。

【问题讨论】:

  • input 是什么类型的对象? (它是扫描仪吗?它是如何实例化的?)
  • 如果您将input 定义为Scanner input = new Scanner(System.in);,此代码应该可以正常工作。
  • 一些注意事项:1) CartPriceAmount 应该是 cartpriceamount,根据标准编码约定和 2) 你是调用input.nextInt();,但将结果分配给double 值的数组。另一个学生曾经告诉我,老师告诉他们使用大写的变量名。这很古怪。
  • @Steve 我敢打赌,他们在此之前正在使用扫描仪,也许他们在此之前以整数形式读取 Amount,因此新行字符在他们读取之前仍位于标准输入项目名称,但他们没有提供足够的信息来确定,因为正如你所指出的,这段代码应该可以工作。

标签: java java.util.scanner parallel-arrays


【解决方案1】:

使用两个扫描器类

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

// 使用两个扫描器类

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 2011-09-08
    • 1970-01-01
    • 2012-07-18
    • 2021-12-08
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多