簡體   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