how do I pass a user inputted integer through methods? - java

Essentially i've isolated the issue, the int numpersons begins as 0. I take a user input to make it a particular number which is the array size, when the second method begins it takes the 0 again and then the array has an out of bounds exception. I want to pass it from one method to the next, or make them more successive, idk how to do this
thanks in advance
import java.util.Scanner;
public class BankApp {
Scanner input = new Scanner(System.in);
int numpersons = 0;
private SavingsAccount[] clients = new SavingsAccount[numpersons];
public BankApp() {
while (numpersons < 1) {
System.out.println("How many people are there?");
numpersons = input.nextInt();
if (numpersons < 1 || 2147483647 < numpersons) {
System.out.println("invalid number, please enter again");
}
}
input.nextLine();
}
public void addClients() {
int i = 0;
while (i < numpersons) {
System.out.println("enter account id " + (i + 1));
String AccountID = input.nextLine();
System.out.println("enter account name " + (i + 1));
String AccountName = input.nextLine();
System.out.println("enter account balance " + (i + 1));
Double AccountBalance = input.nextDouble();
clients[i] = new SavingsAccount(AccountID, AccountName, AccountBalance);
input.nextLine();
i++;
}
}
public void displayClients() {
int i = 0;
while (i < numpersons) {
System.out.println("======================================");
System.out.println("Account ID " + (i + 1) + ": " + clients[i].getID());
System.out.println("Account Name " + (i + 1) + ": " + clients[i].getName());
System.out.println("Account Balance " + (i + 1) + ": " + clients[i].getBalance());
System.out.println("======================================");
i++;
}
}
public static void main(String args[]) {
BankApp ba = new BankApp();
ba.addClients();
ba.displayClients();
}
}

Related

How do i rerun part of a code that uses an array?

I'm trying to make a code that takes a users input and prints their schedule, but I'm running into a problem with my do-while loop.
My program will not rerun. I'm getting an error that says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at com.company.Main.main(Main.java:25)
Here is my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String rerun;
do {
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("How many courses do you have?");
int numCourse = input.nextInt();
input.nextLine();
String[][] timetable = new String[numCourse][2];
for (int j = 0; j < numCourse; j++) {
System.out.println("What is the name of your course #" + (j + 1) + "?");
String course = input.nextLine();
timetable[j][0] = course;
System.out.println("What is your teachers name for " + course + "?");
String teacher = input.nextLine();
timetable[j][1] = teacher;
}
System.out.println("Hello " + name + ", here is your timetable:");
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
System.out.println("Would anyone else like to print their schedule? (yes/no)");
rerun = input.next();
}while(rerun.equalsIgnoreCase("yes"));
System.out.println("Goodbye!");
}
}
Problem is in second for loop where you display your from array. put next() inplace of nextLine() because sometimes it skip the position.
Change
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
To
for (int i = 0; i < numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
Suppose your numCorse is 2. In your code, loop start from 0 and terminate after 2 so, Your loop working right while i is 0 and 1 but if i is going to 3 you get exception ArrayIndexOutOfBound.

How do I initialize a variable in an if else program that combines three choices?

I'm writing a party planner program for a question for class.
I can't initialize my three choices of entertainment, decorations, and food.
Eclipse tells me that I should set all these values to 0. I have to stick to these if else statements because that's what we have learned so far.
Here is my code:
import java.util.Scanner;
public class PartyPlanner {
public static void main(String[] args) {
// TODO Auto-generated method stub
int entertainment;
int decorations;
int food;
int budget = entertainment + decorations + food;
Scanner keyboard = new Scanner(System.in);
System.out.println("For your choices, please type"
+ " in what is contained in the brackets."
+ " We will do the calculations for you.");
System.out.println("Choose entertainment:"
+ " [band] for $400 or " + "[DJ] for $150");
String choice1 = keyboard.nextLine();
if (choice1 == "DJ")
{
entertainment = 400;
}
else if (choice1 == "band")
{
entertainment = 150;
}
System.out.println("Where would you like to buy "
+ "decorations? [school] for $100 or [your own] for $250 ?");
String choice2 = keyboard.nextLine();
if (choice2 == "school")
{
decorations = 100;
}
else if (choice2 == "your own")
{
decorations = 250;
}
System.out.println("Would you like to purchase"
+ " [pizza] for $200 or [sub sandwiches]"
+ " for $250 or [appetizers] for $150?");
String choice3 = keyboard.nextLine();
if (choice3 == "pizza")
{
food = 200;
}
else if (choice3 == "sub sandwiches")
{
food = 250;
}
else if (choice3 == "appetizers")
{
food = 150;
}
System.out.println("You have chosen: " + choice1 +
" and " + choice2 + " and " + choice3);
System.out.println("The total cost of this party"
+ " comes out to:" + budget);
}
}
The problem is
The local variable entertainment, decorations, and food may have not been initalized.
First , you have to make the sum at the end of the code because at first the variables are not initialized yet , and secondly you can assign a value of zero if no choice have been made , like this :
public class PartyPlanner {
public static void main(String[] args) {
// TODO Auto-generated method stub
int entertainment;
int decorations;
int food;
Scanner keyboard = new Scanner(System.in);
System.out.println("For your choices, please type"
+ " in what is contained in the brackets."
+ " We will do the calculations for you.");
System.out.println("Choose entertainment:"
+ " [band] for $400 or " + "[DJ] for $150");
String choice1 = keyboard.nextLine();
if (choice1 == "DJ")
{
entertainment = 400;
}
else if (choice1 == "band")
{
entertainment = 150;
}
else { entertainment = 0; }
System.out.println("Where would you like to buy "
+ "decorations? [school] for $100 or [your own] for $250 ?");
String choice2 = keyboard.nextLine();
if (choice2 == "school")
{
decorations = 100;
}
else if (choice2 == "your own")
{
decorations = 250;
}
else { decorations = 0; }
System.out.println("Would you like to purchase"
+ " [pizza] for $200 or [sub sandwiches]"
+ " for $250 or [appetizers] for $150?");
String choice3 = keyboard.nextLine();
if (choice3 == "pizza")
{
food = 200;
}
else if (choice3 == "sub sandwiches")
{
food = 250;
}
else if (choice3 == "appetizers")
{
food = 150;
}
else { food = 0 ; }
int budget = entertainment + decorations + food;
System.out.println("You have chosen: " + choice1 +
" and " + choice2 + " and " + choice3);
System.out.println("The total cost of this party"
+ " comes out to:" + budget);
}
}

Multiple arrays within a for loop

I've been working on a small bit of code that helps me calculate performance of a movie's Box-Office weekend. I want it to require the
Name of the movie
How much it'll cost to use
How much it's predicted to make that weekend
Then I want it to output all the above information, with the addition of each movie's performance. Well, I'm having issues with it saving multiple String[] values as well as int[] values. I can remove the String lines, and all the int[]'s (both the price and the prediction) work fine, or I can remove the int[]'s and the String[] works fine. Can anyone help me find my errors?
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[15];
int[] moviePrice = new int[15];
int[] moviePrediction = new int[15];
int[] moviePreformance = new int[15];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = console.nextInt();
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = console.nextInt();
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
When you used nextInt() and entered a number you also enterd a new line character, so the next time you called nextLine() this new line character was your next input waiting.
You could fix this by always using nextLine, or by adding a call for nextLine.
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[2];
int[] moviePrice = new int[2];
int[] moviePrediction = new int[2];
int[] moviePreformance = new int[2];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = Integer.parseInt(console.nextLine());
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = Integer.parseInt(console.nextLine());
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
This should fix the issue:
moviePrice[i] = console.nextInt();
console.nextLine();
moviePrediction[i] = console.nextInt();
console.nextLine();
console.nextInt() only reads the number, not the rest of the line, like carriage return.

Array values being set for everything (Java)

In my code below, I am having an issue where I add the customer name to one room, but instead it adds the customer to every room. I can't figure out what in my code the issue is. I have tried removing the procedure but that still produced the same problem.
package test;
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice, custName = "";
int roomNum = 1;
String[] hotel = new String[12];
String[] customer = new String[12];
hotelInitialise(hotel);
custInitialise(customer);
while ( roomNum < hotel.length-1 ) {
for (int i = 0; i < hotel.length-1; i++) {
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("V: " + "View all rooms\n");
choice = input.next().toUpperCase();
if (choice.equals("A")) {
System.out.println("Enter room number(1-10)");
roomNum =input.nextInt();
System.out.println("Enter name for room " + roomNum + " : " ) ;
custName = input.next();
addNewBooking(hotel, custName);
System.out.println(" ");
}
if (choice.equals("V")) {
seeAllRooms(hotel, custName);
}
}
}
}
// When the program loads it will assign all the values of the array as being empty
private static void hotelInitialise( String hotelRef[] ) {
for (int x = 0; x < 11; x++){
hotelRef[x] = "Room " + x + " is empty.";
}
System.out.println( "Welcome to the Summer Tropic Hotel.\n");
}
private static void custInitialise (String custRef[]) {
for (int i = 0; i < 11; i++) {
custRef[i] = ", no customer has occupied this room";
}
}
private static void addNewBooking(String hotel[], String customer) {
for (int x =1; x <11; x++) {
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
System.out.println("Room " + x + " is empty.");
else {
System.out.println("Room " + x + " is occupied by "+ customer);
}
}
}
private static void seeAllRooms(String hotel[], String customer) {
for (int i = 0; i < hotel.length-1; i++) {
int j=0;
String custName = customer;
hotel[j]= custName;
if (hotel[i].equals("Room " + i + " is empty."))
System.out.println("Room " + i + " is empty.");
else {
System.out.println("Room " + i + " is occupied by "+ hotel[j] + ".");
}
}
}
}
In addNewBooking method you have this line:
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
However hotel[x] has a value of "Room x is empty" e.g. hotel[1] is "Room 1 is empty" So the final check is becoming "hotel[x].equals(Room Room x is empty is empty.)" which is never equals to your hotel[x]
You have to change your code to
if (hotel[x].equals("Room " + x + " is empty."))
//do something there like add the booking

Issue using methods and an array

My problem here is displaying the data using another method. I tried both of the methods but there was no output.
I think that objects in the ArrayList are gone when I made them as parameters on both methods or maybe not.
Please kindly help me with this problem of mine. There are still more options to be filled, I also need some help for it.
public class Student {
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
public Student() {
this.IDNumber = IDNum;
this.firstName = fName;
this.middleName = mName;
this.lastName = lName;
this.degree = deg;
this.yearLevel = level;
}
public void setIdNumber(String IDNumber) {
this.IDNumber = IDNumber;
}
public String getIdNumber() {
return IDNumber;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getMiddleName()
{
return middleName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getDegree() {
return degree;
}
public void setYearLevel(int yearLevel) {
this.yearLevel = yearLevel;
}
public int getYearLevel() {
return yearLevel;
}
/* #Override
public String toString(){
return ("ID Number: "+this.getIdNumber()+
"\nName: "+ this.getFirstName()+
" "+ this.getMiddleName()+
" "+ this.getLastName()+
"\nDegree and YearLevel: "+ this.getDegree() +
" - " + this.getYearLevel());
} */
}
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner in = new Scanner(System.in);
int choice = 0;
System.out.print("****STUDENT RECORD SYSTEM****\n\n");
System.out.println("\t MENU ");
System.out.println("[1]ADD STUDENT");
System.out.println("[2]DISPLAY ALL");
System.out.println("[3]DISPLAY SPECIFIC");
System.out.println("[4]UPDATE");
System.out.println("[5]AVERAGE");
System.out.println("[6]EXIT");
System.out.println("?");
choice = in.nextInt();
if (choice == 1) {
options();
}
else if (choice == 2) {
displayAll(student, studentList);
}
else if (choice == 3) {
displaySpecific(student, studentList);
}
}
public static void options() {
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
char ans;
String temp;
int total;
do {
System.out.println("TOTAL: ");
total = in.nextInt();
Student[] student = new Student[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Student();
System.out.print("*********STUDENT INFORMATION*********\n\n");
System.out.println("PRESS ENTER");
in.nextLine();
System.out.print("ID NUMBER: ");
student[index].setIdNumber(in.nextLine());
System.out.print("FIRST NAME: ");
student[index].setFirstName(in.nextLine());
System.out.print("MIDDLE NAME: ");
student[index].setMiddleName(in.nextLine());
System.out.print("LAST NAME: ");
student[index].setLastName(in.nextLine());
System.out.print("DEGREE: ");
student[index].setDegree(in.nextLine());
System.out.print("YEAR LEVEL: ");
student[index].setYearLevel(in.nextInt());
studentList.add(student[index]);
}
System.out
.print("Would you like to enter in a new student (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
} while (ans == 'y');
// SEARCH and DISPLAY SPECIFIC
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
// DISPLAY ALL
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
}
menu();
}
public static void displayAll(Student student,
ArrayList<Student> studentList) {
System.out.printf("STUDENT RECORD");
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
}
}
public static void displaySpecific(Student student,
ArrayList<Student> studentList) {
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
}
}
Move
ArrayList <Student> studentList = new ArrayList <Student>();
from options method to class field.
EDIT:
As you can see, now studentList is not a local variable of
public static void options()
but of the class.
Anyway i edited the args of some methods because you don't need to pass students as argument since now it's a field of the class.
import java.util.ArrayList;
import java.util.Scanner;
public class test {
static ArrayList<Student> studentList = new ArrayList<Student>();
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner in = new Scanner(System.in);
int choice = 0;
System.out.print("****STUDENT RECORD SYSTEM****\n\n");
System.out.println("\t MENU ");
System.out.println("[1]ADD STUDENT");
System.out.println("[2]DISPLAY ALL");
System.out.println("[3]DISPLAY SPECIFIC");
System.out.println("[4]UPDATE");
System.out.println("[5]AVERAGE");
System.out.println("[6]EXIT");
System.out.println("?");
choice = in.nextInt();
if (choice == 1) {
options();
}
else if (choice == 2) {
displayAll();
}
else if (choice == 3) {
displaySpecific(student);// here you should ask to the user what studend he want to show - here it continues to give you error
}
}
public static void options() {
Scanner in = new Scanner(System.in);
char ans;
String temp;
int total;
do {
System.out.println("TOTAL: ");
total = in.nextInt();
Student[] student = new Student[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Student();
System.out.print("*********STUDENT INFORMATION*********\n\n");
System.out.println("PRESS ENTER");
in.nextLine();
System.out.print("ID NUMBER: ");
student[index].setIdNumber(in.nextLine());
System.out.print("FIRST NAME: ");
student[index].setFirstName(in.nextLine());
System.out.print("MIDDLE NAME: ");
student[index].setMiddleName(in.nextLine());
System.out.print("LAST NAME: ");
student[index].setLastName(in.nextLine());
System.out.print("DEGREE: ");
student[index].setDegree(in.nextLine());
System.out.print("YEAR LEVEL: ");
student[index].setYearLevel(in.nextInt());
studentList.add(student[index]);
}
System.out
.print("Would you like to enter in a new student (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
} while (ans == 'y');
// SEARCH and DISPLAY SPECIFIC
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
// DISPLAY ALL
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
}
menu();
}
public static void displayAll() {
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
}
}
public static void displaySpecific(Student student) {
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
}
}

Categories