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?
Related
Hi guys hope you're well (-:
I'm trying to write a method that reads from a file and creates different types of objects (Academic, Student, Programmer) that it then adds to a list (Person). I'm stuck trying to figure out a way to create different objects for each instance of a type of person, and add them to the list in the order that they are read. As in, it might go Programmer, Programmer, Student, Programmer, and it should add them in that order to the list. I've gotten it working where it creates an object for each type, but this means the output of the list is grouped by type instead of read order.
The data it reads will be newline separated, with the following format:
<type of person>
<name>
<additional data>
Where the type of person will determine which subclass of Person to create, name is the person's name, and additional data is a series of lines of additional of information corresponding to the type of person. A student will have (in this order): the name of their degree, which year they're in. An academic will have what subject they teach. A programmer will have their favourite programming language.
input file:
Student
Alice
Computer Science
2
Academic
Bob
Programming
Programmer
Eve
Scala
Student
Jim
Computer Science
1
So at the moment the output of this would be
[Hi, I'm Alice. I am studying Computer Science. I am in my 2nd year., Hi, I'm Jim. I am studying Computer Science. I am in my 1st year., Hi, I'm Bob. I teach Programming., Hi, I'm Eve. I like to program in Scala.]
But I want it to be
[Hi, I'm Alice. I am studying Computer Science. I am in my 2nd year., Hi, I'm Bob. I teach Programming., Hi, I'm Eve. I like to program in Scala., Hi, I'm Jim. I am studying Computer Science. I am in my 1st year.]
And here is the code-
import java.io.*;
import java.util.*;
public class MiniFB {
public static List<Person> readInData(String filename) {
//this is the method I am talking about
ArrayList<Person> list = new ArrayList<Person>();
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNextLine()) {
if (sc.nextLine().equals("Student")) {
String n = sc.nextLine();
String d = sc.nextLine();
int y = sc.nextInt();
Student s = new Student(n, d, y);
list.add(s);
}
}
sc.close();
}
catch (IOException e) {
System.err.println("error");
}
//
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNextLine()) {
if (sc.nextLine().equals("Academic")) {
String n = sc.nextLine();
String s = sc.nextLine();
Academic a = new Academic(n, s);
list.add(a);
}
}
sc.close();
}
catch (IOException e) {
System.err.println("error");
}
//
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNextLine()) {
if (sc.nextLine().equals("Programmer")) {
String n = sc.nextLine();
String l = sc.nextLine();
Programmer p = new Programmer(n, l);
list.add(p);
}
}
sc.close();
}
catch (IOException e) {
System.err.println("error");
}
//
return list;
}
public static void main(String[] args) {
List<Person> people = readInData("testFile.txt");
System.out.println(people);
}
}
public abstract class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
#Override
public String toString() {
return "Hi, I'm " + name + ".";
}
#Override
public abstract boolean equals(Object other);
}
public class Student extends Person {
private String degree;
private int year;
public Student(String name, String degree, int year) {
super(name);
this.degree = degree;
this.year = year;
}
private String ordinalEnding(int cardinal) {
if (cardinal % 100 >= 11 && cardinal % 100 <= 13) return "th";
switch (cardinal % 10) {
case 1 :
return "st";
case 2 :
return "nd";
case 3 :
return "rd";
default :
return "th";
}
}
#Override
public String toString() {
return super.toString() + " I am studying " + this.degree + ". I am in my " + this.year + ordinalEnding(this.year) + " year.";
}
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof Student)) return false;
Student other = (Student)o;
return (this.getName().equals(other.getName()) && this.degree.equals(other.degree) && this.year == other.year);
}
}
public class Academic extends Person {
private String subject;
public Academic(String name, String subject) {
super(name);
this.subject = subject;
}
#Override
public String toString() {
return super.toString() + " I teach " + this.subject + ".";
}
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof Academic)) return false;
Academic other = (Academic)o;
return (this.getName().equals(other.getName()) && this.subject.equals(other.subject));
}
}
public class Programmer extends Person {
private String language;
public Programmer(String name, String language) {
super(name);
this.language = language;
}
#Override
public String toString() {
return super.toString() + " I like to program in " + this.language + ".";
}
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof Programmer)) return false;
Programmer other = (Programmer)o;
return (this.getName().equals(other.getName()) && this.language.equals(other.language));
}
}
Okay, so the basic problem is with how you are parsing the file...
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNextLine()) {
if (sc.nextLine().equals("Student")) {
System.out.println("Student");
String n = sc.nextLine();
String d = sc.nextLine();
int y = sc.nextInt();
Student s = new Student(n, d, y);
list.add(s);
}
}
sc.close();
}
catch (IOException e) {
System.err.println("error");
}
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNextLine()) {
if (sc.nextLine().equals("Academic")) {
System.out.println("Academic");
String n = sc.nextLine();
String s = sc.nextLine();
Academic a = new Academic(n, s);
list.add(a);
}
}
sc.close();
}
catch (IOException e) {
System.err.println("error");
}
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNextLine()) {
if (sc.nextLine().equals("Programmer")) {
System.out.println("Programmer");
String n = sc.nextLine();
String l = sc.nextLine();
Programmer p = new Programmer(n, l);
list.add(p);
}
}
sc.close();
}
catch (IOException e) {
System.err.println("error");
}
The first scan will pick up both students, then the next will pick up the academics and the last the programmers, which is great if you want to sort them like that.
Opening and closing the file like this is inefficient, a better solution would be to read each line and make an assessment over what you need to do with it, something like...
try ( Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.equals("Student")) {
String n = sc.nextLine();
String d = sc.nextLine();
int y = sc.nextInt();
Student s = new Student(n, d, y);
list.add(s);
} else if (line.equals("Academic")) {
String n = sc.nextLine();
String s = sc.nextLine();
Academic a = new Academic(n, s);
list.add(a);
} else if (line.equals("Programmer")) {
String n = sc.nextLine();
String l = sc.nextLine();
Programmer p = new Programmer(n, l);
list.add(p);
}
}
} catch (IOException e) {
e.printStackTrace();
}
This will load each entry in the order it appears in the file and will print
[Hi, I'm Alice. I am studying Computer Science. I am in my 2nd year., Hi, I'm Jim. I am studying Computer Science. I am in my 1st year., Hi, I'm Bob. I teach Programming., Hi, I'm Eve. I like to program in Scala.]
Another thing you might want to consider, is allowing each class to parse the text from the Scanner itself, as each class would have a better idea of what it needs and it helps decouple some of the logic, as a suggestion.
So, we could modify the Person and child classes to accept a Scanner via the constructor, this means that each class becomes responsible for it's own parsing...
public static abstract class Person {
private String name;
public Person(Scanner scanner) {
this.name = scanner.nextLine();
}
public String getName() {
return this.name;
}
#Override
public String toString() {
return "Hi, I'm " + name + ".";
}
#Override
public abstract boolean equals(Object other);
}
public static class Student extends Person {
private String degree;
private int year;
public Student(Scanner scanner) {
super(scanner);
this.degree = scanner.nextLine();
this.year = scanner.nextInt();
}
private String ordinalEnding(int cardinal) {
if (cardinal % 100 >= 11 && cardinal % 100 <= 13) return "th";
switch (cardinal % 10) {
case 1 :
return "st";
case 2 :
return "nd";
case 3 :
return "rd";
default :
return "th";
}
}
#Override
public String toString() {
return super.toString() + " I am studying " + this.degree + ". I am in my " + this.year + ordinalEnding(this.year) + " year.";
}
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof Student)) return false;
Student other = (Student)o;
return (this.getName().equals(other.getName()) && this.degree.equals(other.degree) && this.year == other.year);
}
}
public static class Academic extends Person {
private String subject;
public Academic(Scanner scanner) {
super(scanner);
this.subject = scanner.nextLine();
}
#Override
public String toString() {
return super.toString() + " I teach " + this.subject + ".";
}
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof Academic)) return false;
Academic other = (Academic)o;
return (this.getName().equals(other.getName()) && this.subject.equals(other.subject));
}
}
public static class Programmer extends Person {
private String language;
public Programmer(Scanner scanner) {
super(scanner);
this.language = scanner.nextLine();
}
#Override
public String toString() {
return super.toString() + " I like to program in " + this.language + ".";
}
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof Programmer)) return false;
Programmer other = (Programmer)o;
return (this.getName().equals(other.getName()) && this.language.equals(other.language));
}
}
Then reading the file becomes as simple as...
try ( Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.equals("Student")) {
Student s = new Student(sc);
list.add(s);
} else if (line.equals("Academic")) {
Academic a = new Academic(sc);
list.add(a);
} else if (line.equals("Programmer")) {
Programmer p = new Programmer(sc);
list.add(p);
}
}
} catch (IOException e) {
e.printStackTrace();
}
We could talk a lot about "factory patterns" and the like, but this gets the basic idea across ;)
No, you don't need to do this, it's just another way to approach the problem ;)
ArrayList<Person> list = new ArrayList<Person>();
try (Scanner sc = new Scanner(new File(filename))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.equals("Student")) {
String n = sc.nextLine();
String d = sc.nextLine();
int y = sc.nextInt();
Student s = new Student(n, d, y);
list.add(s);
} else if (line.equals("Academic")) {
String n = sc.nextLine();
String s = sc.nextLine();
Academic a = new Academic(n, s);
list.add(a);
} else if (line.equals(...)) {
..
}
}
sc.close();
}
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() + '}';
}
}
I can't get my program to read from a file and populate my array.
This is my StudentAccount class which contains my array.
The array needs to be able to populate from a text file
and also add a Student by using the Scanner class.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class Student {
// attributes
private StudentAccount[] list; // to hold the accounts
private int numStudents;
// to keep track of the number of accounts in the list
// methods
// the constructor
public Student() {
// size array with parameter
list = new StudentAccount[20];
numStudents = 0;
}
// helper method to find the index of a specified account
private int search(String studentNameIn) {
for (int i = 0; i < numStudents; i++) {
StudentAccount tempAccount = list[i];
// find the account at index i
String tempName = tempAccount.getStudentName();
// get account number
if (tempName.equals(studentNameIn))
// if this is the account we are looking for
{
return i; // return the index
}
}
return -999;
}
// return the total number of accounts in the list
public int getTotal() {
return numStudents;
}
// check if the list is empty
public boolean isEmpty() {
if (numStudents == 0) {
return true; // list is empty
} else {
return false; // list is not empty
}
}
// check if the list is full
public boolean isFull() {
if (numStudents == list.length) {
return true; // list is full
} else {
return false; // list is empty
}
}
// add an item to the array
public boolean add(StudentAccount accountIn) {
if (!isFull()) // check if list is full
{
list[numStudents] = accountIn; // add item
numStudents++; // increment total
return true; // indicate success
} else {
return false; // indicate failure
}
}
// return an account at a particular place in the list
public StudentAccount getItem(int positionIn) {
if (positionIn < 1 || positionIn > numStudents) {
return null; // indicate invalid index
} else {
return list[positionIn - 1];
}
}
// return an account with a particular account number
public StudentAccount getItem(String studentNameIn) {
int index;
index = search(studentNameIn);
if (index == -999) {
return null; // indicate invalid index
} else {
return list[index];
}
}
// remove an account
public boolean remove(String numberIn) {
int index = search(numberIn); // find index of account
if (index == -999) // if no such account
{
return false; // remove was unsuccessful
} else { // overwrite items by shifting other items along
for (int i = index; i <= numStudents - 2; i++) {
list[i] = list[i + 1];
}
numStudents--; // decrement total number of accounts
return true; // remove was successful
}
}
static void writeToFile() {
}
static void readFromFile() {
try {
FileInputStream fstream = new FileInputStream("Students.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
in.close();
} catch (Exception e) {
System.out.println("File Not Found");
}
}
}
This is my Student class:
public class StudentAccount {
private String studentName;
private String studentDOB;
private String studentAddress;
private String studentGender;
public final static String MALE = "m";
public final static String FEMALE = "f";
public StudentAccount(String nameIn, String dobIn,
String addressIn, String genderIn) {
this.studentName = nameIn;
this.studentDOB = dobIn;
this.studentAddress = addressIn;
this.studentGender = genderIn;
}
public String getStudentName() {
return studentName;
}
public String getStudentDOB() {
return studentDOB;
}
public String getStudentAddress() {
return studentAddress;
}
public String getStudentGender() {
return studentGender;
}
public static boolean validateGender(String genderIn) {
return (genderIn.toLowerCase().compareTo(MALE) == 0)
|| (genderIn.toLowerCase().compareTo(FEMALE) == 0);
}
}
Finally this is my main class which runs my program.
The method for readFromFile
I need it to read the file one line at a time and save each line as one student record in the array. It reads in from file but doesn't put any data in the array.
public class EnrolmentRegister {
private static String lecturer = "John Smyth";
public static void main(String[] args) {
char choice;
Student newStudent = new Student();
Student.readFromFile();
do {
System.out.println();
System.out.println("1. Add A New Student Account");
System.out.println("2. Remove A Student Account");
System.out.println("3. Get Course Details ");
System.out.println("4. Quit");
System.out.println();
System.out.println("Please Choose One Of The Options Above");
choice = InputScanner.nextChar();
System.out.println();
switch (choice) {
case '1':
option1(newStudent);
break;
case '2':
option2(newStudent);
break;
case '3':
option3(newStudent);
break;
case '4':
break;
default:
System.out.println("Invalid entry");
}
} while (choice != '4');
}
static void option1(Student StudentIn) {
String gender;
System.out.print("Enter Student Name: ");
String studentName = InputScanner.nextString();
System.out.print("Enter Student Date Of Birth: ");
String studentDOB = InputScanner.nextString();
System.out.print("Enter Student Address: ");
String studentAddress = InputScanner.nextString();
do {
System.out.print("Enter Student Gender m/f: ");
gender = InputScanner.nextString();
} while (!StudentAccount.validateGender(gender));
// create new account
StudentAccount account =
new StudentAccount(studentName, studentDOB,
studentAddress, gender);
// add account to list
boolean ok = StudentIn.add(account);
if (!ok) {
System.out.println("The list is full");
} else {
System.out.println("Account created");
}
}
static void option2(Student StudentIn) {
// get account number of account to remove
System.out.print("Enter Student Name: ");
String studentName = InputScanner.nextString();
// delete item if it exists
boolean ok = StudentIn.remove(studentName);
if (!ok) {
System.out.println("No such Student Name");
} else {
System.out.println("Account removed");
}
}
static void option3(Student StudentIn) {
System.out.println("COM 180, " + lecturer);
}
static void option4(Student StudentIn) {
}
static void option5(Student StudentIn) {
}
}
/*When I call the readFromFile method and print it I get each
line of text from the text file but don't know how
to put each line from the file into the array. This is
homework and been at this for days. I know its probably
something simple but I cant work it out. Any help would
be greatly appreciated. Thanks*/
I do not see you declare InputScanner anywhere as scanner:
Scanner InputScanner = new Scanner(new File("fileNameGoesHere"));
Yet you call it multiple times in main:
choice = InputScanner.nextChar();
String studentName = InputScanner.nextString();
Note: do not capitalize variable names since it may be confused with Object types.
I am attempting to write a program that will output data received from a csv file. The CSV file is composed of 28 or so strings/lines with each data in the line separated by a comma into 5 categories (Team name, League, Coaches, Division and Full Time).
I actually have a couple of issues...
When i run my program, i receive a random sequence of characters (such as: [Ljava.lang.String;#5e34d46a) in my coaches category instead of a name that i am expecting. Does this have something to do with it being in an array? How would i solve it.
The categories for each string are displayed in the output as a list, i would like to output the data of strings into a line. For example, instead of the output displaying:
Team name: Team A
League: Western Conference
Coaches: [Ljava.lang.String;#1c751d58
Division: 2
Full Time: true
I would like it to be displayed as a line.
The last category of a single instance of a string in the output is attached to the first category of the next string. Like so: Full Time: trueTeam name: Team A. How would i separate this?
My Team.java code:
public class Team
{
private String name;
private String league;
private String[] coaches;
private String division;
private boolean fullTime;
public Team(String dataLine)
{
String[] data = dataLine.split(",");
this.name = data[0];
this.coaches = getStringAsArray(data[1], ":");
this.league = data[2];
this.division = data[3];
this.fullTime = data[4].equals("yes");
}
public Team(){
}
private String[] getStringAsArray(String t, String delimiter)
{
String[] result = t.split(delimiter);
return result;
}
private String getArrayAsString(String[] coaches)
{
coaches = this.getCoaches();
String result = "";
for(int i = 0; i<coaches.length; i++)
{
result += coaches[i] +" ";
}
result = result.trim();
return result;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setCoaches(String coaches)
{
this.coaches = getStringAsArray(coaches, ":");
}
public String getCoachesAsString()
{
String result = getArrayAsString(coaches);
return result;
}
public boolean isFullTime() {
return fullTime;
}
public void setFullTime(boolean fullTime) {
this.fullTime = fullTime;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String[] getCoaches() {
return coaches;
}
public void setCoaches(String[] coaches) {
this.coaches = coaches;
}
public String getLeague() {
return league;
}
public void setLeague(String league) {
this.league = league;
}
#Override
public String toString() {
return "Team name: " + name + "\nLeague: " + this.league + "\nCoaches: " + this.coaches + "\nDivision: " + this.division + "\nFull Time: " + this.fullTime;
}
}
My StoreData.java code:
import shiftershape.model.Team;
import java.util.ArrayList;
public class StoreData {
public static ArrayList<Team> teams = new ArrayList<Team>();
public static String getTeams()
{
String s = "";
for(int i = 0; i < teams.size(); i++){
s += teams.get(i);
}
return s;
}
public static ArrayList<Team> TeamListFromArray(String[] as)
{
ArrayList<Team> teams = new ArrayList<Team>();
// for( int i= 0 ; i < as.length; i++){
for (String s: as){
teams.add(new Team(s));
}
return teams;
}
}
My ReadCSV.java code:
import Utilities.StoreData;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import shiftershape.model.Team;
public class ReadCsv {
public void readCsv() {
String csvFileToRead = "C:/Users/Fryyy/Desktop/FootballRepo/TestData/football_teams_phase1.csv";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
int i = 0;
while ((line = br.readLine()) != null) {
Team one = new Team(line);
if(i > 0){
StoreData.teams.add(new Team(line));
}else{
i++;
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static ArrayList<Team> getTeams() {
return StoreData.teams;
}
public static void setTeams(ArrayList<Team> teams) {
StoreData.teams = teams;
}
}
My FootballC.java code:
import Utilities.StoreData;
import shiftershape.model.Team;
public class FootballC {
public static void main(String[] args)
{
ReadCsv junk = new ReadCsv();
junk.readCsv();
System.out.println(StoreData.getTeams());
}
}
System.out.println(StoreData.getTeams()); will call toString() on String[]
try this:
for (String s : StoreData.getTeams()) {
System.out.println(s);
}
[Ljava.lang.String;#5e34d46a) is the resource code for an object when printed to standard out. In this case being a string, so somewhere it looks like you're printing an array instead of the value within the array, causing the resource ID to be shown instead of the values within, as Java doesn't print array contents by default.
[Ljava.lang.String;#1c751d58 is the String version of an array. Arrays don't have a nice toString() method. If you used Lists in stead of Arrays it will print better.
The quick conversion of an array to a list is Arrays.asList(array);
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.