I have four classes. Project Class, Student Class, ProjectFile Class and ProjectFrame JFrame.
The ProjectFrame is only for GUI and i haven't touched that.
The Student and Project Class are constructors and i've coded those.
Now i'm trying to implement the ProjectFile class by reading from a text file and then storing the data to be read. I am having trouble as i'm not sure why the Instance of the Project Class isn't storing the data. I've looked at my loops and i did print the variables to be sure that the loop is actually happening. It works for the first time but when i try to call the second array, it gives me a NullPointerException. So i'm assuming it's storing the value as null but that shouldn't be the case.
This is my ProjectFile Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DecelAssignment;
import java.io.*;
/**
*
* #author Zane
*/
public class ProjectFile {
private static Project[] pJect;
private static Student[] sDent;
private static Project ja;
private static BufferedReader br;
public static void readData() {
File inputFile = new File("projects.txt");
try {
br = new BufferedReader(new FileReader(inputFile));
String s = br.readLine();
pJect = null;
pJect = new Project[Integer.parseInt(s)];
//System.out.println(s);
for (int i = 0; i < pJect.length; i++) {
s = br.readLine();
if (s == null) {
break;
} else {
String sLine[] = s.split(",");
int count = 3;
// for (int i2 = 0; i2 < Integer.parseInt(sLine[3]); i2++) {
// sDent[i2] = new Student(sLine[count+1], sLine[count+2], sLine[count+3], sLine[count+4]);
// count += 4;
// }
pJect[i] = new Project(sLine[0], sLine[1], sLine[2], sDent);
System.out.println(pJect[1].getTitle());
System.out.println(sLine[0]);
System.out.println(i);
}
}
} catch (IOException e) {
System.out.println("I caught an IO Exception1");
}
// } catch (NullPointerException e) {
// e.printStackTrace();
// System.out.println("I caught a Null Pointer Exception!");
//
// }
}
// public Project[] getProjectInfo() {
//
//
// return;
// }
public static void main(String[] args) {
readData();
}
}
This is the text file i'm reading from
3
iPhone App,EEE,John Tan,1,P109520,Kelvin Tay,DBIT,M
iPad App,DMIT,Mark Goh,3,P106286,Felicia Wong,DIT,F,P101803,Rachel Chang,DIT,F,P100036,Lewis Poh,DBIT,M
Green Living,DMIT,Audrey Lim,2,P101234,Peter Chua,DIT,M,P103287,Ng Ming Shu,DISM,F
Can someone please explain to me where i'm coding this wrongly? I can't figure it out.
EDIT:
This is the Project Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DecelAssignment;
/**
*
* #author Zane
*/
public class Project {
private String title, school, supervisor;
private Student[] stDent;
public Project() {
title = "";
school = "";
supervisor = "";
stDent = new Student[0];
}
public Student[] getStDent() {
return stDent;
}
public Project(String title, String school, String supervisor, Student[] stDent) {
this.title = title;
this.school = school;
this.supervisor = supervisor;
this.stDent = stDent;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getSupervisor() {
return supervisor;
}
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
I guess your code crashes here
System.out.println(pJect[1].getTitle());
In the first loop pJect[1] will contain null which causes a crash
You probably intend
System.out.println(pJect[i].getTitle());
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
}
}
import java.util.ArrayList;
public class Folder extends AbstractFile
{
//Replace previous ArrayLists with a single
//ArrayList of AbstractFile references
private ArrayList<AbstractFile> files = new ArrayList();
AbstractFile abstractfile;
/**
* Constructor for objects of class Folder
*/
public Folder(String name)
{
super();
this.name = name;
}
// replace previous add methods
// with a single add(AbstractFile fileObject) method
public boolean add(AbstractFile fileObject)
{
return files.add(fileObject);
}
#Override
public int size()
{
int size =0; // size holds the running total
for (AbstractFile file : files){ // for each AbsFile ref
size+=file.size(); //call size() and update the running total
}
return size; // return the final value
}
#Override
public int getNumFiles(){
int numFiles = 0;
for(AbstractFile file: files)
{
numFiles += file.getNumFiles();
}
return numFiles;// default value
}
#Override
public int getNumFolders(){
int numFolders = 0;
// for(AbstractFile file: files)
// {
// if(file instanceof Folder)
// {
// numFolders += file.getNumFolders();
// }
// }
// return numFolders;// default value
for (Object e : files)
{
if (e instanceof Folder)
{
numFolders += e.getNumFolders();
}
}
return numFolders;// default value
}
#Override
public AbstractFile find(String name){
//TODO Later - not in mini assignment
return null;
}
}
AbstractFile Class
public abstract class AbstractFile
{
// instance variables -
String name;
public abstract int size();
public abstract int getNumFiles();
public abstract int getNumFolders();
public abstract AbstractFile find(String name);
public String getName(){
return name;
}
}
FileSystem Class- for testing
public class FileSystem
{
public static void main(String[] args)
{
FileSystem fileSystem = new FileSystem();
fileSystem.fileTest1();
}
public void fileTest1(){
Folder documents = new Folder("Documents");
Folder music = new Folder("Music");
Folder photos = new Folder("Photos");
documents.add(music);
documents.add(photos);
File assign1 = new File("assign1.doc");
documents.add(assign1);
Folder dylan = new Folder("Dylan");
music.add(dylan);
Folder band = new Folder("The Band");
music.add(band);
File family = new File("family.jpg");
photos.add(family);
File tambourine = new File("tambourine.mp3");
dylan.add(tambourine);
File dixie = new File("dixie.mp3");
band.add(dixie);
File weight = new File("weight.mp3");
band.add(weight);
String contents1 = ("Hey, mister, can you tell me ");
String contents2 = ("Hey Mr Tambourine Man");
String contents3 = ("The night they drove old dixie down");
String contents4 = ("fee fi fo fum");
weight.setContents(contents1); // add contents to each File
tambourine.setContents(contents2);
dixie.setContents(contents3);
assign1.setContents(contents4);
//********test for size()****************
int expected = contents1.length() + contents2.length() + contents3.length() + contents4.length();
int result = documents.size();
if(result==expected){ // test fro equality
System.out.println("size() works");
}else{
System.out.println("size() doesn't work");
}
//*****************************************
//*****************test for getNumFiles()******************
expected =5;// what value should expected be set to?
result = documents.getNumFiles();
if(result==expected){ // test fro equality
System.out.println("NumFiles() works");
}else{
System.out.println("NumFiles() doesn't work");
}
//output the results of the test for equality
// **************************************
//*****************test for getNumFiles()******************
expected = 5; // what value should expected be set to?
result = documents.getNumFolders();
if(result==expected){ // test fro equality
System.out.println("NumFolder() works");
}else{
System.out.println("NumFolder() doesn't work");
System.out.printf("%d",result);
}
// **************************************
}
}
File Class
public class File extends AbstractFile
{
private String contents;
/**
* Constructor for objects of class File
*/
public File(String name)
{
super();
this.name = name;
}
public String getContents(){
return contents;
}
public void setContents(String contents){
this.contents = contents;
}
#Override
public int size()
{
if(contents==null){ //handle situation where contents may not have been set
return 0;
}
return contents.length();
}
#Override
public int getNumFiles(){
return 1; // a File object just returns 1 (it contains one File - itself)
}
#Override
public int getNumFolders(){
//TODO
return 0;
}
#Override
public AbstractFile find(String name){
//TODO Later - not in mini assignment
return null;
}
}
Hi, So Basically I'm having trouble with the getNumFolders(method) I have a test class created with 5 folders and these are stored in an ArrayList of type AbstractFile called files. I am trying to loop through this ArrayList to count the folders, bare in mind this ArrayList also contains files, so they must not be counted.
I would appreciate any help.
Thanks so much!
Simply if you want to count the number of Folder instances, then below should do the work.
public int getNumFolders() {
int numFolders = 0;
for(AbstractFile file: files) {
if(file instanceof Folder) {
numFolders++;
}
}
return numFolders;
}
and expectedValue should be 2 here accroding to your test case.
in fileTest1() method of your test case,
expected = 2; // this should be two because there are two folders called music and photos in documents folder
result = documents.getNumFolders();
if anyone can help please ,
i have an issue assign the values from a text file to the class fields.
i have created a class called process and it has a fields like
private String agent;
private String request_type;
private String class_type;
private String num_of_seats;
private String arrivaltime;
my motive is to assign 1block in the file to agent separated by space another block to request type and so on...
say Agent3 R F 10 1 here Agent3 is going to be assign to agent and R going to assign to request_type F to class_type, 10 to num_of_seats,1 to arrivaltime
i am using arraylist to saveinput file (not compulsory i know this only thats y) and another arraylist to save the objects of my class.i am using substring method to assign the values manually is there any way instead of that so that i can simply take block which is seprated by space and do my job.
The input file(input.txt is )
Agent1 R F 2 0
Agent3 R F 10 1
Agent1 C F 1 4
Agent2 C B 2 1
Agent2 R B 10 0
................................................................................
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* #author Navdeep
*
*/
class Process
{
private String agent;
private String request_type;
private String class_type;
private String num_of_seats;
private String arrivaltime;
public Process()
{
setProcess("0", null, null, "0", "0");
}
public Process(String a, String b,String c,String d,String e)
{
setProcess(a,b,c,d,e);
}
public void setProcess(String a, String b,String c,String d,String e)
{
setAgent(a);
setRequest_type(b);
setClass_type(c);
setNum_of_seats(d);
setArrivaltime(e);
}
public void setAgent(String a){
agent = a;
}
public void setRequest_type(String b){
request_type = b;
}
public void setClass_type(String c)
{
class_type = c;
}
public void setNum_of_seats(String d) {
num_of_seats = d;
}
public void setArrivaltime(String e)
{
arrivaltime=e;
}
public String getAgent(){
return agent;
}
public String getRequest_type(){
return request_type ;
}
public String getClass_type()
{
return class_type;
}
public String getNum_of_seats() {
return num_of_seats ;
}
public String getArrivaltime()
{
return arrivaltime;
}
#Override
public String toString() {
return String.format("%s,%s,%s,%s,%s",getAgent(),getRequest_type(),getClass_type(),getNum_of_seats(),getArrivaltime());
}
}
public class main
{
public static void main(String[] args) throws FileNotFoundException
{
File temp = new File(args[0]);
Scanner sc = new Scanner(temp);
ArrayList<String> input = new ArrayList<String>();
while(sc.hasNext())
{
input.add(sc.nextLine());
}
List<Process> mylist = new ArrayList<Process>();
for (int i= 0; i <input.size();i++)
{
Process processobject = new Process();
processobject.setAgent(input.get(i).substring(0, 6));
processobject.setRequest_type(input.get(i).substring(7,8));
processobject.setClass_type(input.get(i).substring(9,10));
if(input.get(i).length() == 15)
{
processobject.setNum_of_seats(input.get(i).substring(11,13));
processobject.setArrivaltime(input.get(i).substring(14,15));
}
if(input.get(i).length() == 14)
{
processobject.setNum_of_seats(input.get(i).substring(11,12));
processobject.setArrivaltime(input.get(i).substring(13,14));
}
mylist.add(processobject); // fill arraylist with objects of my class
}
System.out.println("array list of the input from the file" + input);
System.out.println("\n \nobjects in my list"+ mylist);
}
}
the overall motive of my project is to sort the objects according to the field priorities.
If your objective is to create Process class instance then you can use the following code:
while(sc.hasNext())
{
String line = sc.nextLine();
String elements[] = line.split(" ");
Process processobject = new Process();
processobject.setProcess(elements[0],elements[1],elements[2],elements[3],elements[4]);
}
You can improve the your setProcess method by setting accessing directly class attributes with this reference. Also you can pass the same parameters to Process class constructor then you won't need setProcess method. Check the below code.
public Process(String agent, String request_type, String class_type, String num_of_seats, String arrivaltime) {
this.agent = agent;
this.request_type = request_type;
this.class_type = class_type;
this.num_of_seats = num_of_seats;
this.arrivaltime = arrivaltime;
}
Try this:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(configFileName).getFile());
input = new FileInputStream(someFilePath);
prop.load(input);
String someString=prop.getProperty("someString");
int someintValue=new Integer(prop.getProperty("someintValue"));
I am learning OOP in Java. When finishing coding and compiling it, the compiler shows that this Manager class has private access to the Photographer class. I've been working on for a whole night, but I still cannot find the problem. Anyone could tell me how to fix it?
public class Manager
{
private ArrayList<Assignment> toDoList;
private ArrayList<Photographer> employees;
public Manager()
{
this.toDoList = new ArrayList<Assignment>();
this.employees = new ArrayList<Photographer>();
}
public void hire(String photographer)
{
employees.add(new Photographer(photographer));
}
public void giveOutAssignments()
{
int maxId;
if(toDoList.size()!=0 && employees.size()!=0){
for(Photographer p: employees){
maxId = 0;
//get highest priority
for(int i = 1; i<toDoList.size();i++){
//just check the unfinished assigns
if(!toDoList.get(i).getStatus()){
if(toDoList.get(i).getPriority()>toDoList.get(maxId).getPriority())
maxId = i;
}
}
//take the highest priority
Assignment currentAssign = toDoList.get(maxId);
//HERE IS THE PROBLEM
p.takePicture(currentAssign.getDescription());
//set it as finished
toDoList.get(maxId).setStatus();
}
}
}
}
Here is the Photographer class:
public class Photographer
{
private Map photos;
private String name;
public Photographer(String name)
{
photos = new HashMap(); // An important line. Must go in the constructor.
readPhotos(); // A very important line. this must go in the Photographer
// constructor so that the photographer will be able to take Pictures.
this.name = name;
}
private String takePicture(String description)
{
return photos.get(description);
}
private void readPhotos()
{
Pattern commentPattern = Pattern.compile("^//.*");
Pattern photoPattern = Pattern.compile("([a-zA-Z0-9\\.]+) (.*)");
try
{
Scanner in = new Scanner(new File("photos.txt"));
while (in.hasNextLine())
{
String line = in.nextLine();
Matcher commentMatcher = commentPattern.matcher(line);
Matcher photoMatcher = photoPattern.matcher(line);
if (commentMatcher.find())
{
// This line of the file is a comment. Ignore it.
}
else if (photoMatcher.find())
{
String fileName = photoMatcher.group(1);
String description = photoMatcher.group(2);
photos.put(description, fileName);
}
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
}
takePicture is declared private, it is inaccessible from any other context other than Photographer...
private String getDescription() {
change it to public...
public String getDescription() {
Take a look at Controlling Access to Members of a Class for more details
ps-
I also had an issue with the return type of takePicture in Photographer...
private String takePicture(String description)
{
return photos.get(description);
}
And had to change to something more like...
public String takePicture(String description) {
return (String)photos.get(description);
}
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();
}
}
}