Searching Arrays using Recursion? - java

Does someone know how to use recursion to search for Arrays of objects inside other Arrays?
Carpetas = Folders Archivos = Files Nombre = Name Tamaño = Size
Edit: Translated a few souts for furthe clarity.
The point of this exercise is to create ArrayLists inside of other ArrayLists, simulating real folders and Files used in computers. The code below is what I have done so far. Help!
public class Carpetas {
private String nombre;
private int tamaño;
ArrayList <Carpetas> Crp;
ArrayList <Archivo> Arc;
public Carpetas(String nombre, int tamaño){
this.nombre = nombre;
this.tamaño = tamaño;
Crp = null;
Arc = null;
}
public ArrayList<Carpetas> getCrp() {
return Crp;
}
public void setCrp(Carpetas nueva_carpeta) {
if(Crp == null){
Crp = new ArrayList<>();
Crp.add(nueva_carpeta);
}else{
Crp.add(nueva_carpeta);
}
}
public ArrayList<Archivo> getArc() {
return Arc;
}
public void setArc(Archivo nuevo_archivo ) {
if(Arc == null)
{
Arc = new ArrayList<>();
Arc.add(nuevo_archivo);
}else
{
Arc.add(nuevo_archivo);
}
}
public static void menu(int a){
Scanner input = new Scanner(System.in);
System.out.println("1 - Search folder: ");
System.out.println("2 - Type in/Create Folder: ");
System.out.println("3 - Type in/Create Files: ");
System.out.println("Typ in the menu option: ");
a = input.nextInt();
switch(a){
case 1:
break;
}
}
public String searchCarpeta(String nombre, int y){
if(y == Crp.size()){
return "File not found.";
}
if(nombre.equals(Crp.get(y).getNombre())){
return Crp.get(y).getNombre();
}
else{
return searchCarpeta(nombre, y++);
}
}
public void createCarpetas(String nombre, int y){
if(nombre.equals(Crp.get(y).getNombre())){
System.out.println("Folder already exists.");
return;
}
else{
Crp.add(new Carpetas(nombre, 0));
System.out.println("Folder added successfully!");
}
}
public void createArchivo(String nombre, String archivo, int y){
}
public String getNombre() {
return nombre;
}
public int getTamaño() {
return tamaño;
}
public void setTamaño(int tamaño) {
this.tamaño = tamaño;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Carpetas crp = null;
System.out.println("Type the name of the file: ");
String nombre = input.next();
crp.Crp.add(new Carpetas(nombre, 0));
}
}

Related

How to insert value from user defined datatypes to object in java?

I'm creating an object of type Lightmode, which is a class.
There's also a Smartlamp class which is having a variable of custom data of type Lighmodes and I want to show my defined data type value over there.
I'm trying to create an object and then insert a string against my Lightmode data type which is showing error. I want to print like this:
Name:  lamp1 
Location: 3.1 
Switched On:  false 
Mode:  STANDARD 
Here mode is lightmode datatype and I'm getting a problem over it.
...
public class LightModes
{
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}...
...package smart.home.app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size,mode;
int displayindex=1;
String name;
double location,temperature;
boolean status=false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size=in.nextInt();
// TODO code application logic here
SmartLamp[] smartLamp=new SmartLamp[size];// creating an array object of smartdevice class
//
for(int j=0;j<size;j++)
{
System.out.println("Enter Lamp name.");
name=input.readLine();
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation=new Scanner(System.in);
location=devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode=new Scanner(System.in);
mode=lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus=new Scanner(System.in);
int currentstatus=devicestatus.nextInt();
if(currentstatus==1)
{
status=true;
}
else if(currentstatus==0)
{
status=false;
}
LightModes light = null;
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}...
...public class SmartLamp extends SmartDevice{
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{"+"\nName."+getName()+"\nLocation."
+getLocation() + "\nSwitchedOn."+isSwitchedOn()+
"\nMode=" + getLightModes() + '}';
}
}...
I downloaded your code and added the missing class SmartDevice. Your code contains two compiler errors.
name = input.readLine();
This line throws java.io.IOException which is an unchecked exception and hence must be handled by your code. There are several ways to do this, one of which is to add throws IOException to method main() in class Step5.
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
The first argument to SmartLamp constructor is an instance of class LightModes but you are passing a String. You need to create an instance of LightModes.
Here is your code with my modifications that get rid of the two compiler errors.
(Note: The below code includes my guessed implementation of class SmartDevice.)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException { // Change here.
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size, mode;
int displayindex = 1;
String name;
double location, temperature;
boolean status = false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size = in.nextInt();
SmartLamp[] smartLamp = new SmartLamp[size];// creating an array object of smartdevice class
for (int j = 0; j < size; j++) {
System.out.println("Enter Lamp name.");
name = input.readLine(); // throws java.io.IOException
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation = new Scanner(System.in);
location = devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode = new Scanner(System.in);
mode = lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus = new Scanner(System.in);
int currentstatus = devicestatus.nextInt();
if (currentstatus == 1) {
status = true;
}
else if (currentstatus == 0) {
status = false;
}
LightModes light = new LightModes(); // Change here.
light.setNIGHT_MODE(light.getNIGHT_MODE()); // Change here.
smartLamp[j] = new SmartLamp(light, name, location, status); // Change here.
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}
class LightModes {
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String name, double location, boolean switchedOn) {
this.name = name;
this.location = location;
this.switchedOn = switchedOn;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean isSwitchedOn() {
return switchedOn;
}
}
class SmartLamp extends SmartDevice {
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{" + "\nName." + getName() + "\nLocation." + getLocation()
+ "\nSwitchedOn." + isSwitchedOn() + "\nMode=" + getLightModes() + '}';
}
}

How to get user input and store in custom object? JAVA

Henlo,
Basically what im trying to do is get user inputs and store in a custom object but I have no idea on how to go about it. I have created a loadDataFromConfig() method? that works fine when creating the object SmartHome app = new SmartHome(loadDataFromConfig());.
But I am completely stumped on how to get user inputs and store them in this format: dev[0] = new SmartDevice("device 1",1.3,true);.
All the code that is meant to run should be inside the main method in Step1.java
Here are the 3 classes used for the code (ignore comments they are just notes for me):
package SmartHomeApp;
public class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
//YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {name = value;}
public void setLocation(double value) {location = value;}
public void setSwitchedOn(boolean value) {switchedOn = value;}
public String getName() {return name;}
public double getLocation() {return location;}
public boolean getSwitchedOn() {return switchedOn;}
}
package SmartHomeApp;
public class SmartHome
{
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {return smrtDev.length;}
// can't do toString() for some reason??
public void ToString() {
for(int i=0; i<size();i++)
{
if(smrtDev[i] != null ){
System.out.println("----------");
System.out.println("-DEVICE "+(i+1)+"-");
System.out.println("----------");
System.out.println("Name: "+smrtDev[i].getName());
System.out.println("Location: "+smrtDev[i].getLocation());
System.out.println("Switched On: "+smrtDev[i].getSwitchedOn());
}
}
}
}
package SmartHomeApp;
import java.util.*;
public class Step1 {
public static void main(String args[]) {
SmartHome app = new SmartHome(loadDataFromConfig());
app.ToString();
}
public static SmartDevice[] loadDataFromConfig()
{
SmartDevice[] dev = new SmartDevice[20];
dev[0] = new SmartDevice("device 1",1.3,true);
dev[1] = new SmartDevice("device 2",2.3,false);
dev[2] = new SmartDevice("device 3",3.3,true);
dev[4] = new SmartDevice("device 5",4.3,false);
dev[19] = new SmartDevice("device 20",5.3,false);
return dev;
}
}
Some of the improvements required in your code are as follows:
Follow Java naming conventions e.g. ToString() should be toString(). Check this to learn more about toString(). Most of the IDEs (e.g. eclipse) provide a feature to generate toString() method on click of a button. Whatever way (either manual or with the help of your IDE) you generate it, it must return a String.
You should do away with using next(), nextInt(), nextDouble() etc. and use nextLine() instead. Check this to learn more it. To give you an idea what problems next(), nextDouble() can cause, try entering a name with a space e.g.
Enter size:
2
Name:
Light Amplification by Stimulated Emission of Radiation
Location:
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.nextDouble(Scanner.java:2564)
at Main.main(Main.java:83)
Given below is a sample code incorporating the improvements mentioned above:
import java.util.Scanner;
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
// YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {
name = value;
}
public void setLocation(double value) {
location = value;
}
public void setSwitchedOn(boolean value) {
switchedOn = value;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean getSwitchedOn() {
return switchedOn;
}
#Override
public String toString() {
return "SmartDevice [name=" + name + ", location=" + location + ", switchedOn=" + switchedOn + "]";
}
}
class SmartHome {
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {
return smrtDev.length;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (SmartDevice smartDevice : smrtDev) {
sb.append(smartDevice.toString()).append("\n");
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int size = getPositiveInt(myObj, "Enter size: ");
SmartDevice[] newList = new SmartDevice[size];
for (int i = 0; i < newList.length; i++) {
System.out.print("Name: ");
String x = myObj.nextLine();
double y = getFloatingPointNumber(myObj, "Location: ");
boolean z = getBoolean(myObj, "Is on?: ");
newList[i] = new SmartDevice(x, y, z);
}
SmartHome newDevice = new SmartHome(newList);
System.out.println(newDevice);
}
static int getPositiveInt(Scanner in, String message) {
boolean valid;
int n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Integer.parseInt(in.nextLine());
if (n <= 0) {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
System.out.println("This in not a positive integer. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static double getFloatingPointNumber(Scanner in, String message) {
boolean valid;
double n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Double.parseDouble(in.nextLine());
} catch (NumberFormatException | NullPointerException e) {
System.out.println("This in not a number. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static boolean getBoolean(Scanner in, String message) {
System.out.print(message);
return Boolean.parseBoolean(in.nextLine());
}
}
A sample run:
Enter size: x
This in not a positive integer. Please try again.
Enter size: -2
This in not a positive integer. Please try again.
Enter size: 10.5
This in not a positive integer. Please try again.
Enter size: 2
Name: Light Amplification by Stimulated Emission of Radiation
Location: 123.456
Is on?: true
Name: Vacuum Diode
Location: 234.567
Is on?: no
SmartDevice [name=Light Amplification by Stimulated Emission of Radiation, location=123.456, switchedOn=true]
SmartDevice [name=Vacuum Diode, location=234.567, switchedOn=false]
So as suggested I tried to do the following:
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter size: ");
int size = myObj.nextInt();
SmartDevice[] newList = new SmartDevice[size];
for(int i =0; i<newList.length;i++) {
System.out.println("Name: ");
String x = myObj.next();
System.out.println("Location: ");
double y = myObj.nextDouble();
System.out.println("Is on?: ");
boolean z = myObj.nextBoolean();
newList[i] = new SmartDevice(x,y,z);
}
SmartHome newDevice = new SmartHome(newList);
newDevice.ToString();
}
Got it working but not sure if this is the most efficient way to do so??

EDIT (judge harshly): My display() method won't display and I'm not sure why

I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.
The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.
I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.
My constructor looks like this:
==================================================
public class Salesperson
{
private String salesName;
private int salesID;
private double annualSales;
public Salesperson(String salesName, int salesIDNum, double yearlySales)
{
this.salesName = salesName;
salesID = salesIDNum;
annualSales = yearlySales;
}
public String getSalesName()
{
return salesName;
}
public void setSalesName(String salesName)
{
this.salesName = salesName;
}
public double getSalesID()
{
return salesID;
}
public void setSalesID(int salesIDNum)
{
salesID = salesIDNum;
}
public double getAnnualSales()
{
return annualSales;
}
public void setAnnualSales(double yearlySales)
{
annualSales = yearlySales;
}
#Override
public String toString()
{
return String.format("%s-%-10s%-10.2f", salesName,
salesID, annualSales);
}
}
And my code for application looks like this:
import java.util.Arrays;
import java.util.Scanner;
public class CreateSalesperson
{
private static final Scanner USER_INPUT = new Scanner(System.in);
private static final int UPPER_SIZE_LIMIT = 20;
private static final int LOWER_SIZE_LIMIT = 0;
private static Salesperson[] salesStaffInDatabase = new
Salesperson[20];
private static int numOfSalesPpl = 0;
private static boolean loop = true;
public static void main(String[] args)
{
String selection;
selection = programMenu();
String response;
while(loop)
switch(selection)
{
case "A":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "a":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "C":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "c":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "E":
System.out.print("You Are Leaving Database");
loop = false;
break;
case "e":
System.out.print("You Are Leaving Database");
loop = false;
break;
}
}
public static void changeRecord()
{
String idNum;
String salesName;
double salesAmount;
String response;
System.out.print("Enter Sales ID: ");
idNum = USER_INPUT.nextLine();
if(isValidID(idNum))
{
int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
System.out.println(salesStaffInDatabase[searchResult]);
}
else
{
System.out.println("Invalid Sales ID");
}
}
public static boolean isValidID(String idNum)
{
boolean isValid= false;
for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
{
if(salesStaffInDatabase[val].equals(idNum))
{
isValid = true;
}
}
return isValid;
}
public static void addRecord()
{
int idNum;
String salesName;
double salesAmount;
String idNo;
String response;
do
{
System.out.print("Please enter sales ID: ");
idNum = USER_INPUT.nextInt();
idNo = Integer.toString(idNum);
if(idNo.length() != 8)
System.out.println("Sales ID must be 8 digits long: ");
}
while(idNo.length() < 8 || idNo.length() > 8);
System.out.print("Name: ");
salesName = USER_INPUT.nextLine();
USER_INPUT.nextLine();
System.out.print("Sales Amount: ");
salesAmount = Double.parseDouble(USER_INPUT.nextLine());
salesStaffInDatabase[numOfSalesPpl] = new
Salesperson(salesName,idNum,salesAmount);
salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);
System.out.print("Do you want to display database Y/N?: ");
response = USER_INPUT.nextLine();
while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
{
displayDatabase();
}
}
public static void displayDatabase()
{
for(int val=0;val < numOfSalesPpl; val++)
{
System.out.println(salesStaffInDatabase[val]);
}
}
public static String programMenu()
{
String selection;
do
{
System.out.println("(A)dd a Record");
System.out.println("(C)hange a Record");
System.out.println("(E)xit Database");
System.out.print("Enter selection: ");
selection = USER_INPUT.nextLine();
}
while(!selection.equalsIgnoreCase("a") &&
!selection.equalsIgnoreCase("c")
&& !selection.equalsIgnoreCase("e"));
return selection;
}
}
=================================================================
In Java, whenever you want to display an object as string, you must override the toString() method.
The code that you posted, the Salesperson's toString() method returns only the salesID and anualSales. If you want to display another attribute, you must place it in the toString() method.
If you want to display the first name on the beginning of the output, you can do:
#Override public String toString() {
return String.format("%s - %-10s%-10.2f", salesFirstName, salesID, annualSales);
}
edit the toString()method in Salesperson class :
#Override
public String toString() {
return "Salesperson{" +
"salesFirstName='" + salesFirstName + '\'' +
", salesLastName='" + salesLastName + '\'' +
", salesID='" + salesID + '\'' +
", annualSales=" + String.format("%-10.2f", annualSales)+
'}';
}

Why am I getting an exception main "thread" error?

I have created two classes (and two interfaces) and then a main code. I just debugged the main code because I was getting an error that was preventing my code from working properly. I know that the problem in my Project03.java file is in line 29 and the line is input = userInput.nextLine(); . The error is:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at Project03.main(Project03.java:29)
Why is the error coming up and how can I prevent it? Thank you!
The codes are below:
SimpleMusicTrack.java
import java.util.Scanner;
import java.lang.Object;
public class SimpleMusicTrack implements PlayListTrack {
private String name;
private String artist;
private String albumName;
// Convenience constructor for unit testing
public SimpleMusicTrack(String name, String artist, String album) {
this.name = name;
this.artist = artist;
this.albumName = album;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getArtist() {
return this.artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getAlbum() {
return this.albumName;
}
public void setAlbum(String album) {
this.albumName = album;
}
public boolean getNextTrack(Scanner infile) {
if (infile == null)
return false;
while (infile.hasNext()) {
this.setName(infile.nextLine());
this.setArtist(infile.nextLine());
this.setAlbum(infile.nextLine());
return true;
}
return false;
}
public boolean equals(Object obj) {
boolean songInfo;
if (obj instanceof MusicTrack) {
MusicTrack name1 = (MusicTrack) obj;
if (this.name.equals(name1.getName())
&& this.artist.equals(name1.getArtist())
&& this.albumName.equals(name1.getArtist())) {
songInfo = true;
} else {
songInfo = false;
}
} else {
songInfo = false;
}
return songInfo;
}
public String toString() {
String allSongInfo;
allSongInfo = this.artist + " / " + this.name;
return allSongInfo;
}
}
PlayListTrack.java
import java.util.Scanner;
public interface PlayListTrack {
public String getName();
public void setName(String name);
public String getArtist();
public void setArtist(String artist);
public String getAlbum();
public void setAlbum(String album);
public boolean getNextTrack(Scanner infile);
// Attempts to read a play list track entry from a Scanner object
// Sets the values in the object to the values given in
// the file
// If it successfully loads the track, return true
// otherwise, return false
}
SimplePlayList.java
import java.util.*;
import java.util.Queue;
public class SimplePlayList implements PlayList {
Queue<PlayListTrack> queue;
public SimplePlayList(Scanner in) {
queue = new LinkedList<PlayListTrack>();
readFile(in);
}
public void readFile(Scanner in) {
Scanner inScanner = new Scanner(System.in);
Queue<PlayListTrack> queue = new LinkedList<PlayListTrack>();
while (in.hasNext()) {
queue.add(new SimpleMusicTrack(in.nextLine(), in.nextLine(), in
.nextLine()));
}
inScanner.close();
}
public PlayListTrack getNextTrack() {
while (!queue.isEmpty()) {
queue.remove();
}
return queue.peek();
}
public PlayListTrack peekAtNextTrack() {
while (!queue.isEmpty()) {
queue.peek();
}
return queue.peek();
}
public void addTrack(PlayListTrack track) {
while (!queue.isEmpty()) {
queue.add(track);
}
}
public boolean isEmpty() {
while (!queue.isEmpty()) {
return false;
}
return true;
}
}
PlayList.java
public interface PlayList {
public PlayListTrack getNextTrack();
// Removes track from PlayList and returns it to the caller
// Should return a null value if the PlayList is empty
public PlayListTrack peekAtNextTrack();
// Returns next entry to the caller, but leaves it in the list
public void addTrack(PlayListTrack track);
// Adds this track to the play list in the appropriate order
public boolean isEmpty();
// Returns true if the play list is empty
}
Project03.java
import java.io.File;
import java.io.*;
import java.util.Scanner;
public class Project03 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter database filename: ");
String fileName = userInput.nextLine();
try {
File file = new File(fileName);
Scanner musicList = new Scanner(file);
String input = "P";
PlayList playList = new SimplePlayList(musicList);
while (!"Q".equalsIgnoreCase(input)) {
if ("A".equalsIgnoreCase(input)) {
displayAddTrackOption(userInput, playList);
input = "";
} else {
displayNextSong(playList);
System.out.print("> ");
input = userInput.nextLine();
}
}
displayRemainingTracks(playList);
} catch (FileNotFoundException e) {
System.out.println("Sorry, could not find your file");
}
}
private static void displayRemainingTracks(PlayList playList) {
System.out
.println("Tracks remaining in play list------------------------------------------------------------");
if (!playList.isEmpty()) {
boolean hasAnotherTrack = true;
int lineNumber = 1;
while (hasAnotherTrack) {
MusicTrack currentTrackToPlay = (MusicTrack) playList
.getNextTrack();
if (currentTrackToPlay != null) {
System.out.printf("%d - %s / %s / %s\n", lineNumber,
currentTrackToPlay.getName(),
currentTrackToPlay.getArtist(),
currentTrackToPlay.getAlbum());
lineNumber++;
} else
hasAnotherTrack = false;
}
} else
System.out.println("No tracks remaining");
}
private static void displayAddTrackOption(Scanner userInput,
PlayList playList) {
String title, artist, album, confirmation;
System.out.print("Track name: ");
title = userInput.nextLine();
System.out.print("Artist name: ");
artist = userInput.nextLine();
System.out.print("Album name: ");
album = userInput.nextLine();
System.out.println("New Track: " + title);
System.out.println("Artist: " + artist);
System.out.println("Album: " + album);
System.out.print("Are you sure you want to add this track [y/n]? ");
confirmation = userInput.nextLine();
if ("Y".equalsIgnoreCase(confirmation)) {
playList.addTrack((PlayListTrack) new SimpleMusicTrack(title,
artist, album));
}
}
private static void displayNextSong(PlayList playList) {
MusicTrack currentMusicTrackToPlay;
MusicTrack nextMusicTrackToPlay;
currentMusicTrackToPlay = (MusicTrack) playList.getNextTrack();
nextMusicTrackToPlay = (MusicTrack) playList.peekAtNextTrack();
if (currentMusicTrackToPlay != null) {
System.out.println("Currently playing: "
+ currentMusicTrackToPlay.getName() + " / "
+ currentMusicTrackToPlay.getArtist());
} else {
System.out.println("Currently playing: No Song Playing");
}
if (nextMusicTrackToPlay != null) {
System.out.println("Next track to play: "
+ nextMusicTrackToPlay.getName() + " / "
+ nextMusicTrackToPlay.getArtist());
} else {
System.out.println("Play list is empty, no more tracks");
}
System.out.println("[P]lay next track");
System.out.println("[A]dd a new track");
System.out.println("[Q]uit");
}
}
You're using two Scanner's on the same stream (System.in). The first being userInput in the main method of your Project03 class. The second being inScanner in the readFile method of your SimplePlayList class:
public void readFile(Scanner in) {
Scanner inScanner = new Scanner(System.in); // <-- remove this line
Queue<PlayListTrack> queue = new LinkedList<PlayListTrack>();
while (in.hasNext()) {
queue.add(new SimpleMusicTrack(in.nextLine(), in.nextLine(), in
.nextLine()));
}
inScanner.close(); // <--- remove this line
}
Using multiple scanners on the same stream is the underlying problem. Scanners can (and will) consume the stream - this may (will) lead to unexpected side-effects. Best not to do it.
If the input is closed, then the input [...] is closed for everyone - and that's not much fun for anyone.
"Details" on why multiple scanners are bad: Do not create multiple buffered wrappers on an InputStream
- from user166390's answer on How to use multiple Scanner objects on System.in?

Printing a separate String from the same Object

I asked this question but the way I worded it was considered a duplicate which was not similar. I am trying to print a separate String for my printAllFlights method which prints all of the user entered information. My other methods print just fine. Here is the output I am trying to achieve.
Choose action:
[1] Print planes
[2] Print flights
[3] Print plane info
[x] Quit
> 2
HA-LOL (42 ppl) (HEL-BAL)
HA-LOL (42 ppl) (BAL-HEL)
How my code is now I get the output null(0) (HEL-BAL). How can i change it to reflect the correct output. Any help would be appreciated.
public class Airport {
private String planeId;
private int capacity;
private String dest;
private String dep;
public Airport(String planeId,int capacity){
this.planeId= planeId;
this.capacity = capacity;
}
public Airport(String planeId, String dep, String dest){
this.dest= dest;
this.dep= dep;
}
public String getPlaneId(){
return this.planeId;
}
public void setPlaneId(String planeId){
this.planeId = planeId;
}
public int getCapacity(){
return this.capacity;
}
public void setCapacity(int capacity){
this.capacity = capacity;
}
public String getDestination(){
return this.dest;
}
public void setDestination(String dest){
this.dest = dest;
}
public String getDeparture(){
return this.dep;
}
public void setDeparture(String dep){
this.dep = dep;
}
public String toString(){
return planeId + " (" + capacity + ")";
}
public String secString(){
return planeId + " (" + capacity + ")" + "(" + dest + "-" + dep;
}
}
import java.util.ArrayList;
public class FlightServices {
private ArrayList<Airport> airport;
public FlightServices() {
airport = new ArrayList<Airport>();
}
public void add(String planeId, int capacity) {
airport.add(new Airport(planeId, capacity));
}
public void addFlight(String planeId, String dest, String dep) {
airport.add(new Airport(planeId, dest, dep));
}
public void printAllPlanes() {
for (Airport all : airport) {
System.out.println(all);
}
}
public void printAllFlights() {
for (Airport all : airport) {
System.out.println(all.secString());
}
}
public void printPlanesInfo(String planeId) {
for (Airport info : airport) {
if (planeId.equals(info.getPlaneId())) {
System.out.println(info);
}
}
}
}
import java.util.Scanner;
public class UserInput {
private Scanner reader;
private FlightServices air;
public UserInput(Scanner reader, FlightServices air) {
this.reader = reader;
this.air = air;
}
public void start() {
while (true) {
System.out.println("Choose operation: ");
System.out.println("[1] Add airplane");
System.out.println("[2] Add flight");
System.out.println("[3] Exit");
int input = Integer.parseInt(reader.nextLine());
if (input == 3) {
break;
} else if (input == 1) {
this.addPlane();
} else if (input == 2) {
this.addFlight();
}
}
}
public void addPlane() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(reader.nextLine());
this.air.add(id, capacity);
}
public void addFlight() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give departure airport code: ");
String dep = reader.nextLine();
System.out.println("Give destination airport code: ");
String des = reader.nextLine();
this.air.addFlight(id,dep,des);
}
public void printing() {
while (true) {
System.out.println("Choose operation: ");
System.out.println("[1] Print planes");
System.out.println("[2] Print flights");
System.out.println("[3] Print plane info");
System.out.println("[4] Quit");
int command = Integer.parseInt(reader.nextLine());
if (command == 4) {
break;
} else if (command == 1) {
this.air.printAllPlanes();
} else if (command == 2) {
this.air.printAllFlights();
} else if (command == 3) {
this.addPlaneInfo();
}
}
}
public void addPlaneInfo() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
this.air.printPlanesInfo(id);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
FlightServices air = new FlightServices();
UserInput ui = new UserInput(reader,air);
ui.start();
System.out.println("Flight Service");
System.out.println("----------");
ui.printing();
}
}
Ok.
public void add(String planeId, int capacity) {
airport.add(new Airport(planeId, capacity));
}
public void addFlight(String planeId, String dest, String dep) {
airport.add(new Airport(planeId, dest, dep));
}
You're adding some Airportobjects to your airport using addFlight() and others using add(). The ones you add using addFlight() have no capacity values and the ones using add() have no dest or dep. Do you see? Simply making two entries with the same planeId will not combine them in your arraylist. When you try to print, some values will be null depending on how you had added the Airport objects.
EDIT:
One solution i can think of, while changing your code as less as possible-
public void add(String planeId, int capacity) {
int flag=0;
for(Airport air:airport) {
if(air.planeID.equals(planeID)) {
air.capacity=capacity;
flag=1;
}
}
if(flag==0)
airport.add(new Airport(planeId, capacity));
}
And similarly edit your add() function. This way, you can have all relevant fields filled in a single entry.
Of course, a much better idea would be to restructure your classes entirely, but this should work.

Categories

Resources