I am working on this airline program. The program should ask the user how many seats on the plane are sold and then I have this for loop to allow a user to enter a name and a meal choice for each person on the plane.
I have tried reading through some different questions about infinite for loops on stackoverflow, but I can't seem to figure out exactly what is going wrong with my code. I feel like there must be something about for loops that I am not understanding because I thought that it would only go through until your i < someNumber is no longer true.
So when I run this program, say I enter 2 seats I would expect it to go through the loop just twice, but It just keeps going. asking for a name and then a meal.
import java.util.Scanner;
public class Flyers
{
String name;
String mealType;
int economySeats;
int businessSeats;
int firstClassSeats;
int count;
public Flyers()
{
}
public String toString()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
return "Name: " + name + ", Meal " + mealType;
}
public void addEconomyFlyers()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of economy seats sold: ");
economySeats = in.nextInt();
for(count = 0; count < economySeats; count++)
{
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
Flyers newFlyer = new Flyers();
String seat = newFlyer.toString();
}
}
Here is my main class if that is helpful.
import java.util.Scanner;
public class Aviation
{
public Aviation()
{
}
public static void main(String[] args)
{
int option;
FlightCost newFlight = new FlightCost();
FlightProfit flight = new FlightProfit();
Flyers newFlyers = new Flyers();
Scanner in = new Scanner(System.in);
System.out.print("Enter new flight location: ");
String location = in.next();
do{
String menu = "\n Please select an option to perform"
+ "\n1 (1) Get flight costs."
+ "\n2 (2) Get flight profits."
+ "\n3 (3) Enter names/meals."
+ "\n4 (4) Exit.";
System.out.println(menu);
option = in.nextInt();
}while (option < 0 || option > 4);
switch(option)
{
case 1:
newFlight.getCost(location);
break;
case 2:
flight.addEconomySeats();
flight.addBusinessSeats();
flight.addFirstClassSeats();
flight.getProfit(location);
break;
case 3:
newFlyers.addEconomyFlyers();
break;
case 4:
System.out.println("Exit");
break;
default:
System.out.println("Error: must select menu option.");
}
}
}
remove below code from toString()
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
You are already reading these from the for loop.
Also, your do-while loop is all wrong. The condition doesn't make sense. It should be option > 0 && option <4
As Pat said:
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
this code in the toString() is obsolete
however the do while does make sense, to me at least, as i see it you want the menu printed out each time the user gives an invalid int, however you are still letting 0 get through although that is not a valid choice, the do while should be:
while (option <= 0 || option > 4);
or
while (option < 1 || option > 4);
Another quirk in your code:
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
Flyers newFlyer = new Flyers();
String seat = newFlyer.toString();
you create a new instance of the class you have just modified and call toString() on, even though you have not populated that class with data, so the toString method as it would be after the edit pat suggested will return "Name: Meal "
As i see your code is a work in progress, try adding more System.out.print on various variables for debugging purpose or use a debugger, though i know using debugger when learning can be difficult, it sure was for me. Also remember that every time you create a new instance ex:
Flyers newFlyer = new Flyers();
it has only the data that is either set by default or set in your constructor ex:
public Flyers()
{
}
I hope what i wrote was helpful, have a nice day and keep at it.
Related
I am trying to write a Java program in which the user specifies how many "student records" they would like to input, followed by the student's name, age, and GPA, which then gets stored as text. However, I am having a problem with my text not including all entered data and a mysterious dangling newline that I cannot get rid of.
Here is my program:
import java.io.*;
import java.util.Scanner;
public class CreateFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
FileWriter fwriter = new FileWriter("c:\\Students.dat");
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = " ";
String next = " ";
int age = 0;
int hm = 0;
double gpa = 0.0;
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.nextLine();
input.nextLine();
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
next = input.nextLine();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
StudentFile.close();
System.exit(0);
}
}
Here is sample input and output to illustrate my issues:
run:
How many student records would you like to enter: 3
Enter Name: Jon
Enter Age: 20
Enter GPA: 3.4
Enter Name: Bill
Enter Age: 24
Enter GPA: 3.6
Enter Name: Ted
Enter Age: 34
Enter GPA: 3.9
This is the produced text file:
20
3.4
Bill
24
3.6
Ted
34
3.9
Why doesn't it store the first name entered? Why isn't there a newline in the first entry, but it is in the others?
The problem is that you're using nextLine() when you need to be using next(). I'm assuming you put the second input.nextLine() in there because you were initially having a problem where it would print out "Enter Name: " and then immediately "Enter Age: ". nextLine() is telling your program to skip whatever is there, and not to wait for it. The reason that this paradigm worked at all for any of your entries is that you put next = input.nextLine() at the bottom of your loop. Here's a fix:
package createfile;
import java.io.*;
import java.util.Scanner;
public class CreateFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
FileWriter fwriter = new FileWriter("c:Students.dat");
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = " ";
String next = " ";
int age = 0;
int hm = 0;
double gpa = 0.0;
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.next();
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
StudentFile.close();
System.exit(0);
}
}
You could also just move your input.nextLine() above name=input.nextLine() and it would have the same effect.
The other examples only work if you don't have names like "James Peter" - in their code examples only James would be saved as name.
I'd prefer this:
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
input.nextLine();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.nextLine();
System.out.print("Enter Age: ");
age = input.nextInt();
input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
input.nextLine();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
This is the corrected for loop:
for ( int x = 1; x <= hm; x++ )
{
System.out.print( "Enter Name: " );
name = input.next();
input.nextLine();
System.out.print( "Enter Age: " );
age = input.nextInt();
input.nextLine();
System.out.print( "Enter GPA: " );
gpa = input.nextDouble();
next = input.nextLine();
StudentFile.println( name );
StudentFile.println( age );
StudentFile.println( gpa );
}
Some things you may want to consider:
Handle the IOException - it should not be ignored!!
Use the methods hasNextXXX() of the Scanner to check if something is available.
Refactor your usage of the variable next, it's never really used.
It's not necessary to call System.exit( 0 ) from the main method - rather use the return statement with a meaningful value.
package contractmanager;
import java.util.*;
/**
*
* #author Tom McCloud
*/
public class ContractManager {
static Scanner keyb = new Scanner(System.in);
// global scanner
public static void main(String[] args) {
int option;
//variable declaration
String clientName;
String packageSize;
String dataBundle;
String reference;
int period;
boolean intlCalls;
//display menu to user
System.out.println("Welcome: \n");
System.out.println("1. Enter new contract ");
System.out.println("2. Display contract summary");
System.out.println("3. Display summary of contract for selected month");
System.out.println("4. Find and display contract");
System.out.println("0. Exit");
//take option off user
option = keyb.nextInt();
//WIP - only working on option 1 at the minute
switch(option) {
case 1:
clientName = clientName();
packageSize = packageSize();
dataBundle = dataBundle();
reference = reference();
break;
}
exit();
}
public static void exit()
{
System.out.println("Thank you for using the contract manager. Goodbye!");
}
public static String clientName()
{
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.nextLine();
return name;
}
public static String packageSize()
{
String size;
System.out.println("Please input your package size: ");
System.out.println(" 1. Small \n 2. Medium \n 3. Large");
size = keyb.next();
return size;
}
public static String dataBundle()
{
String data;
System.out.println("Please input data bundle size: ");
System.out.println("1. Low \n 2. Medium \n 3. High \n 4. Unlimited");
data = keyb.next();
return data;
}
public static String reference()
{
String ref;
boolean isRefValid = false;
do {
System.out.println("Please input your reference code: ");
ref = keyb.next();
if(ref.length() > 6)
{
System.out.println("Reference number too long, re-enter!");
}
for(int i = 0; i < 2; i++)
{
if(Character.isDigit(ref.charAt(i)))
{
System.out.println("First two characters must be letters!");
}
}
} while(isRefValid = false);
return ref;
}
}
So, this is some code I have. If I press enter code hereone, it executes these, now technically shouldn't this be in order of one another once each method reaches completion and returns?
For example, on execution after pressing "1" I get the following output:
Please input your full name:
Please input your package size:
1. Small
2. Medium
3. Large
Whereas this should come one by one, after the full name has been inputted it should move onto the package size step. If I input it goes to the third step rather than repeating for the second step's input.
I think it's because in your clientName function you have just printed "Please input your full name: " without waiting for input. For example you have to do something like below here scan.nextLine() will wait until user have press enter:
Scanner scan = new Scanner();
System.out.println("Please input your full name:");
String name= scan.next();
System.out.println(name);
scan.nextLine();
Updated: Try by updating clientName function as below
public static String clientName() {
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.next();
keyb.nextLine();
return name;
}
when i use s.charAt(0) while s is an string input from the user, I get this as an error even though the program runs the first half of the program.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at Shopping.main(Shopping.java:22)
What's the solution to this program? here is my code.
import java.util.Scanner;
public class Shopping {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Programmed by Raymond Lee");
System.out.println("Welcome to Shopper's Paradise");
ShoppingCart cart = new ShoppingCart();
System.out.print("Enter the name of the first item: ");
String item = keyboard.nextLine();
System.out.print("Enter the quantity: ");
int quantity = keyboard.nextInt();
System.out.print("Enter the price: ");
double price = keyboard.nextDouble();
cart.addToCart(item, price, quantity);
System.out.print("Enter the name of the next item or Q to quit: ");
String quit = keyboard.nextLine();
char choice = quit.charAt(0);
while((choice != 'Q' && choice != 'q') || quit.length() != 1) {
quit = item;
System.out.print("Enter the quantity: ");
quantity = keyboard.nextInt();
System.out.print("Enter the price: ");
price = keyboard.nextDouble();
cart.addToCart(item, price, quantity);
System.out.print("Enter the name of the next item or Q to quit: ");
quit = keyboard.nextLine();
choice = quit.charAt(0);
}
System.out.println(cart);
}
}
The error is occuring at this line
char choice = quit.charAt(0);
This is due to the fact that when you call
double price = keyboard.nextDouble();
then nextDouble leaves the newline in the input stream. So when following is called
String quit = keyboard.nextLine();
then result of nextLine is empty string, results in the given error when you try to use charAt method.
To resolve this error, simply change following
String quit = keyboard.nextLine();
To
String quit = keyboard.next();
Hope this helps
The objective is to create an account registration method for an ATM object. But I keep breaking on the if statement used to enter the loop. I assume my "wording" is off, but I'm drawing a blank on how to fix it. Any suggestions? The problem itself is at if(acc[i].getAcc()==0)where .getAcc is a getter in a class.
package atmassignment;
import java.util.Scanner;
public class AtmAssignment {
static Scanner in = new Scanner(System.in);
static int cou = 1;
static Account[] acc = new Account[10];
public static void main(String[] args) {
menu();
}
public static void menu(){
char opt;
System.out.println("Thanks for accessing ATManager.");
System.out.println("Please select a menu option to proceed.");
System.out.println("1-Register a new account, 2-Access an account, 0-Exit ATManager");
opt = in.next().charAt(0);
switch (opt) {
case '1':
newAccount();
break;
case '2':
selAccount();
break;
case '0':
System.out.println("Goodbye.");
break;
default:
System.out.println("Invalid Entry.");
break;
}
}
public static void newAccount(){
System.out.println("Account registration");
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i] = new Account(cou, bal, cus);
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
}
}
This allocates an array of object references:
static Account[] acc = new Account[10];
However it doesn't actually allocate any objects, so you are probably getting a null pointer exception when you try to access the first element. In your init code, do something like this:
for(int i = 0; i < 10; i++)
acc[i] = new Account();
You call acc[i].getAcc()==0 before actually constructing your objects. Maybe modify the for loop so that you create your objects and then gather input and update your objects later on with setter methods? This of course requires that you have some sort of default constructor for your Account class.
acc[j through maxLength] = new Account(); //where j spans the entire length of the array
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i].setContact(###);
acc[i].setBalance(###); //ETC
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
Probably you didn't populate your Account[] array. Here I only can see you declare your array like -
static Account[] acc = new Account[10];
So after that when you are trying to get you array element using for loop than you can't access them. You are getting the error at if(acc[i].getAcc()==0) this line. So I suggest remove the if check since you are populating your Account later in this line - acc[i] = new Account(cou, bal, cus);
Hope it will help.
Thanks a lot.
In this program, I'm creating 2 objects from the CarOrder class with preset values. I'm then asking the user for another 2 sets of values to create 2 more objects. Unfortunately, after entering tax status for the first one, it will skip letting the user enter a value for the buyer on the second one. Why is it randomly skipping this one question?
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter Buyer: ");
String buyer1 = keyboard.nextLine();
System.out.println("Enter the type of car being purchased: ");
String car1 = keyboard.nextLine();
System.out.println("Enter the cost of this purchase: ");
double cost1 = keyboard.nextDouble();
System.out.println("Enter quantity of cars being purchased: ");
int quantity1 = keyboard.nextInt();
System.out.println("Enter tax status: ");
boolean tax1 = keyboard.nextBoolean();
System.out.println("Enter Buyer: ");
String buyer2 = keyboard.nextLine();
System.out.println("Enter the type of car being purchased: ");
String car2 = keyboard.nextLine();
System.out.println("Enter the cost of this purchase: ");
int cost2 = keyboard.nextInt();
System.out.println("Enter quantity of cars being purchased: ");
int quantity2 = keyboard.nextInt();
System.out.println("Enter tax status: ");
boolean tax2 = keyboard.nextBoolean();
CarOrder state = new CarOrder(buyer1, car1, cost1, quantity1, tax1);
CarOrder it = new CarOrder(buyer1, car2, cost2, quantity2, tax2);
System.out.println("Chicago Car Wholesalers" );
System.out.println("Oct. 30th, 2012");
System.out.println("New Car Order Report");
}
}
I think nextBoolean() is consuming the boolean but leaving the end of line character, which your nextLine() then consumes as its input. So, add keyboard.nextLine() before asking for the second buyer.
keyboard.nextBoolean() reads only the boolean value. Now when you continue reading with keyboard.nextLine() you get Enter key (That's the skipping part you're talking about).
You need to add keyboard.nextLine(); after asking for the second buyer.
Maybe it's not skipping it, you're using the wrong buyer when creating "it". Look at this closely:
CarOrder state = new CarOrder(buyer1, car1, cost1, quantity1, tax1);
CarOrder it = new CarOrder(buyer1, car2, cost2, quantity2, tax2); // <-- This should be buyer2