JavaLearner
JavaLearner

Reputation: 55

How to add arrays using a for loop and scanner in Java

I'm having trouble with the enterItemInfo() method at the bottom of the block. I want a user to input an item name, and an item price right after, and loop through a number of times equal to itemNames.length. The problem I'm having is that when I run this method, it somehow skips right to the second input, and then any input given results in an error. Not sure where I'm going wrong here.

import java.util.Scanner;

public class Item {
    //FIELDS
    private int itemAmount;
    private String[] itemNames;
    private double[] itemPrices;

    Scanner item = new Scanner(System.in);

    public int getItemAmount() {
        return this.itemAmount;
    }

    public void setItemAmount() {
        System.out.println("Please enter the number of items: ");
        this.itemAmount = item.nextInt();
        System.out.print("There are " + this.itemAmount + " items.");
    }

    public void enterItemInfo() {
        itemNames = new String[this.itemAmount];
        for (int i = 0; i < itemNames.length; i++) {
            System.out.println("Enter the next item name: ");
            itemNames[i] = item.nextLine();
            System.out.println("Enter the price for " + itemNames[i] + ": ");
            itemPrices[i] = item.nextDouble();
            item.nextLine();
        }
    }
}

Upvotes: 2

Views: 707

Answers (2)

SGC
SGC

Reputation: 190

You have missed to make an object for itemprices array. And your code skip the part of entering the product name too. This code should be working:

public void enterItemInfo() {
    itemNames = new String[this.itemAmount];
    itemPrices = new Double[this.itemAmount];
    for (int i = 0; i < itemNames.length; i++) {
        System.out.println("Enter the next item name: ");
        itemNames[i] = item.next();
        item.nextLine();
        System.out.println("Enter the price for " + itemNames[i] + ": ");
        itemPrices[i] = item.nextDouble();
        item.nextLine();
    }
}

Screen shot for running code:

enter image description here

Upvotes: 1

Crih.exe
Crih.exe

Reputation: 524

nextInt() method doesn't read the new line when you hit enter, so the nextLine() method just read this new line.

There are two workarounds:

You can put a nextLine() right after the nextInt() in this way:

itemAmount = item.nextInt();
item.nextLine();

Or, even better, you can read all the inputs using nextLine() and parse the strings into whatever you need:

itemAmount = 0; // give a standard amount if somethings fail in the try-catch
try {
    itemAmount = Integer.parseInt(item.nextLine()); // parse the read line to Integer
} catch(Exception e) {  // catch the exception if the entered line can't be parsed into an Integer. In this case the itemAmount value will be 0
    e.printStackTrace();
}

Upvotes: 0

Related Questions