0

I'm still a bit new to Java, so sorry if this is a silly question. Basically, I'm making a pizza program, so when I order with friends it calculates how much we all owe (for example, if two of us are in on a $4 pizza, we each pay $2 and add that to our own totals). I decided to make a new object type "Person" and an actual object "people". I made it an array and had each person as an index of the array. So far, I just want to make an index for each person and add a name for each. However, when my loop is first run, it skips the lines making the first index. The next ones run just fine. Any reason why and/or is my method for making this ineffective?

Main Class:

DecimalFormat f = new DecimalFormat("##.00");
Scanner scan = new Scanner(System.in);

double costItem;
int numPeopleIn;
Person[] people;
int y;

System.out.println("Welcome to Pizza Cost!\nTo start, how many people are in on this order?");

people = new Person[scan.nextInt()];

System.out.println("Type their names, pressing ENTER between names.");
for (int x = 0; x<people.length; x++) {
    System.out.println("ran");
    people[x] = new Person();
    people[x].name = scan.nextLine();
    System.out.println("hit the end");
}

Person Class:

package me.chris.pizzacost;
public class Person {

String name = "blank";
double cost;

}

Thanks so much in advance, -Chris

Chris
  • 33
  • 6
  • @immibis that did it, just added a random scan.nextLine() before the loop and it worked. Any reason why that happened? Also, do you suggest I use the array method I'm doing now? – Chris Jan 25 '15 at 03:17

1 Answers1

0

Once you've initialized your array, you need to consume an extra new line

people = new Person[scan.nextInt()];
scan.nextLine(); // ignored

This happens because nextInt() only returns the number of people to you (the actual int) and leaves the enter pressed right after it which then interferes with your program by getting scanned on the first iteration of your for loop.

Ravi K Thapliyal
  • 46,997
  • 8
  • 70
  • 84
  • that worked, thanks so much. do you think my method of object arrays is effective or is it fine for this? – Chris Jan 25 '15 at 03:20
  • It's fine for simple programs. Later you could move on to a `List` which could grow dynamically in the loop i.e. until the user says "okay, no more persons need to be added.." and you just `break` out of the `loop` then. – Ravi K Thapliyal Jan 25 '15 at 03:23