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();
}
}
}
Related
So I have have 2 types of files, one for level definition and other for blocks structure definition.
I need to parse both of them into list of strings which contains the lines, and go over the list and over each line, split and parse and map them into java objects.
I have no lead how to do it, I have read about java io reader but I do get confused here where and how to use it.
Understanding the content of the level specification of a single level: this will go over the strings, split and parse them, and map them to java objects, resulting in a LevelInformation object.
P.S I already wrote and built the LevelInformation interface(which works if I manually write a level that implements this interface), which contains every thing that is in the text file (level name, velocities,background and etc..)
So basically I just need to parse those texts file and map them into this interface.
public interface LevelInformation {
int numberOfBalls();
// The initial velocity of each ball
// Note that initialBallVelocities().size() == numberOfBalls()
// velocities created by (a,s) format. a = angle, s = speed.
List<Velocity> initialBallVelocities();
int paddleSpeed();
int paddleWidth();
// the level name will be displayed at the top of the screen.
String levelName();
// Returns a sprite with the background of the level
Sprite getBackground();
// The Blocks that make up this level, each block contains
// its size, color and location.
List<Block> blocks();
// Number of blocks that should be removed
// before the level is considered to be "cleared".
// This number should be <= blocks.size();
int numberOfBlocksToRemove();
}
An example of the files:
level_definition.txt
START_LEVEL
level_name:Square Moon
ball_velocities:45,500
background:image(background_images/night.jpg)
paddle_speed:650
paddle_width:160
block_definitions:definitions/moon_block_definitions.txt
blocks_start_x:25
blocks_start_y:80
row_height:100
num_blocks:4
START_BLOCKS
--ll--
--ll--
END_BLOCKS
END_LEVEL
block_definitions.txt
#block definitions
bdef symbol:l width:100 height:100 fill:color(RGB(154,157,84))
#spacers definitions
sdef symbol:- width:30
So I need to create a list and get a reader and somehow parse it.
I'll be glad to get some tips, ideas and help for doing this.
Thanks.
public class LevelSpecificationReader {
public List<LevelInformation> fromReader(java.io.Reader reader) {
// ...
}
}
I think I need to:
Split the file into lines and make a list of strings out of them.
Which means each line will get into the list as a string.
Get each line, and also split it into I don't know what, but in order
to get info and map in into the needed object. For example:
level_name: something
i'll have to get "something" into "level name" in my interface.
This is my failed attempt:
public List<LevelInformation> fromReader(java.io.Reader reader) throws IOException {
ArrayList<String> listOfLines = new ArrayList<>();
BufferedReader bufReader = new BufferedReader(new FileReader("file.txt"));
String line = bufReader.readLine();
while (line != null) {
listOfLines.add(line);
line = bufReader.readLine();
}
return listOfLines;
}
This code brings an error bcause I return a list of string but I need a list of LevelInformation.
This is not a complete solution, since the code in your question is not a reproducible example since it is not complete. Where are the definitions of classes Block and Sprite and Velocity? Well I guessed those and made up minimal definitions for them.
My hope is that the below code will be enough to help you complete your project. It is based on the details you posted including the sample file: level_definition.txt
Class Sprite
import java.awt.Image;
public class Sprite {
private Image image;
public Sprite(Image image) {
this.image = image;
}
}
class Velocity
public class Velocity {
private int speed;
public Velocity(int speed) {
this.speed = speed;
}
}
Class LevelDtl which implements your interface: LevelInformation.
Personally, I don't see the need for an interface. I think it should be a class.
public class LevelDtl implements LevelInformation {
private String levelName;
private List<Velocity> ballVelocities;
private Sprite background;
private int paddleSpeed;
private int paddleWidth;
private List<Block> blocks;
private int numBlocks;
#Override
public int numberOfBalls() {
return ballVelocities == null ? 0 : ballVelocities.size();
}
#Override
public List<Velocity> initialBallVelocities() {
return ballVelocities;
}
#Override
public int paddleSpeed() {
return paddleSpeed;
}
#Override
public int paddleWidth() {
return paddleWidth;
}
#Override
public String levelName() {
return levelName;
}
#Override
public Sprite getBackground() {
return background;
}
#Override
public List<Block> blocks() {
return blocks;
}
#Override
public int numberOfBlocksToRemove() {
return numBlocks;
}
public void setBackground(Sprite bg) {
background = bg;
}
public void setBallVelocities(List<Velocity> velocities) {
ballVelocities = velocities;
}
public void setLevelName(String name) {
levelName = name;
}
public void setPaddleSpeed(int speed) {
paddleSpeed = speed;
}
public void setPaddleWidth(int width) {
paddleWidth = width;
}
public String toString() {
return String.format("Level: %s , Paddle: [speed = %d , width = %d]",
levelName,
paddleSpeed,
paddleWidth);
}
}
All the methods with #Override annotation are implementations of methods in LevelInformation interface. Also, note that method toString() is only for debugging purposes since I use it in the final class which is the one you named: LevelSpecificationReader. It reads the file level_definition.txt line by line, assuming the format shown in your question and builds and configures an instance of class LevelDtl which it then adds to a List. Finally, the below code prints the contents of the List. Of-course, using the sample data you provided in your question, the List contains only one element.
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.imageio.ImageIO;
public class LevelSpecificationReader {
private static final String BACKGROUND = "background:";
private static final String BALL_VELOCITIES = "ball_velocities:";
private static final String END_BLOCKS = "END_BLOCKS";
private static final String END_LEVEL = "END_LEVEL";
private static final String IMAGE = "image(";
private static final String LEVEL_NAME = "level_name:";
private static final String PADDLE_SPEED = "paddle_speed:";
private static final String PADDLE_WIDTH = "paddle_width:";
private static final String START_BLOCKS = "START_BLOCKS";
private static final String START_LEVEL = "START_LEVEL";
private static void setBackground(LevelDtl level, String data) throws IOException {
Objects.requireNonNull(level, "Null level.");
if (data != null && !data.isEmpty()) {
// image(background_images/night.jpg)
if (data.startsWith(IMAGE)) {
String path = data.substring(IMAGE.length(), data.length() - 1);
BufferedImage image = ImageIO.read(new File(path));
level.setBackground(new Sprite(image));
}
}
}
private static void setInitialBallVelocities(LevelDtl level, String data) {
Objects.requireNonNull(level, "Null level.");
if (data != null && !data.isEmpty()) {
String[] numbers = data.split(",");
if (numbers.length > 0) {
List<Velocity> velocities = new ArrayList<>();
for (String number : numbers) {
try {
int speed = Integer.parseInt(number);
Velocity velocity = new Velocity(speed);
velocities.add(velocity);
}
catch (NumberFormatException xNUmberFormat) {
// Ignore.
}
}
level.setBallVelocities(velocities);
}
}
}
private static void setPaddleSpeed(LevelDtl level, String data) {
Objects.requireNonNull(level, "Null level.");
if (data != null && !data.isEmpty()) {
int speed;
try {
speed = Integer.parseInt(data);
}
catch (NumberFormatException xNumberFormat) {
speed = 0;
}
level.setPaddleSpeed(speed);
}
}
private static void setPaddleWidth(LevelDtl level, String data) {
Objects.requireNonNull(level, "Null level.");
if (data != null && !data.isEmpty()) {
int width;
try {
width = Integer.parseInt(data);
}
catch (NumberFormatException xNumberFormat) {
width = 0;
}
level.setPaddleWidth(width);
}
}
/**
* Start here.
*/
public static void main(String[] args) {
try (FileReader fr = new FileReader("level_definition.txt");
BufferedReader br = new BufferedReader(fr)) {
List<LevelInformation> levels = new ArrayList<>();
LevelDtl level = null;
String line = br.readLine();
while (line != null) {
if (START_LEVEL.equals(line)) {
// End current level.
if (level != null) {
levels.add(level);
}
// Start next level.
level = new LevelDtl();
}
else if (line.startsWith(LEVEL_NAME)) {
level.setLevelName(line.substring(LEVEL_NAME.length()));
}
else if (line.startsWith(BALL_VELOCITIES)) {
setInitialBallVelocities(level, line.substring(BALL_VELOCITIES.length()));
}
else if (line.startsWith(BACKGROUND)) {
setBackground(level, line.substring(BACKGROUND.length()));
}
else if (line.startsWith(PADDLE_SPEED)) {
setPaddleSpeed(level, line.substring(PADDLE_SPEED.length()));
}
else if (line.startsWith(PADDLE_WIDTH)) {
setPaddleWidth(level, line.substring(PADDLE_WIDTH.length()));
}
line = br.readLine();
}
if (level != null) {
levels.add(level);
}
System.out.println(levels);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
The above code only handles lines in file level_definition.txt up to and including this line:
paddle_width:160
Good luck with adding code to handle the rest of the contents of the file.
Maybe what you want is to break it into pieces first so that you don't need to worry about all the things at once and focus on parsing the strings. All you need to do is make a constructor that accepts string and then parse it in the constructor
public List<LevelInformation> fromReader(java.io.Reader reader) throws IOException {
ArrayList<LevelInformation> listOfLines = new ArrayList<>();
BufferedReader bufReader = new BufferedReader(new FileReader("file.txt"));
String line = bufReader.readLine();
while (line != null) {
listOfLines.add(new LevelInformation(line));
line = bufReader.readLine();
}
return listOfLines;
}
public class LevelInformation {
LevelInformation (String text) {
parseText(text);
}
private void parseText(String text) {
//do something here
}
}
Here I have the following classes below. How do I get my wordValidation() method to provide the wordContent to provide output only to the word found and its index.
For sample output using my test program below if I have a consonant word like "BCGAYYY", how do I provide output only to the wrong character in this case A(because A is not a consonat), to get an output like "BCGA" + index?
I have the method wordValidation() below however this provides the whole word and its index...
public abstract class Words {
private String wordDetail;
private String wordContent;
public Words(String wordDetail, String wordContent) throws InvalidWordException{
this.wordContent = wordContent;
this.wordDetail = wordDetail;
wordValidation();
}
public String getWordDetail() {
return this.wordDetail;
}
public String getWordContent() {
return this.wordContent;
}
public abstract String AcceptedCharacters();
public void wordValidation() throws InvalidWordException{
String content = getWordContent();
String theseletters = this.AcceptedCharacters();
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);
if (theseletters.indexOf(c) == -1) {
throw new InvalidWordException(content, i);
}
}
}
public String toString(){
return getWordDetail() + getWordContent();
}
Checked Exception
public class InvalidWordException extends Exception {
public InvalidWordException (String wordContent, int theIndex) {
super("Wrong Word" + wordContent + theIndex);
}
}
Concrete Class 1
public class Vowels extends Words {
private String validVowels;
public Vowels(String wordDetail, String wordContent) throws InvalidWordException {
super(wordDetail, wordContent);
}
#Override
public String AcceptedCharacters() {
return validVowels = "AEIOU";
}
public static void main(String[] args) {
try {
Vowels vowel = new Vowels("First Vowel Check" ,"AEIOXAEI");
} catch (InvalidWordException ex) {
System.out.println(ex.getMessage());
}
}
}
concrete class 2
public class Consonants extends Words {
private String validConsonants;
public Consonants(String wordDetail, String wordContent) throws InvalidWordException{
super(wordDetail, wordContent);
}
#Override
public String AcceptedCharacters() {
return validConsonants ="BCDFGHJKLMNPQRSTVXZWY";
}
public static void main(String[] args) {
try {
Consonants consonants = new Consonants("First Consonant Check","BCGAYYY");
} catch (InvalidWordException ex) {
System.out.println(ex.getMessage());
}
}
}
test program
public static void main(String[] args) {
try {
Consonants consonants = new Consonants("First Consonant Check","BCGAYYY");
} catch (InvalidWordException ex) {
System.out.println(ex.getMessage());
}
}
Change throw new InvalidWordException(content, i);
to
throw new InvalidWordException(content.substring(0,i), i);
In Java, String objects are immutable. So you were passing the original content string as is. That's why it is not giving you your desired output.
I'm trying to implement a HttpMessageConverter which would allow my program to talk over REST to an embedded smart controller.
The controller responds with strings such as:
ret=OK,htemp=27.0,hhum=-,otemp=27.0,err=0,cmpfreq=24
I have a Java object called SensorInfo.
public class SensorInfo {
String ret;
Double htemp;
String hhum;
Double otemp;
Integer err;
Integer cmpfreq;
// getters and setters
}
What's the best way of mapping the controller response to the above Java object?
You can simply split the string and assign each element as needed. You have:
ret=OK,htemp=27.0,hhum=-,otemp=27.0,err=0,cmpfreq=24
Lets assume you have that stored in a variable called myStr. Then all you need to do is this:
String[] strSplit = myStr.split(" ");
SensorInfo info = new SensorInfo();
info.ret = afterEquals(strSplit[0]);
info.htemp = Double.parse(afterEquals(strsplit[1]));
info.hhum = afterEquals(strSplit[2]);
info.otemp= Double.parse(afterEquals(strSplit[3]));
info.err = Integer.parse(afterEquals(strSplit[4]));
info.cmpfreq = Integer.parse(afterEquals(strSplit[5]));
You will declare a method to extract the part of the response after the equals sign to make the above work:
private String afterEquals(String input) {
input.substring(input.indexOf('=') + 1);
}
Note that this assumes the order of your response is fixed. If it isn't, you can easily modify this to look at each argument to see which variable to assign it to.
You should add error handling, as the following is not really error prone, but might help you:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ValueAssigner {
// ret=OK,htemp=27.0,hhum=-,otemp=27.0,err=0,cmpfreq=24
String ret;
Double htemp;
String hhum;
Double otemp;
Integer err;
Integer cmpfreq;
public static void main(String[] a) {
System.out.println(new ValueAssigner("ret=OK,htemp=27.0,hhum=-,otemp=27.0,err=0,cmpfreq=24").getCmpfreq());
}
ValueAssigner(String in) {
String[] split = in.split(",");
for (String s : split) {
Method method;
String[] keyValue = s.split("=");
try {
method = this.getClass().getMethod("set" + ucFirst(keyValue[0]), String.class);
method.invoke(this, keyValue[1]);
} catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException | SecurityException | NoSuchMethodException e) {
// e.printStackTrace();
// omitted here
}
}
}
private static String ucFirst(String in) {
return in.substring(0, 1).toUpperCase() + in.substring(1);
}
public String getRet() {
return ret;
}
public void setRet(String ret) {
this.ret = ret;
}
public Double getHtemp() {
return htemp;
}
public void setHtemp(String htemp) {
this.htemp = Double.parse(htemp);
}
public String getHhum() {
return hhum;
}
public void setHhum(String hhum) {
this.hhum = hhum;
}
public Double getOtemp() {
return otemp;
}
public void setOtemp(String otemp) {
this.otemp = Double.parse(otemp);
}
public Integer getErr() {
return err;
}
public void setErr(String err) {
this.err = Integer.parse(err);
}
public Integer getCmpfreq() {
return cmpfreq;
}
public void setCmpfreq(String cmpfreq) {
this.cmpfreq = Integer.parse(cmpfreq);
}
}
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 have the following piece of code :
Essentially the number of methods should remain the same as in the code and I need to extract a string from an element of the linkedlist of Objects of type emp_struct.. How do I do it?
import java.util.*;
import java.io.*;
class a1 {
static LinkedList l1;
private emp_struct input() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
emp_struct obj = new emp_struct();
obj.emp_id = br.readLine();
obj.name = br.readLine();
obj.salary = Double.parseDouble(br.readLine());
obj.dept = br.readLine();
try{
search(obj);
}catch(Exception e){
System.out.println(e);
obj = input();
}
return obj;
}
boolean search(emp_struct obj)
{
int lastIndex = l1.lastIndexOf(l1);
int begIndex = 0;
for(begIndex =0;begIndex<lastIndex;begIndex++)
{
Object chkCase = l1.get(begIndex);
String chk = chkCase.getEmpID();
if(chk.equals(obj.emp_id));
throw new DuplicateEntryException("Duplicate entry found");
}
return true;
}
public static void main(String args[]) throws IOException
{
l1 = new LinkedList();
}
}
class DuplicateEntryException extends Exception {
String detail;
DuplicateEntryException(String a)
{
detail = a;
}
public String toString()
{
return "User Defined Exception : "+detail;
}
}
class emp_struct {
public String emp_id;
public String name;
public double salary;
public String dept;
public String getEmpID()
{
return emp_id;
}
public String toString()
{
return emp_id+"\t"+name+"\t"+salary+"\t"+dept;
}
}
In your search method, if you find the value, you're throwing an exception. If you don't find the value, you return true. This doesn't seem like the best approach.
If you find the value, shouldn't you return true, then if it makes it through the array without finding it, shouldn't you return false?
This line
Object chkCase = l1.get(begIndex);
should be
emp_struct chkCase = (emp_struct)l1.get(begIndex);
among other things...