Using indexOf() method for ArrayList of objects - java

In my program, I have a Vendor class and a Hospital class and store instances of these classes in arraylists called vendors and hospitals. My Vendor class has a string array with names of hospitals that correspond to instances of the Hospital class. I'm trying to find a way to go from the name of the hospital in the string array that is part of the Vendor class, to getting the index value of that hospital for the hospitals arraylist. Apologies if this post doesn't make much sense, I'm very new to coding. Any help would be greatly appreciated.
Edit: Please Ctrl+F with the following to jump to the particular lines of code in question
//check if hospital
Vendor Class
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Vendor {
//static variables are the same for all vendor instances
static int numOfHospitals;
static int numOfAppointments;
//non-static variables are specific to one vendor instance
int priorityNum;
String salespersonName;
String vendorCompanyName;
String [] vendorPicks;
String[] vendorSchedule;
public void printVendorSchedule() {
System.out.println(Arrays.toString(vendorSchedule));
}
public void printVendorPicks () {
System.out.println(Arrays.toString(vendorPicks));
}
public String getVendorSchedule (int appointmentSlot) {
return vendorSchedule [appointmentSlot];
}
public String getVendorPick (int currentHospitalPick) {
return vendorPicks[currentHospitalPick];
}
public boolean checkVendorSchedule (int appointmentSlot) {
return ((vendorSchedule[appointmentSlot]).equals("open"));
}
public void setVendorAppointment (int appointmentSlot, String hospitalName) {
vendorSchedule[appointmentSlot] = hospitalName;
}
public Vendor createNewVendor(int priorityNum, int numOfAppointments, int numOfHospitals, String salespersonName, String vendorCompanyName){
this.priorityNum=priorityNum;
this.salespersonName=salespersonName;
this.vendorCompanyName=vendorCompanyName;
this.vendorPicks = new String[numOfHospitals];
this.vendorSchedule = new String[numOfAppointments];
for (int i = 0; i <numOfAppointments; i++) {
this.vendorSchedule[i] = "open";
}
Scanner input = new Scanner(System.in);
Vendor vendorToAdd = new Vendor();
//loop to add vendor's hospital picks
int counter = 0;
while (counter < numOfHospitals) {
System.out.println("Enter the #" +(counter+1) +" hospital for "+salespersonName+". If there are no more hospitals for this vendor, enter Done.");
String placeHolder = input.nextLine();
if (placeHolder.equalsIgnoreCase("done")) {
break;
}
vendorPicks[counter]=placeHolder;
counter++;
}
return vendorToAdd;
}
}
Hospital Class
package com.company;
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class Hospital {
//static variables here
int numOfAppointments;
int numOfHospitals;
//non-static variables here
String nameHospital;
String nameDirector;
String [] hospitalSchedule;
public void printHospitalSchedule () {
System.out.println(Arrays.toString(hospitalSchedule));
}
public String getHospitalSchedule(int appointmentSlot) {
return hospitalSchedule[appointmentSlot];
}
public boolean checkHospitalSchedule (int appointmentSlot) {
return ((hospitalSchedule[appointmentSlot]).equals("open"));
}
public void setHospitalAppointment (int appointmentSlot, String nameVendor) {
hospitalSchedule[appointmentSlot] = nameVendor;
}
public Hospital createNewHospital(int numOfAppointments, int numOfHospitals,
String nameHospital, String nameDirector) {
Hospital h1 = new Hospital();
this.nameDirector=nameDirector;
this.nameHospital=nameHospital;
this.hospitalSchedule = new String[numOfAppointments];
for (int i=0; i < numOfAppointments; i++) {
hospitalSchedule[i] = "open";
}
return h1;
}
}
Main Class
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Inputting #vendors, #hospitals
int vendorCounter=1;
System.out.println("Enter the total number of appointment slots.");
Scanner myScanner = new Scanner(System.in);
int numOfAppointments = Integer.parseInt(myScanner.nextLine());
System.out.println("Enter the total number of hospitals in the draft.");
int numOfHospitals = Integer.parseInt(myScanner.nextLine());
ArrayList<Hospital> hospitals = new ArrayList<Hospital>();
//creating hospitals
int hospitalCounter = 1;
while (hospitalCounter <=numOfHospitals) {
System.out.println("Enter the name of hospital #" + hospitalCounter);
String currentHospitalName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
System.out.println("Enter the director's name for " + currentHospitalName + ".");
String currentDirectorName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
Hospital h1 = new Hospital();
h1.createNewHospital(numOfAppointments, numOfHospitals, currentHospitalName, currentDirectorName);
hospitals.add(h1);
hospitalCounter++;
}
//creating vendors
ArrayList<Vendor> vendors = new ArrayList<Vendor>();
Scanner myInput = new Scanner(System.in);
while (vendorCounter != 2000){
System.out.println("Are you entering a new vendor? Enter Yes or No");
String isAddingNewVendor;
isAddingNewVendor= myScanner.nextLine();
if (isAddingNewVendor.equalsIgnoreCase("yes"))
{
System.out.println("Enter the name of the salesperson.");
String salespersonName = myInput.nextLine();
System.out.println("Enter the company name for "+salespersonName+".");
String vendorCompanyName = myInput.nextLine();
Vendor v1 = new Vendor();
v1.createNewVendor(vendorCounter, numOfAppointments, numOfHospitals,salespersonName,vendorCompanyName);
vendors.add(v1);
vendorCounter++;
}
else vendorCounter = 2000;
}
/* System.out.println(vendors.get(0).vendorCompanyName);
System.out.println(hospitals.get(0).nameHospital);
System.out.println(vendors.get(0));
vendors.get(0).printVendorSchedule();
vendors.get(0).printVendorPicks();
hospitals.get(0).printHospitalSchedule();
if (vendors.get(0).checkVendorSchedule(0)) {
System.out.println ("This appointment slot is open for the vendor.");
}
if (hospitals.get(0).checkHospitalSchedule(0)) {
System.out.println("This appointment slot is open for the hospital.");
}*/
for (int i = 0; i < numOfHospitals; i++) {
System.out.println("Information for hospital #" + i);
System.out.println("Hospital name: " +hospitals.get(i).nameHospital);
System.out.println("Director's name: " + hospitals.get(i).nameDirector);
System.out.println("The hospital's initial schedule:");
hospitals.get(i).printHospitalSchedule();
}
for (int i = 0; i < vendors.size(); i++) {
System.out.println("Information for vendor #" + i);
System.out.println("Salesperson's name: "+vendors.get(i).salespersonName);
System.out.println("Company name: " + vendors.get(i).vendorCompanyName);
System.out.println("The vendor's hospital choices:");
vendors.get(i).printVendorPicks();
System.out.println("The vendor's initial schedule:");
vendors.get(i).printVendorSchedule();
}
//draft loop logic
int draftRound = 1;
while (draftRound <= numOfAppointments) {
if (draftRound % 2 == 1) {
//insert code for odd-numbered draft rounds here.
//these rounds should start with picker 1, then 2, 3, etc.
int currentVendor = 0; //starts this round with the first vendor
while (currentVendor < vendors.size()){
//this while loop continues running through a single draft round until all vendors get a pick
int currentAppointmentSlot = 0;
int currentVendorPickSlot=0;
while (currentVendorPickSlot < numOfHospitals) { //this loops through a single vendor until all appointments checked or appt assigned
//check if hospital and vendor are both open
String currentHospital = vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
System.out.println(currentHospital);
int currentHospitalsIndex = hospitals.indexOf(currentHospital); //indexof is returning -1 creating the exceptionoutofbounds
System.out.println("Current hospital index:"+ currentHospitalsIndex);
if ( hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
currentAppointmentSlot++;
}
else {
vendors.get(currentVendor).setVendorAppointment(currentVendorPickSlot, hospitals.get(currentHospitalsIndex).nameHospital);
hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentVendorPickSlot, vendors.get(currentVendor).salespersonName);
break; // does this break the loop?
}
}
currentVendor++;
}
draftRound++;
}
if (draftRound % 2 == 0) {
//insert code for even-numbered draft rounds here.
//these rounds should start with the last picker and go down by 1 each turn until 1st picker.
int currentVendor = vendors.size()-1; //starts this draft round with the last vendor
while (currentVendor >= 0) {
//this while loop continues running through a single draft round until all vendors get a pick
int currentAppointmentSlot = 0; //looping through the hospital choices for a single vendor
int currentVendorPickSlot=0;
while (currentVendorPickSlot < numOfHospitals) {
//check if hospital and vendor are both open
String currentHospital = vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
int currentHospitalsIndex = hospitals.indexOf(currentHospital);
if (hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
currentAppointmentSlot++;
//continuing the loop if the appointment slot doesn't work
}
else {
vendors.get(currentVendor).setVendorAppointment(currentAppointmentSlot, hospitals.get(currentHospitalsIndex).nameHospital);
hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentAppointmentSlot, vendors.get(currentVendor).salespersonName);
currentVendor++;
break; // does this break the loop?
}
}
currentVendor++;
}
draftRound++;
}
else break;
}
for (int i = 0; i < numOfHospitals; i++) {
System.out.println("Information for hospital #" + i);
System.out.println("Hospital name: " +hospitals.get(i).nameHospital);
System.out.println("Director's name: " + hospitals.get(i).nameDirector);
System.out.println("The hospital's final schedule:");
hospitals.get(i).printHospitalSchedule();
}
for (int i = 0; i < vendors.size(); i++) {
System.out.println("Information for vendor #" + i);
System.out.println("Salesperson's name: "+vendors.get(i).salespersonName);
System.out.println("Company name: " + vendors.get(i).vendorCompanyName);
System.out.println("The vendor's final schedule:");
vendors.get(i).printVendorSchedule();
}
}}

First using stream we will Iterate through hospitals list,
find out the hospital from the list whose name equals currentHospital name, take out the first result using findFirst.
Since the result may be or may not be available it returns Optional.
So on Optional, we will say if it's (the hospital object which we were looking for) present we will get the hospital out of it using the get method
Optional<Hospital> result = hospitals.stream().filter(h -> h.nameHospital.equals(currentHospital)).findFirst();
if(result.isPresent()){
Hospital hospital = result.get();
}

Related

How do I make a class to dynamic check different objects variable?

I'm new to Java, and i'm trying to create an automatic working shift schedule.
I want the code to mix four different employees to handle a morning shift and afternoon shift every work day.
I have made some code that just pick a random employee into a shift:
import java.util.Arrays;
import java.util.Random;
public class CreateNewShift {
public static void main(String[] args) {
int startWeek = 30; //Which week would start from?
int endWeek = 32; //which week will you end on?
generateShift(startWeek, endWeek);
}
private static void generateShift(int startWeek, int endWeek) {
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
for (int x = 0; x <= (endWeek - startWeek); x++) { //This is counting the number of weeks
System.out.println("\nWeek: " + (startWeek+x));
for (int i = 1; i <= 5; i++) { //this is finding the next working shift day
morningShift = p.chooseRandomEmployee(Employees);
afternoonShift = p.chooseRandomEmployee(Employees);
if (i == 1) {
System.out.println("Mon: " + morningShift + " + " + afternoonShift);
}
else if (i == 2) {
System.out.println("Tue: " + morningShift + " + " + afternoonShift);
}
else if (i == 3) {
System.out.println("Wed: " + morningShift + " + " + afternoonShift);
}
else if (i == 4) {
System.out.println("Thu: " + morningShift + " + " + afternoonShift);
}
else {
System.out.println("Fri: " + morningShift + " + " + afternoonShift);
}
}
}
}
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
However, I now want the code to handle more restictions.
So i'm currently trying to add the option for the employees to choose some specific days that they dont want to have a shift. I have done this by adding this code to the Employee class:
public class Employee {
boolean monShift = true;
boolean tueShift = true;
boolean wedShift = true;
boolean thuShift = true;
boolean friShift = true;
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
And then i had tried to create new objects in my main class:
private static void generateShift(int startWeek, int endWeek) {
Employee Employee1 = new Employee("Employee1");
Employee Employee2 = new Employee("Employee2");
Employee Employee3 = new Employee("Employee3");
Employee Employee4 = new Employee("Employee4");
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
....
Quetions:
How can I improve my code in the Employee class to do a check if the random chosen employee have
monShift = true;
I have tried something like this, but i know it will not work, (and does not work either):
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
**if (("Employee" + randomNumber).monShift == false) {**
// Go back and try find a new random employee
}
else {
return Employees[randomNumber];
}
}
}
So i need a way to make my code dynamic to know which object (employee) it has to check if they are available that specific day or not.
Feel free to ask for a deepening if my question is not clear.
Since this i my first question on this forum, I also appriciate feedback if my question and thoughts are too long, or any other comments.
I dont think that putting the chooseRandomEmployee() function inside the Employee object is a good idea beacuse is not a part of the employee, is not an "action" of it. I think you shiudl put it outside but I want to respect your decision so shoudl check the do while loop.
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
int randomNumber;
do {
//Generate a new random number
Random r = new Random();
randomNumber = r.nextInt(Employees.length);
//The line under is the same that saying "If monSift == false return to
//the beginning and start again generating a new number"
} while ("Employee" + randomNumber).monShift == false);
return Employees[randomNumber];
}
}

Loop with get and set?

I'm writing a program with two classes, one person class and one main. The person class use get and set for six people and then the main class ask for the names and then show the user the six names (in my example it only shows four). Is it possible to use a loop for this? I know I could use a list for this but it's for school and they want us to use constructors, set and get in the first week or so. The code now looks like this. Is this even possible with an example like this or do I need to use a list or an array?
PersonClass.java
public class PersonClass {
private String namn;
public void setNamn(String namn) {
this.namn = namn;
}
public String getNamn() {
return namn;
}
}
MainClass.java
import javax.swing.*;
public class MainClass {
public static void main(String[] args) {
PersonClass person1 = new PersonClass();
PersonClass person2 = new PersonClass();
PersonClass person3 = new PersonClass();
PersonClass person4 = new PersonClass();
String namn1 = JOptionPane.showInputDialog("Enter full name for person 1!");
person1.setNamn(namn1);
String namn2 = JOptionPane.showInputDialog("Enter full name for person 2!");
person2.setNamn(namn2);
String namn3 = JOptionPane.showInputDialog("Enter full name for person 3!");
person3.setNamn(namn3);
String namn4 = JOptionPane.showInputDialog("Enter full name for person 4!");
person3.setNamn(namn4);
JOptionPane.showMessageDialog(null, "Person 1: " + person1.getNamn() +
"\nPerson 2: " + person2.getNamn() + "\nPerson 3: " + person3.getNamn() +
"\nPerson 4: " + person4.getNamn());
}
}
I'm personally a fan of Lists as well, but Arrays are just as good of an option. I build the output as it goes with a little String.format help.
List<PersonClass> persons = new ArrayList<PersonClass>();
String output = "";
for(int i = 1; i <= 6; i++) {
String name = JOptionPane.showInputDialog(String.format("Enter full name for person %d!", i));
PersonClass person = new PersonClass();
person.setNamn(name);
persons.add(person);
output += String.format("Person %d: %s\n",i, person.getNamn());
}
JOptionPane.showMessageDialog(null, output);
Hello because of your tone when suggesting arrays I take it that you are not comfortable with the concept yet, but maybe talk with your teacher about this and about the answers you get here!
PersonClass[] personArray = {person1, person2, person3, person4};
for (int i = 0; i < personArray.length; i++)
{
// (i + 1) because our array starts at 0, but it's the 0 + 1th person
String msg = "Enter full name for person" + (i + 1);
personArray[i].setName(JOptionPane.showInputDialog(msg));
}
List<PersonClass> people = new ArrayList<PersonClass>;
for (int i = 0; i < 6; i++) { // set i to number of required people
PersonClass person = new PersonClass();
person.setNamn(JOptionPane.showInputDialog("Enter full name for person " + (i + 1) +"!");
people.add(person);
JOptionPane.showMessageDialog(null, person.getNamn());
}
people will contain all the new PersonClass you created.
PersonClass[] persons = new PersonClass[4];
for(int i = 0; i < persons.length; i++){
persons[i] = new PersonClass();
persons[i].setNamn(JOptionPane.showInputDialog("Enter full name for person " + (i+1));
}
If dialog will be closed - there will be null returned.
One way to do this with a loop would be to make your main class like this. See comments:
import java.util.ArrayList;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
ArrayList<PersonClass> people = new ArrayList<PersonClass>();
int index=5;
//Loop that will ask for 6 names
for(int ii=0; ii<=index; ii++){
//create person object
PersonClass person = new PersonClass();
//get/set the name
person.setNamn(JOptionPane.showInputDialog("Enter full name for person " + ii + " !"));
//save name in arraylist
people.add(person);
}
int count = 1;
//will output names via a loop
for(PersonClass person : people){
if(person.getNamn() != null){
JOptionPane.showMessageDialog(null, "Person " + count + " name: " + person.getNamn());
}
count++;
}
}
}
If it were me, I'd create a custom constructor for the PersonClass, which sets the namn on construction:
public class PersonClass {
private String namn;
//Custom constructor using a setter
public PersonClass(String namn){
this.setNamn(namn);
}
public void setNamn(String namn) {
this.namn = namn;
}
public String getNamn() {
return namn;
}
}
Then I would do this in my MainClass:
import java.util.ArrayList;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
ArrayList<PersonClass> people = new ArrayList<PersonClass>();
int index=5;
//Loop that will ask for 6 names
for(int ii=0; ii<=index; ii++){
//create, set, and add name to list
people.add(new PersonClass(JOptionPane.showInputDialog("Enter full name for person " + ii + " !")));
}
int count = 1;
for(PersonClass person : people){
if(person.getNamn() != null){
JOptionPane.showMessageDialog(null, "Person " + count + " name: " + person.getNamn());
}
count++;
}
}
}

Need help using an ArrayList

It seems that 20 regiments were in a continuous process of formation. The first had 1000 men, the second had 950, the third 900, and so on down to the twentieth regiment, which garrisoned only 50. During each week, 100 men were added to each regiment, and at week's end, the largest regiment was sent off to the front.This lasted for a total of 20 weeks.
For this program I have already managed to print out the original number of men for each regiment. But I am having difficult adding 100 men to each regiment.The adding men must be a method in the army class. I am getting the regiment objects using a .txt file. All this files contains is the names of regiments numbered 1-20.
I currently have no errors my only problem is that I do not know how to add men to my regiment. I have to use the addMen method in the army class which I currently have blank.
public class Regiment {
private String name; //name of regiment
private int regNumber; //regiment number
private int men; // regiment men
public Regiment(int regNumber, String name, int men) {
this.name = name;
this.regNumber = regNumber;
this.men = men;
}
public String getName() {
return name;
}
public int getregNumber() {
return regNumber;
}
public int getMen() {
return men;
}
public int addMen2(int RegNumber) {
int men = 1050 - (regNumber * 50);
return men;
}
}
ArmyDataList:
class ArmyDataList {
public ArrayList<Regiment> list;
public ArmyDataList() {
list = new ArrayList<Regiment>();
}
public void AddToList(Regiment current) {
list.add(current);
}
public void RemoveFromList(Regiment current) {
list.remove(current);
}
public Regiment getLargest() {
if (list.isEmpty()) {
return null;
}
Regiment Reg1 = list.get(0);
for (int i = 1; i < list.size(); i++) {
Regiment current = list.get(i); // get next regiment
// is current regiment > largest
if (current.getMen() > Reg1.getMen()) {
Reg1 = current;
}
}
return Reg1;
}
public void addMen() {
}
public String toString() {
String out
= String.format("%28s%12s%n", "Regiments", " Men")
+ String.format("%12s%n", "Number")
+ String.format("%12s%16s%14s%n", "=======", "===============",
"=========");
for (int i = 0; i < list.size(); i++) {
Regiment regim = list.get(i);
int regNumber = regim.getregNumber();
String name = regim.getName();
int men = regim.addMen2(regNumber);
out = out + String.format("%12s", regNumber)
+ String.format("%16s", name)
+ String.format("%10s", men)
+ "\n";
}
return out + "\n";
}
}
RegimentTest:
public class RegimentTest {
public static void main(String[] args) throws IOException
{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}
System.out.println(army.toString());
}
Add a setMen(int numberOfMen) method to your Regiment class. Then in your addMen() method, you can do something like this:
public void addMen(){
for(Regiment r : list){ //iterate through the list of regiments
r.setMen(r.getMen() + 100); //add 100 men to each regiment
}
}
The setMen method would look like this:
public void setMen(int numberOfMen){
men = numberOfMen;
}
There is another issue with your toString method, where the regiment's addMen2 method is called - right now you're just printing the number, not initializing the number of men. In the constructor for your Regiment class, replace the line
this.men = men;
with
this.men = addMen2(regNumber);
Then in your toString method, replace
int men = regim.addMen2(regNumber);
with
int men = regim.getMen();
Here is what your main should look like:
public static void main(String[] args) throws IOException{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line);
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder);
}
System.out.println(army.toString()); //print out the initial # of men
for(int i = 0; i < 20; i++)
army.addMen();
System.out.println(army.toString()); //print the final # of men
}
in Regiment get rid of method addMen2, and replace it with
public void addMen(int men) {
this.men +=men;
}
then in your army you could have method
public void addMen(int men) {
for(Regiment regiment : list){
regiment.addMen(men);
}
}
that will be simplest solution to add 100 men to each regiment,
other thing is, your toString is bit nasty, regiment should know how meny soldiers it ghas, you shouldnt need additional method to calculate it (reason why i recommend you to trash addMen2 method)
to initiate your Regiment, use constructor. You want to have regiments in sizes 1000, 1950, 1900 etc, do it when you are creating them
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 1050 - (regNumber * 50);
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}

Displaying Pictures in Array

In drjava I'm trying to acquire pictures in hold them in the array, and then print out a description of each picture. Right now everything compiles but when I run it has me choose the folder that contains the pictures and then the interactions pane disappears. The code I have so far is in my House app for acquiring the pictures and printing the descriptions is
SSCCEE
HOUSE.java
public class House
{
String owner;
public final static int CAPACITY = 6;
Picture[ ] pictArray = new Picture[CAPACITY];
public House(String pString)
{
this.owner = pString;
}
public String toString()
{
return("The House owned by " + this.owner);
}
public void acquire( int position, Picture pRef )
{
this.pictArray[ position ] = pRef;
}
public void printPictures()
{
for (int i=0; i < this.pictArray.length;i++)
{
System.out.print("The Picture in position " + i + " is ");
System.out.println( this.pictArray[ i ]);
}
}
public void swap( int positionA, int positionB )
{
System.out.println("NOTHING DONE. THIS IS JUST A swap's STUB");
}
public void showOff()
{
System.out.println("NOTHING DONE. THIS IS JUST showOff's STUB");
}
}
Test.java
import java.util.Scanner;
public class Test
{
public static void main(String[] a)
{
House h = new House("Justin Chaisetseree");
Scanner sc = new Scanner(System.in);
FileChooser.pickMediaPath();
for( int i = 0; i < 6; i++)
{
h.acquire(i,new Picture(FileChooser.pickAFile()));
}
h.printPictures();
h.showOff();
Boolean done = false;
while( ! done )
{
System.out.println("Which two do you want to swap?");
System.out.print("Type in two numbers from 0 to ");
System.out.print( 5 );
System.out.println(" or two -1s to stop.");
int userInput1 = sc.nextInt();
int userInput2 = sc.nextInt();
if( userInput1 < 0 || userInput2 < 0)
{
done = true;
}
else
{
h.swap( userInput1, userInput2 );
}
}
h.showOff();
}
}

Infinite while loop in java, not reading in sentinel

I've had this problem throughout multiple programs, but I can't remember how I fixed it last time. In the second while loop in my body, the second sentinel value is never read in for some reason. I've been trying to fix it for a while now, thought I might see if anyone had any clue.
import java.text.DecimalFormat; // imports the decimal format
public class Car {
// Makes three instance variables.
private String make;
private int year;
private double price;
// Makes the an object that formats doubles.
public static DecimalFormat twoDecPl = new DecimalFormat("$0.00");
// Constructor that assigns the instance variables
// to the values that the user made.
public Car(String carMake,int carYear, double carPrice)
{
make = carMake;
year = carYear;
price = carPrice;
}
// Retrieves variable make.
public String getMake()
{
return make;
}
// Retrieves variable year.
public int getYear()
{
return year;
}
// Retrieves variable price.
public double getPrice()
{
return price;
}
// Checks if two objects are equal.
public boolean equals(Car c1, Car c2)
{
boolean b = false;
if(c1.getMake().equals(c2.getMake()) && c1.getPrice() == c2.getPrice() &&
c1.getYear() == c2.getYear())
{
b = true;
return b;
}
else
{
return b;
}
}
// Turns the object into a readable string.
public String toString()
{
return "Description of car:" +
"\n Make : " + make +
"\n Year : " + year +
"\n Price: " + twoDecPl.format(price);
}
}
import java.util.Scanner; // imports a scanner
public class CarSearch {
public static void main(String[] args)
{
// initializes all variables
Scanner scan = new Scanner(System.in);
final int SIZE_ARR = 30;
Car[] carArr = new Car[SIZE_ARR];
final String SENT = "EndDatabase";
String carMake = "";
int carYear = 0;
double carPrice = 0;
int count = 0;
int pos = 0;
final String SECSENT = "EndSearchKeys";
final boolean DEBUG_SW = true;
// Loop that goes through the first list of values.
// It then stores the values in an array, then uses the
// values to make an object.
while(scan.hasNext())
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car car1 = new Car(carMake, carYear, carPrice);
carArr[count] = car1;
count++;
}
// Calls the method debugSwitch to show the debug information.
debugSwitch(carArr, DEBUG_SW, count);
// Calls the method printData to print the database.
printData(carArr, count);
// Loops through the second group of values and stores them in key.
// Then, it searches for a match in the database.
**while(scan.hasNext())**
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SECSENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car key = new Car(carMake, carYear, carPrice);
// Stores the output of seqSearch in pos.
// If the debug switch is on, then it prints these statements.
if(DEBUG_SW == true)
{
System.out.println("Search, make = " + key.getMake());
System.out.println("Search, year = " + key.getYear());
System.out.println("Search, price = " + key.getPrice());
}
System.out.println("key =");
System.out.println(key);
pos = seqSearch(carArr, count, key);
if(pos != -1)
{
System.out.println("This vehicle was found at index = " + pos);
}
else
{
System.out.println("This vehicle was not found in the database.");
}
}
}
// This method prints the database of cars.
private static void printData(Car[] carArr, int count)
{
for(int i = 0; i < count; i++)
{
System.out.println("Description of car:");
System.out.println(carArr[i]);
}
}
// Searches for a match in the database.
private static int seqSearch(Car[] carArr, int count, Car key)
{
for(int i = 0; i < count; i++)
{
boolean b = key.equals(key, carArr[i]);
if(b == true)
{
return i;
}
}
return -1;
}
// Prints debug statements if DEBUG_SW is set to true.
public static void debugSwitch(Car[] carArr, boolean DEBUG_SW, int count)
{
if(DEBUG_SW == true)
{
for(int i = 0; i < count; i++)
{
System.out.println("DB make = " + carArr[i].getMake());
System.out.println("DB year = " + carArr[i].getYear());
System.out.println("DB price = " + carArr[i].getPrice());
}
}
}
}
I think this is your problem, but I might be wrong:
Inside your while loop, you have these calls:
next()
nextInt()
nextDouble()
The problem is that the last call (nextDouble), will not eat the newline. So to fix this issue, you should add an extra nextLine() call at the end of the two loops.
What happens is that the next time you call next(), it will return the newline, instead of the CarMake-thing.

Categories