Menu loop after name, Java - java

I am trying to create a small Hotel application with a menu system. So far the user is asked for a room number (0-9) and a room name, once this is entered I want the user to be returned to the menu where the other menu options can be entered. I don't think the other menu options are working currently either :(
Here is my code so far:
package hotel;
import java.util.*;
public class Hotel2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Room[] myHotel = new Room[10];
myHotel[0] = new Room ();
myHotel[1] = new Room ();
myHotel[2] = new Room ();
myHotel[3] = new Room ();
myHotel[4] = new Room ();
myHotel[5] = new Room ();
myHotel[6] = new Room ();
myHotel[7] = new Room ();
myHotel[8] = new Room ();
myHotel[9] = new Room ();
String roomName;
String menuEntry = null;
int roomNum = 0;
String[] hotel = new String[11];
for (int x = 0; x < 10; x++ ) hotel[x] = "";
initialise(hotel);
while ( roomNum < 10 )
{
System.out.println("Please enter one of the following options:\n1) Add customer\n2) Delete customer from room\n3 )View all empty rooms\n4) Find a customer\n5) Load program from text file\n6) Order rooms alphabetically\n7) Store program into text file\n8) View all rooms\nInput:");
menuEntry = input.next();
while (menuEntry.equals("1"))
{
System.out.println("Enter room number (0-9):" );
roomNum = input.nextInt();
if (roomNum < 10)
{
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
}
if (menuEntry.equals("V"))
{
for (int x = 0; x < 10; x++ )
{
System.out.println("room " + x + " occupied by " + hotel[x]);
}
}
if (menuEntry.equals("E"));
{
}
if (menuEntry.equals ("D"))
{
System.out.println("Enter the room number which you would like to delete a customer from:");
roomNum = input.nextInt();
hotel[roomNum] = "empty";
}
}
}
private static void initialise( String hotelRef[] ) {
for (int x = 0; x < 10; x++ ) hotelRef[x] = "empty";
System.out.println( "initilise\n");
}
}

Your while loops waits for menuEntry to be different than 1, but you never change menuEntry inside the loop. Change it to do while loop
do {
System.out.println("Please enter one of the following options:\n1) Add customer\n2) Delete customer from room\n3 )View all empty rooms\n4) Find a customer\n5) Load program from text file\n6) Order rooms alphabetically\n7) Store program into text file\n8) View all rooms\nInput:");
menuEntry = input.next();
System.out.println("Enter room number (0-9):" );
roomNum = input.nextInt();
if (roomNum < 10)
{
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
} while (menuEntry.equals("1"));
You should also insert the rest of the options into the loop and make the conditions to match the options in the menu.
Another option with while loop
System.out.println("Please enter one of the following options:\n1) Add customer\n2) Delete customer from room\n3 )View all empty rooms\n4) Find a customer\n5) Load program from text file\n6) Order rooms alphabetically\n7) Store program into text file\n8) View all rooms\nInput:");
menuEntry = input.next();
while (menuEntry.equals("1")) {
System.out.println("Enter room number (0-9):" );
roomNum = input.nextInt();
if (roomNum < 10)
{
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
System.out.println("Please enter one of the following options:\n1) Add customer\n2) Delete customer from room\n3 )View all empty rooms\n4) Find a customer\n5) Load program from text file\n6) Order rooms alphabetically\n7) Store program into text file\n8) View all rooms\nInput:");
menuEntry = input.next();
}

Something like this help your code to look more cleaner and understandable
while ( roomNum < 10 && menuEntry.equals("1") ){
//then perform your if statement
// or preferabley use a switch(menuEntry){}
}

Related

How do I add randomly generated strings and integers to arrays while the code is running?

I'm trying to make a text-based business game, where you can hire and fire employees. Max there can be 5 employees, once strength is reached five, we may fire employees. I have written code to randomly generate details of a new applicant, but I am not able to save the hired employee. Can someone please guide?
package TestPackage;
import java.util.*;
public class EmployeeRandomizer {
/*this is where the employee's profile will be created and chosen by user. */
public static void main (String args[]) {
int spacesAvailable = 5;
int employeesHired = 0;
while(true) {
Random generate = new Random();
String[] name = {"John", "Marcus", "Susan", "Henry"};
int[] age = {20,21,22,23,24,25,25,26,26,27,28,29,30,20,21,22,23,24,25,25,26,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
String[] education = {"business", "accountant", "human resources","none"};
for(int i = 0; i < employeesHired; i++){
int index = (int)(Math.random() * 10);
System.out.println(name[index]+age[index]+education[index]);
}
System.out.println("name: " +name[generate.nextInt(4)]);
System.out.println("age: "+age[generate.nextInt(40)]);
System.out.println("education: " +education[generate.nextInt(4)]);
System.out.println("will you hire this person? (y/n)");
Scanner hire = new Scanner(System.in);
String hireEmployee = hire.next();
if(hireEmployee.equals("y")) {
System.out.println("you have hired a new employee!");
spacesAvailable = spacesAvailable-1;
employeesHired = employeesHired+1;
System.out.println("employees: " + employeesHired);
if(spacesAvailable>0 && employeesHired<5) {
System.out.println("There's " +spacesAvailable+" available spaces in your employee list.");
System.out.println("1. hire more employees");
System.out.println("2. view employees list");
Scanner hireMore = new Scanner(System.in);
String hireMoreAnswer =hireMore.next();
if (hireMoreAnswer.equals("1")) {
continue;
}
if (hireMoreAnswer.equals("2")) {
for(int i = 0; i < employeesHired;){
int index = (int)(Math.random() * 10);
System.out.println(name[index]);
System.out.println(age[index]);
System.out.println(education[index]);
break;
}
break;
}
}
if(spacesAvailable==0 || employeesHired==5) {
System.out.println("You have no more spaces left to hire more employees. (1 or 2?)");
System.out.println("1. Fire an employee (+1 space)");
System.out.println("2. Exit (more coming soon!)");
Scanner oneTwo = new Scanner(System.in);
String oneOrTwo = oneTwo.next();
if(oneOrTwo.equals("1")) {
}
if (oneOrTwo.contentEquals("2")) {
break;
}
}
}
if(hireEmployee.equals("n")) {
System.out.println("you have declined this application");
System.out.println("There's " +spacesAvailable+" available spaces in your employee list. Would you like to hire more employees? (y/n)");
Scanner hireMoreTwo = new Scanner(System.in);
String hireMoreAnswerTwo =hireMoreTwo.next();
if (hireMoreAnswerTwo.equals("y")) {
continue;
}
if (hireMoreAnswerTwo.equals("n")) {
break;
}
}
}
}
}

Testing the Output it Says its Terminated

The Code below I tried got to work correctly. When I go to "Run As" in Eclipse, the Console shows nothing and the output is blank. Please help. NOTE I took out the public class & import java because the post wasn't loading the code correctly.
public static void main(String[] args ) {
// Create new Scanner
Scanner input = new Scanner(System.in);
// Set number of students to 10
int numStudents = 10;
// Note
int [][] studentData = new int[numStudents][1];
// loop
for (int i = 0; i > numStudents; i++) {
// Note
boolean classesValidity = true ;
while (classesValidity == false) {
System.out.print("Enter classes and graduation year for student’" +
(i + 1) + " : " );
int numClasses = input.nextInt();
studentData [i][0] = numClasses;
int gradYear = input.nextInt();
studentData [i][1] = gradYear; }
for (int i1 = 0; i > numStudents; i ++) { System.out.println("\n Student " + ( i ) + " needs " +
studentData [i][0]*3 + " credits to graduate in " + studentData [i][1]); }}}}
classesValidity is initialized with true and remains unchanged. In turn the while loop is never executed and the program only iterates through studentData without operating on it.

How do I update a users input in an arraylist?

So I'm making a program for a car dealership as my final project for my class. At this time I'd say I'm about 75% done, but I am having trouble figuring out how to update the users input in an array list. So each array list slot contains the year, make, model, color, and mileage of a car. I can add a new car, I can remove a car, and I can quit my program. I have tried many things, I've read many papers, blogs, forums, and my book for class, but its always updating with the programmers input.
package carDealer;
import java.util.ArrayList;
import java.util.Scanner;
public class VehicleInformation {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<VehicleInventory> car = new ArrayList<VehicleInventory>();
String userInput = "-";
while (!userInput.equals("q")) {
System.out.println("Commands: 'a' to add, 'd' to delete, 'e' to edit, 'q' to quit");
userInput = scnr.next();
if (userInput.equals("a")) {
System.out.println("Year: ");
int year = scnr.nextInt();
System.out.println("Make: ");
String make = scnr.next();
System.out.println("Model: ");
String model = scnr.next();
System.out.println("Color: ");
String color = scnr.next();
System.out.println("Mileage: ");
int mileage = scnr.nextInt();
VehicleInventory userCar = new VehicleInventory();
userCar.setMake(make);
userCar.setModel(model);
userCar.setYear(year);
userCar.setColor(color);
userCar.setMileage(mileage);
userCar.print();
addCar(car, userCar);
}
if (userInput.equals("d")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.remove(userNum - 1);
System.out.println("count: " + car.size());
}
if (userInput.equals("e")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.get(userNum - 1);
You can just do a loop to look up for the car model the user wants to update (it can be any other attribute), and once found update it's value with the desired one:
String vehicleToLookUp = "golf"; // This will be received by user input
String vehicleNewName = "golf gti"; // This will be received by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.get(i).setSomeAttribute(...); // Set the desired attribute here
}
}
Or if you want to substitute the whole object...
String vehicleToLookUp = "golf"; // This will be received by user input
VehicleInventory newVehicle = new VehicleInventory(); // You will set the attributes by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.set(i, newVehicle ); // Create your object and pass it here
}
}
Also, instead of all those if, you could use if/else if or even a switch/case for better performance/readability (think that even if your logic is true for first if, it will check for all the other if you created, wasting time and processing power.

An application for a temporary management with Java

Hello the StackOverflow community! I am recent Java learner with 1 year of experience only. I was asked to design a software that mimics a school DB, storing all names, class, roll, and other details. When asked to, it would display appropriate messages, like calculating performance, deleting records, etc. It is yet an incomplete work but the first part (accepting and storing details) are done. I have spent a lot of time behind this and the only thing I get is a nullPointerError. Sorry, but I have been asked to stick to the basics, so no glitzy code. I have used inheritance. The superclass is "Student".
public class Student {
int roll,age = 0; // Roll to be auto-updated
String cl,name;
// Marks variables now
int m_eng, m_math, m_physics, m_chem, m_bio = 0;
public Student(){
}
public Student(int a, String cla){
age = a;
cl = cla; // Assign values
}
void setMarks(int eng, int math, int phy, int chem, int bio){
m_eng = eng; m_math = math; m_physics = phy; m_chem = chem; m_bio = bio;
}
}
Here's the error:
java.lang.NullPointerException
at Application.accept_data(Application.java:35)
at Application.execute(Application.java:23)
at Application.input(Application.java:16)
at Application.main(Application.java:101)
Here is the code, though:
import java.util.Scanner;
public class Application extends Student {
static int n; static Scanner sc = new Scanner(System.in);
static Student s[];
void input(){
System.out.println("Enter the number of students: ");
n = sc.nextInt();
s = new Student[n]; // Create array for n students
System.out.println("Enter your choice: ");
System.out.println("1. Accept student's details ");
System.out.println("2. Display all records ");
System.out.println("3. Display data student-wise ");
System.out.println("4. Delete record");
System.out.println("5. Display performance status");
System.out.println("6. Exit");
execute();
}
static void execute(){
boolean correct = false;
while (!correct){
int op = sc.nextInt();
switch(op){
case 1: accept_data(); correct = true;
case 2: disp_data();correct = true;
case 3: disp_studentwise();correct = true;
case 4: del_record();correct = true;
case 5: performance();correct = true;
case 6: System.exit(0); correct = true;//Terminate
default: System.out.println("You must enter a choice. Kindly re-enter: ");correct = false;
}
}
}
static void accept_data(){
for (int i = 0; i<s.length; i++){
s[i].roll = i+1; //Autoupdate roll
System.out.println("Enter name: "); s[i].name = sc.nextLine();
System.out.println("Enter age: "); s[i].age = sc.nextInt(); // Refer to object prope.
System.out.println("Enter class: "); s[i].cl = sc.nextLine();
System.out.println("We're heading for marks entry!");
System.out.println("Enter marks in the following order: ENGLISH, MATH, PHYSICS, CHEMISTRY, BIOLOGY");
s[i].setMarks(sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt());
}
System.out.println("Thanks. Main menu, please enter your choice now: ");
execute();
}
static void disp_data(){
System.out.println("The system will display all stored information of students available.");
for (int i = 0; i<s.length; i++){
if (s[i].roll != -1){
continue; // In case record is deleted, it won't display
}
else {
printrec(i);
}
}
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void disp_studentwise(){
System.out.println("Enter the roll number");
int r = sc.nextInt();
boolean ok = (r>s.length||r<0)?false:true;
while (!ok){
System.out.println("Incorrect roll. Please re-enter: ");
r = sc.nextInt();
if (r>s.length) ok = false;
else ok = true;
}
printrec(r-1);
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void printrec(int n){
int i = n;
System.out.println("For roll number " + s[i].roll + ", details: ");
System.out.println("Name: " + s[i].name); System.out.println("Age: " + s[i].age);
System.out.println("Class: " + s[i].cl);
System.out.println("Subject \t Marks");
System.out.println("English: \t " + s[i].m_eng); // Display record with marks
System.out.println("Maths: \t " + s[i].m_math);
System.out.println("Physics: \t " + s[i].m_physics);
System.out.println("Chemistry: \t " + s[i].m_chem);
System.out.println("Biology: \t " + s[i].m_bio);
}
static void del_record(){
System.out.println("Enter the roll number you want to delete: ");
int rll = sc.nextInt();
for (int i = 0; i<s.length; i++){
if (rll == s[i].roll){
s[i].roll = -1; // Assign non-positive value to refer deleted items
}
}
}
static void performance(){
}
public static void main(String[] args){
Application ob = new Application();
ob.input(); // Start program
}
}
Can anyone point out what's going wrong? Why there's a problem with accepting details of students after pressing for the 1st option? It shows nullPointer on s[i].roll. Keep in mind that roll is autoupdated, and user doesn't intervene there. It serves as a primary key. An explanation would be beneficial, if possible of course, I am eager to learn. Thanks.
this :
s = new Student[n]; // Create array for n students
You are just creating an array of 'n' Student objects here ... that doesn't mean that your 'n' Students are initialized ... your array contains only 'null' values ...
you may want in your accept_data method do a :
for (int i = 0; i<s.length; i++){
s[i] = new Student();
s[i].roll = i+1; //Autoupdate roll
....
You are getting an NPE because you create an array of Students in your input method, but you never populate it with Student objects, so in accept_data, you're trying to access the roll field on a non-existent object.
You will need to fill in the array with new Student objects in your input method before you call accept_data.

code is just continue looping.How to solve?

import java.util.Scanner;
public class TestPerson
{
/**
* Creates a new instance of <code>TestPerson</code>.
*/
public TestPerson()
{
}
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Menus[] menu = { new Menus("Add Member") };
MemberType[] m = { new MemberType("Corporate Member"), new MemberType("VIP Member") };
Clubs[] c = { new Clubs("Yoga", "Miss AA"), new Clubs("Kick-boxing", "Mr.AA"), new Clubs("aerobics", "Mrs.Wendy") };
RegMember[] r = new RegMember[1];
Cmember cm;
Vipmember vip;
Scanner s = new Scanner(System.in);
int choice = 0;
for (int z = 0; z < menu.length; z++)
{
System.out.println((z + 1) + ". " + menu[z].toString());
}
System.out.println("\nEnter Your selection:");
int choice = s.nextInt();
while (choice == 1)
{
for (int i = 0; i < r.length; i++)
{
System.out.println("\nYour reg no is :" + (RegMember.getNextNo() + 1));
for (int a = 0; a < m.length; a++)
{
System.out.println((a + 1) + ". " + m[a].toString());
}
System.out.println("\nEnter Your selection:");
int sel = s.nextInt();
if (sel == 1)
{
s.nextLine();
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Company Name:");
String CompanyName = s.nextLine();
String memberType = "Corporate Member";
for (int b = 0; b < c.length; b++)
{
System.out.println((b + 1) + ". " + c[b].toString());
}
System.out.println("\nEnter Your selection:");
int sel2 = s.nextInt();
String clubs = "Yoga";
cm = new Cmember(Name, Hpnum, age, CompanyName, memberType, clubs);
r[i] = new RegMember(cm);
}
else
{
s.nextLine();
System.out.println("---You will get a free exercise class---");
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Email:");
String email = s.next();
String memberType = "VIP Member";
vip = new Vipmember(Name, Hpnum, age, email, memberType);
r[i] = new RegMember(vip);
}
s.nextLine();
}
}
displayInfor(r);
}
public static void displayInfor(RegMember[] r)
{
for (int i = 0; i < r.length; i++)
System.out.println(r[i].toString());
}
}
I am a beginner for java. I am facing the problem that my code is continue looping.How to solve it?? thank you.
Your choice variable is never set to not = 1. Therefore the while loop will continue to run forever.
edit: With the amount of log messages in that code you should be able to see where surely.
If you are using If statements as such why not just alter the choice variable manually.
Anyway its too vague your question specify which loop and it would be easier to help

Categories

Resources