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);
Related
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() + '}';
}
}
As you can see, these are my three classes I use for this program .. I can not find the way to let me return the two parameters in the sentence even if I do not write the keyword that I have in the array .. i would like to find the way i allow me to write input: "From roma to milano" or "to roma da milano" and have reset the parameters as they are in the code I have already developed .. according to you it is possible to achieve this, in addition to what already does the code which I have proposed to you in vision? Thanks for the attention, and for the time spent for me. Good day !
package eubot.controller;
import eubot.dictionary.EubotDictionary;
public class EubotController {
public EubotDictionary getDictionary(String stringInput) {
EubotDictionary dictionary = null;
String found = null;
for (String string1 : EubotDictionary.keyWord) {
if (stringInput.contains(string1)) {
dictionary = new EubotDictionary();
dictionary.setTesto(stringInput);
System.out.println("the string contains : " + string1);
found = string1;
String splittable = stringInput.substring(stringInput.indexOf(found) + found.length(),
stringInput.length());
// System.out.println(splittable);
for (String string2 : EubotDictionary.parameter) {
if (splittable.contains(string2)) {
dictionary = new EubotDictionary();
dictionary.setTesto(splittable);
found = string2;
String splittable1 = string2.valueOf(string2);
System.out.println("the parameters are : " + splittable1);
}
}
break;
}
}
return dictionary;
}
public EubotDictionary findParametro(String stringInput) {
EubotDictionary dictionary = null;
for (String string2 : EubotDictionary.parameter) {
if (stringInput.contains(string2)) {
}
dictionary = new EubotDictionary();
dictionary.testo = stringInput;
}
return dictionary;
}
}
package eubot.dictionary;
public class EubotDictionary {
public String testo;
public String getTesto() {
return testo;
}
public void setTesto(String testo) {
this.testo = testo;
}
public static String[] keyWord = { "devo andare", "voglio andare", "vorrei andare", "devo recarmi"};
public static String[] parameter = { "bari", "roma", "milano", "pisa", "firenze", "napoli", "como", "torino" };
public static String[] req;
}
package eubot.test;
import java.util.Scanner;
import eubot.controller.*;
import eubot.dictionary.*;
public class Test {
public static void main(String[] args) {
System.out.println("<<-|-|-|-|-|-|-|-|-|<<<Welcome In EuBot>>>|-|-|-|-|-|-|-|-|->>");
EubotController controller = new EubotController();
Scanner input = new Scanner(System.in);
String string;
while (true) {
string = input.nextLine();
EubotDictionary dictionary = controller.getDictionary(string);
}
}
}
Based on your comment:
public class EubotController {
private String[] parameter = { "bari", "roma", "milano", "pisa", "firenze", "napoli", "como", "torino" };
public void processInputString(String inputString) {
String[] input = inputString.split(" ");
boolean prefixPrinted = false;
for (String i : input) {
for (String p : parameter) {
if (i.equals(p)) {
if(!prefixPrinted) {
printPrefix(inputString, p); //call when the first parameter is found
prefixPrinted = true;
}
System.out.println("The parameters are: " + p);
}
}
}
}
private void printPrefix(String inputString, String parameterAfterPrefix) {
String prefix = inputString.substring(0,
inputString.indexOf(parameterAfterPrefix)).trim();
System.out.println(prefix);
}
}
I renamed getDictionary, so you need to call now controller.processInputString(string) in your main-method.
Eclipse can auto-generate a toString() method from a object's fields. If those fields are objects then they too may have similarly auto-generated toString() methods.
e.g. a President object might look like this:
President [country=USA, name=Name [title=Mr, forename=Barack, surname=Obama], address=Address [houseNumber=1600, street=Pennsylvania Avenue, town=Washington]]
which is easier to read if I format it:
President [
country=USA,
name=Name [
title=Mr,
forename=Barack,
surname=Obama],
address=Address [
houseNumber=1600,
street=Pennsylvania Avenue,
town=Washington]]
What is the best way to parse this String to create a map of maps?
I've got a solution, but it's not pretty. I was hoping to be able to avoid the low level String manipulation somehow, but here it is:
import java.util.LinkedHashMap;
import java.util.Map;
public class MappedObject {
public String className;
public Map<String, String> leafFields = new LinkedHashMap<>();
public Map<String, MappedObject> treeFields = new LinkedHashMap<>();
#Override
public String toString() {
return "[className=" + className
+ (leafFields.isEmpty() ? "" : ", leafFields=" + leafFields)
+ (treeFields.isEmpty() ? "" : ", treeFields=" + treeFields)
+ "]";
}
public static MappedObject createFromString(String s) {
MappedObject mo = new MappedObject();
new Mapper(s).mapObject(mo);
return mo;
}
private static class Mapper {
private String s;
public Mapper(String s) {
this.s = s;
}
private String mapObject(MappedObject mo) {
mo.className = removeFirstNCharacters(s.indexOf(' '));
while (s.contains("=")) {
removeLeadingNonLetters();
String key = removeFirstNCharacters(s.indexOf('='));
removeFirstNCharacters(1); // remove the =
String leafValue = getLeafValue();
if (leafValue != null) {
mo.leafFields.put(key, leafValue);
if (s.startsWith("]")) { // that was the last field in the tree
return s;
}
} else {
MappedObject treeField = new MappedObject();
mo.treeFields.put(key, treeField);
s = new Mapper(s).mapObject(treeField);
}
}
return s; // s contains only close brackets - ]
}
private void removeLeadingNonLetters() {
int i = 0;
while (!Character.isLetter(s.charAt(i))) {
i++;
}
removeFirstNCharacters(i);
}
private String removeFirstNCharacters(int n) {
String value = s.substring(0, n);
s = s.substring(value.length());
return value;
}
private String getLeafValue() {
int endIndex = getEndIndex();
if (!s.contains("[") || s.indexOf('[') > endIndex) {
return removeFirstNCharacters(endIndex);
}
return null;
}
/** The end of the value, if it's a leaf field. */
private int getEndIndex() {
if(s.contains(",")) {
return Math.min(s.indexOf(','), s.indexOf(']'));
}
return s.indexOf(']');
}
}
}
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?
I have to use getters and setters for this code and
actually i'm using two classes to get the result
here is Ndc class:
package java4u.com;
public class Ndc {
private String ndcQUAL;
private String ndcCODE;
private String ndcUNIT;
private String ndcQTY;
String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public String getndcQUAL() {
if(str.contains("N4"))
{
return "N4";
}
else
{
return "";
}
}
public void setndcQUAL(String getndcQUAL) {
this.ndcQUAL = getndcQUAL;
}
public String getndcCODE() {
if(str.contains("N4")){
int i=str.indexOf("N4");
str=str.substring(i+2,i+13);
return str;
}
else
{
return "";
}
}
public void setndcCODE(String getndcCODE) {
this.ndcCODE = getndcCODE;
}
public String getndcUNIT() {
if(str.contains("N4")) {
str=str.substring(i+13,i+15);
return str;
}else
{
return "";
}
}
public void setndcUNIT(String getndcUNIT) {
this.ndcUNIT = getndcUNIT;
}
public String getndcQTY() {
if(str.contains("N4")) {
do {
int i=str.indexOf(getndcUNIT());
str=str.substring(i,i++);
return str;
} while(str.length()<=35 || str.contains("N4") || str.contains("TPL"));
else
{
return "";
}
}
public void setndcQTY(String getndcQTY) {
this.ndcQTY = getndcQTY;
}
}
here i'm using str variable and the string will be entered during runtime and the condition is if string contains "N4" value then the loop should be continue else return space.
and I have four methods in this program and
getNdcQUAL() method should return "N4" if string contains "N4" value
and getNdcCODE() method should display next 11 digits after the "N4" for this case I shouldn't mention str.substring(2,13)..I should find the position of NdcQUAL and from there to next 11 digits will be print..
and getNdcUNIT() method should display next two bytes qualifier after the 11 digits for this case also I should find the position of NdcCODE and from there to 2 digits
and finally getNdcQTY() method should return the data after the NdcUNIT for this case also I should find the position of NdcUNIT and from there to untill one of the condition is met
here is my main class
package java4u.com;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor.GetterSetterReflection;
public class Test {
public static String getStr(String str)
{
return str;
}
public static void main(String args[]) {
Ndc ndc=new Ndc();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("enter a string:");
br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
couldn't understand how to pass the string value from Ndc.java to Test.java also couldn't get how to pass other methods from Ndc.java to Test.java
here is the sample output
str=N412345678923UN2345.677
it should return
N4
12345678923
UN
2345.67
please help me!!!!!!
Since you don't have a constructor. You need to manually set the str
If this N412345678923UN2345.677 is the br.readLine(). Then you need to set it in the for your NDC object
String str = br.readLine();
ndc.setStr(str); // now the str is set in your ndc object.
System.out.println(ndc.getndcCODE());
System.out.println(ndc.getndcUNIT());
System.out.println(ndc.getndcCQTY());
You should first pass the string like this :
ndc.setndcQUAL(yourString);
then get the required value :
System.out.print(ndc.getndcQUAL());
Your approach has one major flaw - you need to execute the methods in a predefined order, else it will extract wrong data. You can however use your setStr(String str) method to initialize all proper fields and then just use your getter methods to return the values you've set within your setStr(...) method:
public class Ndc
{
private String ndcQUAL;
private String ndcCODE;
private String ndcUNIT;
private String ndcQTY;
public void setStr(String str)
{
int pos = 0;
if (str.contains("N4"))
{
pos = str.indexOf("N4");
this.ndcQUAL = str.substring(pos, pos+=2);
this.ndcCODE = str.substring(pos, pos+=11);
this.ndcUNIT = str.substring(pos, pos+=2);
String data = str.substring(pos);
// trim the data at the end corresponding to the provided class logic
int p = data.length();
if (data.contains("N4"))
{
p = data.indexOf("N4");
}
else if (data.contains("TLP"))
{
p = data.indexOf("TLP");
}
if (p > 35)
p = 35;
this.ndcQTY = data.substring(0, p);
}
else
this.ndcQUAL = "";
}
public String getndcQUAL()
{
return this.ndcQUAL;
}
public String getndcCODE()
{
return this.ndcCODE;
}
public String getndcUNIT()
{
return this.ndcUNIT;
}
public String getndcQTY()
{
return this.ndcQTY;
}
}
To break the loop if no valid N4 string was entered, you first have to define a kind of loop first and check the getndcQUAL() return value if it equals N4 after you've assigned the input string to setStr(...):
public class Test
{
public static void main(String args[])
{
Ndc ndc=new Ndc();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
do
{
System.out.println("enter a string:");
ndc.setStr(br.readLine());
System.out.println("QUAL: "+ndc.getndcQUAL());
System.out.println("CODE: "+ndc.getndcCODE());
System.out.println("UNIT: "+ndc.getndcUNIT());
System.out.println("QTY: "+ndc.getndcQTY());
}
while("N4".equals(ndc.getndcQUAL()));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}