Need to add the numbers from an object - java

I am writing a program that takes names, dates and numbers from a user as many times as they enter it and then adds up the numbers that were entered. If you look at the third for loop you will see where I am trying to add. I tried doing total = cust[i].amount + total; but I cannot access amount for some reason.
This is for an assignment.(I know were not supposed to post homework questions on here but I'm stumped.)The only data member Customer is to have is name
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int MAX = 9999;
Customer [] cust = new Customer[MAX];
int choice = 0;
int cnt;
double total = 0;
for(cnt=0; cnt < MAX && (choice == 1 || choice ==2 || choice == 0); cnt++){
System.out.println("For a Service customer type 1, for a Purchaser type 2, to terminate the program press 9");
choice = s.nextInt();
switch (choice){
case 1:
cust [cnt] = new Service();
break;
case 2:
cust [cnt] = new Purchaser();
break;
default:
break;
}
}
for(int i=0; i < cnt; i++){
if(cust[i]!= null)
cust[i].showData();
}
for(int i=0; i < cnt; i++ ){
total = cust[i].amount + total;
}
s.close();
}
}
interface Functions {
public void getData();
public void showData();
}
abstract class Customer implements Functions {
protected String name;
}
class Purchaser extends Customer {
protected double payment;
public Purchaser(){
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter payment amount: ");
payment = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s Payment amount is: %.2f\n",name,payment);
}
}
class Service extends Customer {
protected String date;
protected double amount;
public Service () {
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter date of Service: ");
date = s.nextLine();
System.out.println("Enter the cost of Service: ");
amount = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
}

There's no field amount in the class Customer.

There are several issues, but you should
// Use one loop...
for(int i=0; i < cnt; i++){
if(cust[i]!= null) { // <-- check for null.
cust[i].showData();
/* or
if (cust instanceof Service) {
total += ((Service)cust[i]).amount; // <-- assuming a public amount
// field in Service. This is not a good
// practice, but your question is difficult to
// answer.
}
*/
total += cust[i].getAmount(); // <-- a method.
}
}
That is add a getAmount to your interface if you want to get the amount (or, to make this code work - change the access modifier and add a public field named amount to Customer and remove the shadowing fields in your subclasses).
Or, you can learn about Collections (which I strongly recommend you do anyway) - and actually use the correct storage method - perhaps ArrayList.

This is one solution that I could come up with, where we add a getAmount method to the interface:
import java.util.Scanner;
public class home {
/**
* #param args
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int MAX = 2;
Customer [] cust = new Customer[MAX];
int choice = 0;
int cnt;
double total = 0;
for(cnt=0; cnt < MAX && (choice == 1 || choice ==2 || choice == 0); cnt++){
System.out.println("For a Service customer type 1, for a Purchaser type 2, to terminate the program press 9");
choice = s.nextInt();
switch (choice){
case 1:
cust [cnt] = new Service();
break;
case 2:
cust [cnt] = new Purchaser();
break;
default:
break;
}
}
for(int i=0; i < cnt; i++){
if(cust[i]!= null)
cust[i].showData();
total = cust[i].getAmount() + total;
}
s.close();
}
}
abstract class Customer implements Functions {
protected String name;
}
import java.util.Scanner;
class Service extends Customer {
protected String date;
protected double amount;
public Service () {
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter date of Service: ");
date = s.nextLine();
System.out.println("Enter the cost of Service: ");
amount = s.nextDouble();
}
public double getAmount(){
return this.amount;
}
public void showData() {
System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
}
}
import java.util.Scanner;
class Purchaser extends Customer {
protected double payment;
public Purchaser(){
getData();
}
public double getAmount(){
return this.payment;
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter payment amount: ");
payment = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s Payment amount is: %.2f\n",name,payment);
}
}
interface Functions {
public void getData();
public void showData();
public double getAmount();
}

Related

How to sum value in a specific object?

I have this code where you would search for the patient ID and when found a sub menu will show, the user would then be prompted to choose. If the user chooses bill the would then be asked to enter a transaction and it would be summed to the balance in the same object as the ID that was searched. However when the user inputs a value it always sums the value to the balance(450) in the object.
How can I fix this?
NB: it's in an array
output: adds the input to the first object only.
patient pAccount[] = new patient [10];
patient p1 = new patient("Jabari","luck",d1 ,"234-4343", "p01" ,450);
patient p2 = new patient("Lisa", "nun", d2,"311-5634" , "p02",300);
patient p3 = new patient("Kyle", "Hep",d3 ,"555-5555" , "p03",2000 );
//search array for patient ID
public static void ID(person [] pAccount) {
Scanner scan= new Scanner(System.in);
String num = scan.next();
for(int i=0; i< pAccount.length; i++) {
if (pAccount[i].getpatID().equals(num)) {
System.out.println("found");
break;
}
}
}
//sum user input to balance
public static void bill(person[] pAccount) {
Scanner in = new Scanner (System.in);
double sum;
double num= in.nextDouble();
for(int i=0; i <= pAccount.length; i++) {
person ad= pAccount[i];
sum = ((patient) ad).getbalance()+ num;
System.out.println("Balance: " +sum);
break;
}
}```
what I understood from your question is, you need to add sum to the balance of a specific object in Patient Object array. Below is the way to do,
(I excluded few member variables which I didn't get just by looking at Object creation in your question and kept only name, patId and balance in Patient Class. Also I assumed you've Constructor with all the fields)
I took your code and modified a little for you requirement. You can refer comments I added in the code snippets.
PatientMainClass.class
public class PatientMainClass {
public static void main(String[] args) {
Patient pAccount[] = new Patient[3];
Patient p1 = new Patient("Jabari", "p01", 450);
pAccount[0] = p1;
Patient p2 = new Patient("Lisa", "p02", 300);
pAccount[1] = p2;
Patient p3 = new Patient("Kyle", "p03", 2000);
pAccount[2] = p3;
//Use bill method to add Amount to existing balance of all the Patient Objects
Patient.bill(pAccount);
System.out.println();
for (int i = 0; i < pAccount.length; i++) {
System.out.println("After adding amount to the Balance of pAccount[" + i + "] is : " + pAccount[i].getBalance());
}
System.out.println();
//Use billToSpecific method to add Amount to specific Patient Object
//to billToSpecific method, pass both Patient Array and Patient ID to which you want to add Amount
Patient.billToSpecificPatient(pAccount, "p02");
System.out.println();
for (int i = 0; i < pAccount.length; i++) {
System.out.println("After adding amount to p02, Balance of pAccount[" + i + "] is : " + pAccount[i].getBalance());
}
} }
Patient.class
public class Patient {
private String name;
private String patId;
private double balance;
public Patient(String name, String patId, double balance) {
super();
this.name = name;
this.patId = patId;
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatId() {
return patId;
}
public void setPatId(String patId) {
this.patId = patId;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
// This method will Add entered value i.e.. "num" to the Balance of all the Patient Objects
public static void bill(Patient[] pAccount) {
System.out.println("In bill method"); // Always try using System.out.println for Debugging
Scanner in = new Scanner(System.in);
double sum;
double num = in.nextDouble();
for (int i = 0; i < pAccount.length; i++) {
Patient ad = pAccount[i];
sum = ((Patient) ad).getBalance() + num;
ad.setBalance(sum);
System.out.println("Balance: " + sum);
// break; // Commenting break statement to add balance to all the Objects
}
}
// This method will Add entered value i.e.. "num" to the Balance of the Specific Patient Object
public static void billToSpecificPatient(Patient[] pAccount, String patId) {
System.out.println("In billToSpecific method"); // Always try using System.out.println for Debugging
Scanner in = new Scanner(System.in);
double sum;
double num = in.nextDouble();
for (int i = 0; i < pAccount.length; i++) {
if (pAccount[i].getPatId().equals(patId)) {
Patient ad = pAccount[i];
sum = ((Patient) ad).getBalance() + num;
ad.setBalance(sum);
System.out.println("Balance: " + sum);
break; // Using break statement to exit the loop once we add amount to specific Patient Object
}
}
} }
I guess, you can now resolve your issue with the help of these code snippets. Hope it is helpful.

Cannot get program to print to command line or report file

I have a program here that compiles but I cannot get it to print to the command line or a report file. Any assistance is appreciated. Here is the error that I get:
Error: Main method not found in class Township, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Press any key to continue . .
import java.util.*;
import java.io.*;
//Township class
class Township
{
//instance variables
String name;
int households;
int bicycles;
double average;
String tier;
double funding;
//constructor
public Township(String name, int households, int bicycles)
{
this.name = name;
this.households = households;
this.bicycles = bicycles;
}
//calculate average bikes per household
public void AverageBikes()
{
average = (double)bicycles/households;
}
//calculate the funding
public void Funding()
{
if(average>=3.0) funding = 50000.00;
else if(average>=2.0) funding = 40000.00;
else if(average>=1.0) funding = 30000.00;
else if(average>=0.5) funding = 20000.00;
else funding = 0.00;
}
//calculate the tier
public void Tier()
{
if(average>=3.0) tier = "One";
else if(average>=2.0) tier = "Two";
else if(average>=1.0) tier = "Three";
else if(average>=0.5) tier = "Four";
else tier = "Five";
}
//sort the townships in alphabetical order by township name
public static void sort(Township t[], int n)
{
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
if(t[i].name.compareTo(t[j].name) > 0){
Township tmp = t[i];
t[i] = t[j];
t[j] = tmp;
}
}
}
}
}
//Driver class
class Driver
{
//method to print the report
public static void printReport(Township t[], int n)
{
//sort the list
Township.sort(t, n);
System.out.println ("Township Number Bicycles Average Bikes Proposed Tier");
System.out.println ("Name Households reported Per household Funding Designation");
//print the report
for(int i=0; i<n; i++)
{
System.out.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
}
//method to get input from user
public static Township getInput(Scanner sc)
{
System.out.print ("Enter the name of Township: ");
String name = sc.nextLine();
System.out.print ("Enter the number households: ");
int household = sc.nextInt();
System.out.print ("Enter the bicycles reported: ");
int bicycles = sc.nextInt();
Township town = new Township(name, household, bicycles);
town.AverageBikes();
town.Funding();
town.Tier();
return town;
}
//method to get input from file
public static int readFile(Township town[]) throws IOException
{
//open the file
Scanner sc = new Scanner(new File("town.txt"));
int i=0;
while(sc.hasNext())
{
String name = sc.nextLine();
int household = sc.nextInt();
sc.nextLine();
int bicycles = sc.nextInt();
sc.nextLine();
town[i] = new Township(name, household, bicycles);
town[i].AverageBikes();
town[i].Funding();
town[i].Tier();
i++;
}
return i;
}
//method to write the report to the file
public static void writeFile(Township t[], int n) throws IOException
{
//sort the list
Township.sort(t, n);
FileWriter writer = new FileWriter("report.txt");
PrintWriter pout = new PrintWriter(writer);
pout.printf ("Township Number Bicycles Average Bikes Proposed Tier\n");
pout.printf ("Name Households reported Per household Funding Designation\n");
for(int i=0; i<n; i++)
{
pout.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
pout.close();
}
//main method
public static void main (String[] args) throws IOException
{
//create an instance of Scanner class
Scanner sc = new Scanner(System.in);
//create an array of Townships
Township town[] = new Township[10];
int i= readFile(town);
//processing
while(true)
{
//menu
System.out.println ("1. Input\n2. Report\n3. Exit");
//prompt to enter a choice
System.out.print("Enter choice: ");
int n = sc.nextInt();
switch(n)
{
case 1:
//get input from user
town[i] = getInput(sc);
i++;
break;
case 2:
//print the report
printReport(town, i);
break;
case 3:
//write to file
writeFile(town, i);
System.out.println ("Goodbye!");
return;
}
}
}
}
EDIT
I updated the error and some code thanks to the responses.
Here is the new error that I get:
Error: Exception in thread "main" java.util.InputMismatchException at
java.base/java.util.Scanner.throwFor(Scanner.java:939) at
java.base/java.util.Scanner.next(Scanner.java:1594) at
java.base/java.util.Scanner.nextInt(Scanner.java:2258) at
java.base/java.util.Scanner.nextInt(Scanner.java:2212) at
Township.readFile(Township.java:143) at
Township.main(Township.java:20)
Code:
import java.util.*;
import java.io.*;
//Township class
public class Township{
//instance variables
String name;
int households;
int bicycles;
double average;
String tier;
double funding;
public static void main (String[] args) throws IOException{
//create an instance of Scanner class
Scanner sc = new Scanner(System.in);
//create an array of Townships
Township town[] = new Township[10];
int i= readFile(town);
//processing
while(true)
{
//menu
System.out.println ("1. Input\n2. Report\n3. Exit");
//prompt to enter a choice
System.out.print("Enter choice: ");
int n = sc.nextInt();
switch(n)
{
case 1:
//get input from user
town[i] = getInput(sc);
i++;
break;
case 2:
//print the report
printReport(town, i);
break;
case 3:
//write to file
writeFile(town, i);
System.out.println ("Goodbye!");
return;
}
}
}
//==================================================================
//constructor
public Township(String name, int households, int bicycles)
{
this.name = name;
this.households = households;
this.bicycles = bicycles;
}
//calculate average bikes per household
public void AverageBikes()
{
average = (double)bicycles/households;
}
//calculate the funding
public void Funding()
{
if(average>=3.0) funding = 50000.00;
else if(average>=2.0) funding = 40000.00;
else if(average>=1.0) funding = 30000.00;
else if(average>=0.5) funding = 20000.00;
else funding = 0.00;
}
//calculate the tier
//==================================================================
public void Tier()
{
if(average>=3.0) tier = "One";
else if(average>=2.0) tier = "Two";
else if(average>=1.0) tier = "Three";
else if(average>=0.5) tier = "Four";
else tier = "Five";
}
//sort the townships in alphabetical order by township name
public static void sort(Township t[], int n)
{
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
if(t[i].name.compareTo(t[j].name) > 0){
Township tmp = t[i];
t[i] = t[j];
t[j] = tmp;
}
}
}
}
//==================================================================
//method to print the report
public static void printReport(Township t[], int n)
{
//sort the list
Township.sort(t, n);
System.out.println ("Township Number Bicycles Average Bikes Proposed Tier");
System.out.println ("Name Households reported Per household Funding Designation");
//print the report
for(int i=0; i<n; i++)
{
System.out.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
}
//==================================================================
//method to get input from user
public static Township getInput(Scanner sc)
{
System.out.print ("Enter the name of Township: ");
String name = sc.nextLine();
System.out.print ("Enter the number households: ");
int household = sc.nextInt();
System.out.print ("Enter the bicycles reported: ");
int bicycles = sc.nextInt();
Township town = new Township(name, household, bicycles);
town.AverageBikes();
town.Funding();
town.Tier();
return town;
}
//==================================================================
//method to get input from file
public static int readFile(Township town[]) throws IOException
{
//open the file
Scanner sc = new Scanner(new File("bicycledata.txt"));
int i=0;
while(sc.hasNext())
{
String name = sc.nextLine();
int households = sc.nextInt();
sc.nextLine();
int bicycles = sc.nextInt();
sc.nextLine();
town[i] = new Township(name, households, bicycles);
town[i].AverageBikes();
town[i].Funding();
town[i].Tier();
i++;
}
return i;
}
//==================================================================
//method to write the report to the file
public static void writeFile(Township t[], int n) throws IOException{
//sort the list
Township.sort(t, n);
FileWriter writer = new FileWriter("report.txt");
PrintWriter pout = new PrintWriter(writer);
pout.printf ("Township Number Bicycles Average Bikes Proposed Tier\n");
pout.printf ("Name Households reported Per household Funding Designation\n");
for(int i=0; i<n; i++)
{
pout.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
pout.close();
}//end method
}//end class
Try this:
class Township {
//instance variables
String name;
int households;
int bicycles;
double average;
String tier;
double funding;
//constructor
public Township(String name, int households, int bicycles) {
this.name = name;
this.households = households;
this.bicycles = bicycles;
}
// Rest of Township class code...
public static void main(String[] args) {
// Do things...
}
}
Take a look to this: Essentials
Every application needs one class with a main method. This class is
the entry point for the program, and is the class name passed to the
java interpreter command to run the application.
IOException is thrown to you for another reason. The answer to your question has been given.
I think you are compiling class Township which do not have main() method. You should compile Driver class because class Driver has main() method and creating the object of class Township.

Java passing class array into array

I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}

Array out of bounds exception with scanning user input into an array

Hey I have code for a project im trying to finish up and I keep getting array out of bounds exceptions at a certain part and would like to know how to fix it. My project is to create a reservation system using 3 classes Room,Reservation and a client class. I'm having trouble with my bookRoom class after asking for the number of guests for the room.Any help would be greatly appreciated. The exception occurs at line 57 in the reservation class. The line in question is in bold.
`
public class Reservation {
public void roomInitialization(Room[] room,int numberOfRooms,int numberOfSmokingRooms)
{
boolean smoking=true;
String[] guestName={null,null,null,null};
for (int i=0;i<numberOfRooms;i++)
{
if (i>=numberOfSmokingRooms)
smoking=false;
room[i]=new Room(smoking,false,guestName,null,i+1);
}
}
public void displayRoomsInfo(Room[] room,int numberOfRooms)
{
for (int i=0;i<numberOfRooms;i++)
{
System.out.println("Room " + room[i].getroomNumber() + "\t" +
(room[i].getsmoking()?"Smoking room":"Non-Smoking Room"));
if (room[i].getoccupied())
{
System.out.print("Phone: "+room[i].getguestPhone()+"\t");
for(int j=0;j<4;j++)
System.out.print(room[i].getguestName()[j]+"\t");
System.out.println();
}
}
}
public void bookRoom (Room[] room, int numberOfRooms)
{
displayRoomsInfo(room, numberOfRooms);
Scanner scan = new Scanner(System.in);
Scanner scans = new Scanner(System.in);
Scanner scand = new Scanner(System.in);
System.out.print("Enter a Room Number: ");
int roomNumber = scan.nextInt()-1;
if (roomNumber >=0 && roomNumber < 30){
room[roomNumber].setoccupied(true);
System.out.print("Enter a Phone Number: ");
String guestPhone = scans.nextLine();
room[roomNumber].setguestPhone(guestPhone);
System.out.print("Enter number of guests:(Max of 4 per room) ");
int guests = scand.nextInt()-1;
String[] guestName = new String[guests];
for (int i=0;i<guestName.length;i++)
System.out.print("Enter guest names: ");
**guestName[guests] = scand.next();**
room[roomNumber].setguestName(guestName);
}
else
System.out.println("Enter a valid room number");
}
public void checkOut(Room[] room)
{
Scanner scan=new Scanner(System.in);
int roomNumber;
String[] nullguestName={null,null,null,null};
do
{
System.out.print("Enter the room number: ");
roomNumber=scan.nextInt()-1;
if (roomNumber>=0 && roomNumber<30)
break;
else
System.out.println("Enter a valid room number");
}while(true);
if (room[roomNumber].getoccupied())
{
room[roomNumber].setoccupied(false);
room[roomNumber].setguestPhone(null);
room[roomNumber].setguestName(nullguestName);
}
else
System.out.println("room "+(roomNumber+1)+" is already empty");
}
}
`
Code for the other classes
package hotel;
public class Room {
private boolean smoking;
private boolean occupied;
private String[] guestName=new String[4];
private String guestPhone;
private int roomNumber;
public Room (boolean smoking,boolean occupied,String[] guestName, String guestPhone,int roomNumber)
{
this.smoking=smoking;
this.occupied=occupied;
for (int i=0;i<4;i++)
this.guestName[i]=guestName[i];
this.guestPhone=guestPhone;
this.roomNumber=roomNumber;
}
public void setoccupied(boolean occupied) {
this.occupied = occupied;
}
public void setsmoking(boolean smoking) {
this.smoking = smoking;
}
public void setroomNumber(int roomNumber) {
this.roomNumber = roomNumber;
}
public void setguestPhone(String guestPhone) {
this.guestPhone = guestPhone;
}
public void setguestName(String[] guestName)
{
for (int i=0;i<4;i++)
this.guestName[i]=guestName[i];
}
public boolean getsmoking() {
return this.smoking;
}
public boolean getoccupied(){
return this.occupied;
}
public String getguestPhone(){
return this.guestPhone;
}
public int getroomNumber() {
return this.roomNumber;
}
public String[] getguestName()
{
String[] tempguestName=new String[4];
for (int i=0;i<4;i++)
tempguestName[i]=this.guestName[i];
return tempguestName;
}
}
package hotel;
import java.util.Scanner;
public class ReservationDemo {
public static void main(String[]args)
{
final int numberOfRooms=30, numberOfSmokingRooms=5;
Room[] room=new Room[numberOfRooms];
Reservation reservation=new Reservation();
reservation.roomInitialization(room,numberOfRooms,numberOfSmokingRooms);
int userSelection;
Scanner scan=new Scanner(System.in);
do
{
System.out.println("Press: 1-Book room\t2-checkout\t3-display all rooms\t4-exit. ");
userSelection=scan.nextInt();
switch(userSelection)
{
case 1:
reservation.bookRoom(room,numberOfRooms);
break;
case 2:
reservation.checkOut(room);
break;
case 3:
reservation.displayRoomsInfo(room,numberOfRooms);
break;
case 4:
System.exit(0);
default:
break;
}
}while (true);
}
}
There are lots of mistake in your code.
First-- Use the following code instead of your version in Reservation class
System.out.print("Enter number of guests:(Max of 4 per room) ");
int guests = scand.nextInt();
String[] guestName = new String[guests];
for (int i=0;i<guestName.length;i++) {
System.out.print("Enter guest names: ");
guestName[i] = scand.next();
}
Second -- Use the following method in Room class instead of the existing one.
public void setguestName(String[] guestName)
{
for (int i=0;i<guestName.length;i++)
this.guestName[i]=guestName[i];
}
Let me know what you achieve
You are trying to index into the guests array using the variable guests which is the size of the array, you should be using the iteration counter variable i instead:
guestName[guests] = scand.next() should be guestName[i] = scand.next()

Method to display records.

Hey guys just need help on how to finish this up.
Code Snippet:
import java.util.Scanner;
public class CreateLoans implements LoanConstants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//set the program here
float prime;
float amountOfLoan = 0;
String customerFirstName;
String customerLastName;
String LoanType;
System.out.println("Please Enter the current prime interest rate");
prime = sc.nextInt() / 100f;
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
LoanType = sc.next();
//enter the Loan amount
System.out.println("Enter the amount of loan");
amountOfLoan = sc.nextInt();
//enter Customer Names
System.out.println("Enter First Name");
customerFirstName = sc.next();
System.out.println("Enter Last Name");
customerLastName = sc.next();
//enter the term
System.out.println("Enter the Type of Loan you want. 1 = short tem , 2 = medium term , 3 = long term");
int t = sc.nextInt();
}
}
I need to display the records I have asked and store the object into an array.
so this where I'm stuck. I need to do this in a loop 5 times and by the end display all records in an array, if that makes sense?
Try this way :
import java.util.Scanner;
public class CreateLoans {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Loan[] loans = new Loan[5];
for(int i=0;i<5;i++) {
loans[i] = new Loan();
System.out.println("Please Enter the current prime interest rate");
float prime = sc.nextInt();
prime = (float)(prime/100f);
loans[i].setPrime(prime);
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
String loanType = sc.next();
loans[i].setLoanType(loanType);
//enter the Loan amount
System.out.println("Enter the amount of loan");
float amountOfLoan = sc.nextFloat();
loans[i].setAmountOfLoan(amountOfLoan);
//enter Customer Names
System.out.println("Enter First Name");
String customerFirstName = sc.next();
loans[i].setCustomerFirstName(customerFirstName);
System.out.println("Enter Last Name");
String customerLastName = sc.next();
loans[i].setCustomerLastName(customerLastName);
}
//Display details
for(int i=0;i<5;i++) {
System.out.println(loans[i]);
}
}
}
class Loan {
private float prime;
private float amountOfLoan = 0;
private String customerFirstName;
private String customerLastName;
private String LoanType;
public float getPrime() {
return prime;
}
public void setPrime(float prime) {
this.prime = prime;
}
public float getAmountOfLoan() {
return amountOfLoan;
}
public void setAmountOfLoan(float amountOfLoan) {
this.amountOfLoan = amountOfLoan;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public String getLoanType() {
return LoanType;
}
public void setLoanType(String loanType) {
LoanType = loanType;
}
#Override
public String toString() {
return "First Name : " + customerFirstName + "\n" +
"Last Name : " + customerLastName + "\n" +
"Amount of Loan : " + amountOfLoan + "\n" +
"Loan type : " + LoanType + "\n" +
"Prime : " + prime + "\n\n";
}
}
Create a Loan class and put all necessary details as private members into it and override toString() method.
Make a ArrayList and add all the variables inside that list
ArrayList arrlist = new ArrayList();
arrlist.add(prime);
arrlist.add(LoanType);
arrlist.add(amountOfLoan);
arrlist.add(customerFirstName );
arrlist.add(customerLastName);
arrlist.add(t);
and display the ArrayList
System.out.println(arrlist);
Example of a loop
int[] nums = new int[5];
String[] names = new String[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++){
System.out.println("Enter a number: ");
int number = input.nextInt();
// insert into array
nums[i] = number;
System.out.println("Enter a name: ");
String name = input.nextLne();
// insert into array
names[i] = name;
}
Everything you want to be looped 5 times, you can put inside the loop. Whatever values you want to store, you can do that in the loop also.

Categories

Resources