I have just begun working on a programming language called XScript. It is designed so that I can run it from a Java application, but also re-program it through a java application. The idea being so that I can create virtual computers in games or a program that develops itself over time. So far I have the following code. I understand there may need to be an alteration to the name due to proprietary software, but for now it is fine.
The Artificial Main Class:
import com.x.lang.XLoader;
public class Main {
public static void main(String[] args) {
XLoader xl = new XLoader();
xl.exec("/Users/Nathan/Desktop/XScript/test.xls");
}
}
The XLoader (Loads and executes the XScript):
package com.x.lang;
import java.io.File;
import com.x.lang.object.XObject;
public class XLoader {
XObject xo;
public String fileLocation;
public void exec(String fl) {
fileLocation = fl;
XObject xo = new XObject(new File(fileLocation));
xo.exec();
}
}
The XCommandHub Where the Language Key Functions are Stored:
package com.x.lang;
import com.x.lang.keyword.Print;
import com.x.lang.keyword.Set;
import com.x.lang.object.XCommand;
import com.x.lang.object.XObject;
public class XCommandHub {
public XCommand xc[] = new XCommand[2];
public XCommandHub(XObject x) {
xc[0] = new Print(x);
xc[1] = new Set(x);
}
public XCommand getCommand(String s) {
for (int i = 0; i < 2; i++) {
if (xc[i].getCommandName() == s) {
return xc[i];
}
}
return null;
}
}
The XCommand Class Defining The Keywords:
package com.x.lang.object;
public abstract class XCommand {
private String commandName;
public XObject xobject;
public XCommand (String cn, XObject x) {
commandName = cn;
commandName += ": ";
xobject = x;
}
public abstract void exec(XVar xv);
public String getCommandName() {
return commandName;
}
}
The XVar Class Defining All Variables:
package com.x.lang.object;
public class XVar {
private String var1;
public String name;
public XVar(String s) {
var1 = s;
}
public String getStringValue() {
if (this.var1 != null) {
return var1;
}
return " ";
}
public int getIntValue() {
if (this.var1 != null) {
return Integer.parseInt(var1);
}
return 0;
}
public void setName(String s) {
name = s;
}
}
The XObject Class Actual Executing the Commands:
package com.x.lang.object;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import com.x.lang.XCommandHub;
public class XObject {
public XVar xvars[] = new XVar[150];
public int varCount = 0;
public File f;
XCommandHub x;
public XObject (File file) {
f = file;
x = new XCommandHub(this);
}
public void addVar(XVar var, String name) {
xvars[varCount] = var;
xvars[varCount].setName(name);
varCount++;
}
public XVar getVar(String varName) {
for (int i = 0; i < varCount; i++) {
if (xvars[i].name == varName) {
return xvars[i];
}
}
return null;
}
public void exec() {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
for (int i = 0; i < 2; i++) {
if (sCurrentLine.startsWith(x.xc[i].getCommandName()))
try {
x.getCommand(x.xc[i].getCommandName()).exec(new XVar(sCurrentLine.split(": ")[1]));
} catch (ArrayIndexOutOfBoundsException e) {
x.getCommand(x.xc[i].getCommandName()).exec(new XVar(" "));
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The Two Classes Defining The Commands I Have Programmed So Far:
package com.x.lang.keyword;
import com.x.lang.object.XCommand;
import com.x.lang.object.XObject;
import com.x.lang.object.XVar;
public class Print extends XCommand {
public Print(XObject x) {
super("print", x);
}
#Override
public void exec(XVar xv) {
if (xv.getStringValue().startsWith("%")) {
try {
System.out.println(xobject.getVar(xv.getStringValue().substring(1)).getStringValue());
} catch (NullPointerException e) {
System.out.println(xv.getStringValue());
}
}
else {
System.out.println(xv.getStringValue());
}
}
}
package com.x.lang.keyword;
import com.x.lang.object.XCommand;
import com.x.lang.object.XObject;
import com.x.lang.object.XVar;
public class Set extends XCommand {
public Set(XObject x) {
super("set", x);
}
#Override
public void exec(XVar xv) {
String[] add = xv.getStringValue().split("=");
xobject.addVar(new XVar(add[1]), add[0]);
}
}
From what I have programmed so far I have tried to give the user the ability to print a variable that they have declared in the code. A basic .xls (X Language Script) might look something like this:
set: x=Hello StackOverflow
print: This was programmed in XScript!
print:
print: %x
However, there is a NullPointerException in the print class when I try and retrieve the variable x from the array. The program returns "%x" rather than "Hello StackOverflow", because I have deliberately caught the exception, however I do not know how it came about in the first place.
Thanks
Doctor_N
Your code will never find the variable it is looking for:
public XVar getVar(String varName) {
for (int i = 0; i < varCount; i++) {
if (xvars[i].name == varName) {
return xvars[i];
}
}
return null;
}
This function will almost always return null since you are comparing strings using == and not using .equals. == compares references (memory addresses) and it is highly unlikely that the parameter and the string you are comparing against will point to the same location. Due to this, you almost always return null.
Because of that, this line will always cause a NullPointerException:
System.out.println(xobject.getVar(xv.getStringValue().substring(1)).getStringValue());
This is because you are effectively calling getStringValue() on null.
I suggest changing the if to:
if(xvars[i] != null && xvars[i].name.equals(varName)) {
...
}
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
}
}
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 got the following code Simmulation.java, but when I tried compiling it, it is coming up with an error saying,
error: constructor CashewPallet in class CashewPallet cannot be applied to give types;
CashewPallet c1 = new CashewPallet();
Required: String,int, found: no arguments
Reason: Actual and formal arguments differ in length
I know what this error means, and when I tried to fix the line to CashewPallet c1 = new CashewPallet(String, int); and again CashewPallet c1 = new CashewPallet(nutType, id); but either didn't work! AND now I am not sure how can this be solved.
I am new to this, any help is much appreciated.
Many Thanks in advance!
Please bear with me.
EDIT : Thank you for the answers everyone! It has worked now and compiled successfully BUT when I executed it, it is coming up with error: ArrayIndexOutOfBoundsException :0 at Simmulation.main(Simmulation.java:201) Any help in fixing it Please?
THANK YOU!
This is Simmulation.java file
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class Simmulation implements Operation {
Queue<CashewPallet> inputQueue=new LinkedList<CashewPallet>();
Stack<CashewPallet> stBay1=new Stack<CashewPallet>();
Stack<CashewPallet> stBay2=new Stack<CashewPallet>();
FileOutputStream fout4;
PrintWriter pw;
static int tick=0;
CashewPallet c1;
String temp;
Scanner sc;
public Simmulation(String fn)
{
int index=0;
String nutType="";
int id=0;
Scanner s2 ;
try
{
sc = new Scanner(new File(fn));
fout4=new FileOutputStream("nuts.txt");
pw=new PrintWriter(fout4,true);
String eol = System.getProperty("line.separator");
while(sc.hasNextLine())
{
tick++;
s2 = new Scanner(sc.nextLine());
if(s2.hasNext())
{
while ( s2.hasNext())
{
String s = s2.next();
if(index==0)
{
nutType=s;
}
else
{
id=Integer.parseInt(s);
}
index++;
}
System.out.println("Nuttype "+nutType+" Id is "+id+"tick "+tick);
if((nutType.equalsIgnoreCase("A")||nutType.equalsIgnoreCase("P")|| nutType.equalsIgnoreCase("C")|| nutType.equalsIgnoreCase("W")) && id!=0)
inputQueue.add(new CashewPallet(nutType.toUpperCase(),id));
System.out.println("Size of Queue "+inputQueue.size());
int k=0;
if(!inputQueue.isEmpty())
{
while(inputQueue.size()>k)
{
// stBay1.push(inputQueue.poll());
process(inputQueue.poll());
k++;
}
// System.out.println("Size of input "+inputQueue.size() +" Size of stay "+stBay1.size());
}
}
else
{
fout4.write(" ".getBytes());
}
index=0;
if(!stBay2.isEmpty())
{
while(!stBay2.isEmpty())
{
c1=stBay2.pop();
temp=tick+" "+c1.getNutType()+" "+c1.getId()+eol;
fout4.write(temp.getBytes());
}
// System.out.println("Nut final "+ stBay2.peek().getNutType());
}
else
{
temp=tick+eol;
fout4.write(temp.getBytes());
}
}
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
closeStream();
}
public CashewPallet process( CashewPallet c)
{
//CashewPallet c=new CashewPallet();
int k=0;
//while(stBay.size()>k)
//{
//c=stBay.pop();
String operation=c.getNutType();
if(c.getPriority()==1)
{
shelling(c);
washing(c);
packing(c);
//stBay2.push(c);
}
else
{
switch(operation)
{
case "A": shelling(c);
washing(c);
packing(c);
break;
case "C": washing(c);
packing(c);
break;
case "W" : washing(c);
shelling(c);
packing(c);
break;
}
}
return c;
}
public void closeStream()
{
try
{
fout4.close();
}
catch(Exception e)
{
}
}
public boolean shelling(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Shelling for "+c.getNutType());
}
return true;
}
public boolean washing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Washing for "+c.getNutType());
}
return true;
}
public boolean packing(CashewPallet c)
{
//for(int i=0;i<20; i++)
{
System.out.println("Performing Packing for "+c.getNutType());
}
stBay2.push(c);
return true;
}
public static void main(String args[])
{
new Simmulation(args[0]);
}
This is CashewPallet.java file
public class CashewPallet {
private String nutType;
private int id;
private int priority;
private int opTick;
public int getOpTick() {
return opTick;
}
public void setOpTick(int opTick) {
this.opTick = opTick;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public CashewPallet(String nutType, int id) {
this.nutType = nutType;
this.id = id;
if(this.nutType.equalsIgnoreCase("p"))
{
priority=1;
}
else
{
priority=0;
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNutType() {
return nutType;
}
public void setNutType(String nutType) {
this.nutType = nutType;
}
When you use CashewPallet's constructor, you need to supply actual values for the arguments. The arguments are String nutType and int id, which means you need to supply a String that will go into nutType and an int that will go into id. For example:
CashewPallet c1 = new CashewPallet("Pecan", 42);
The constructor in CashewPallet requires a String and an int; you didn't provide them:
public CashewPallet(String nutType, int id)
You called it like this:
CashewPallet c1 = new CashewPallet();
Change it to something like:
CashewPallet c1 = new CashewPallet("Peanut",1337);
EDIT:
You're getting an ArrayIndexOutOfBoundsException on this line:
new Simmulation(args[0]);
That's in your args[0]. If that's out of bounds, then that means that you don't have command line arguments.
You should call it with command line arguments (or specifically one command line argument).
java Simmulation myarg
In this case your argument is the name of your file.
I'm using Eclipse and I'm using Java. My objective it's to sort a vector, with the bogoSort method
in one vector( vectorExample ) adapted to my type of vector and use the Java sort on other vector (javaVector) and compare them.
I did the tests but it did't work, so I don't know what is failing.
*Note: there are few words in spanish: ordenado = sorted, Ejemplo = Example, maximo = maximun, contenido = content.
EjemploVector class
package vector;
import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.Iterator;
public class EjemploVector <T> {
protected T[] contenido;
private int numeroElementos;
#SuppressWarnings("unchecked")
public EjemploVector () {
contenido = (T[]) new Object[100];
numeroElementos = 0;
}
#SuppressWarnings("unchecked")
public EjemploVector (int maximo) {
contenido = (T[]) new Object[maximo];
numeroElementos = 0;
}
public String toString(){
String toString="[";
for (int k=0; k<numeroElementos;k++){
if (k==numeroElementos-1){
toString = toString + contenido[k].toString();
} else {
toString = toString + contenido[k].toString()+", ";
}
}
toString = toString + "]";
return toString;
}
public boolean equals (Object derecho){
if (!(derecho instanceof Vector<?>)) {
return false;
} else if (numeroElementos != ((Vector<?>)derecho).size()) {
return false;
} else {
Iterator<?> elemento = ((Vector<?>)derecho).iterator();
for (int k=0; k<numeroElementos;k++){
if (!((contenido[k]).equals (elemento.next()))) {
return false;
}
}
return true;
}
}
public void addElement (T elemento){
contenido[numeroElementos++]= elemento;
}
protected T[] getContenido(){
return this.contenido;
}
protected T getContenido (int k){
return this.contenido[k];
}
#SuppressWarnings("unchecked")
protected void setContenido (int k, Object elemento){
this.contenido[k]= (T)elemento;
}
EjemploVectorOrdenadoClass
package vector.ordenado;
import java.util.Arrays;
import java.util.Random;
import vector.EjemploVector;
public class EjemploVectorOrdenado<T extends Comparable<T>> extends EjemploVector<T> {
private boolean organized;
public EjemploVectorOrdenado() {
super();
organized = true;
}
public EjemploVectorOrdenado(int maximo) {
super(maximo);
organized = true; //
}
public boolean getOrdenado() {
return this.organized;
}
// Method bogoSort
public void bogoSort() {
if (!this.organized) {
if (this.size() > 0) {
Random generator;
T tempVariable;
int randomPosition;
do {
generator = new Random();
for (int i = 0; i < this.size(); i++) {
randomPosition = generator.nextInt(this.size());
tempVariable = contenido[i];
contenido[i] = contenido[randomPosition];
contenido[randomPosition] = tempVariable;
}
} while (!organized);
}
}
this.organized = true;
}
public void addElement(T elemento) {
super.addElement(elemento);
if (organized && this.size() > 1) {
T penultimo = this.getContenido(this.size() - 2);
T ultimo = this.getContenido(this.size() - 1);
organized = penultimo.compareTo(ultimo) <= 0;
}
}
}
ElementoTest class
package elementos;
import java.io.Serializable;
public class ElementoTest implements Comparable<ElementoTest>, Serializable {
private static final long serialVersionUID = -7683744298261205956L;
private static int numeroElementosTest = 0;
private int clave;
private int valor;
public ElementoTest(int i){
this.clave = i;
this.valor = numeroElementosTest;
numeroElementosTest++;
}
public String toString(){
return ("(" + this.clave + "," + this.valor + ")");
}
public boolean equals (Object derecho){
if (!(derecho instanceof ElementoTest)) {
return false;
} else {
return clave == ((ElementoTest)derecho).clave;
}
}
public char getClave(){
return this.clave;
}
public int getValor(){
return this.valor;
}
#Override
public int compareTo(ElementoTest elemento) {
if (elemento == null){
return -1;
} else if (this.equals(elemento)){
return 0;
} else if (clave < elemento.clave){
return -1;
} else {
return 1;
}
}
}
TESTS
The first it's a stupid test, because it puts elements in order so... really the methods arenĀ“t doing anything, java just compare and it gives correct
I tried to make an unsorted vector adding elements but there appears the java.lang.ClassCastException: [Ljava.... etc.
package vector.ordenado;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.Vector;
import org.junit.Before;
import org.junit.Test;
import elementos.ElementoTest;
public class EjemploVectorOrdenadoTest {
private Vector<ElementoTest> vectorJava;
private EjemploVectorOrdenado<ElementoTest> vectorExample;
#Before
public void setUp() throws Exception {
vectorJava = new Vector<ElementoTest>(100);
vectorExample = new EjemploVectorOrdenado<ElementoTest>(100);
}
#Test
public void testSortFailTest() {
for (char c = 'a'; c < 'g'; c++) {
vectorJava.addElement(new ElementoTest(c));
vectorExample.addElement(new ElementoTest(c));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
#Test
public void testSort() {
{
vectorJava.addElement(new ElementoTest(1));
vectorJava.addElement(new ElementoTest(3));
vectorJava.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(3));
vectorExample.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(1));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
}
Sorry, for the problems and thanks.
The problem is that your test class ElementoTest should implement the Comparable interface. Or you need to provide a Comparator during your comparison.
Does your class ElementtoTest implement Comparable?
If not, it needs to.
I'm suspecting it doesn't, because that's exactly what would cause this error. you'll need to add implements Comparable and then override the int compareTo(Elementtotest e) method, where you specify what criteria you'd like to order the objects based on.
I'm parsing Java Source Files to collect various informations about my classes. Therefore I'm using the JavaParser, since I could not find a good alternative (good suggestions have the chance to become "answers") to parse Source Files.
I already managed to get Annotations of all methods from my class. The code looks like this:
package de.mackaz;
import japa.parser.JavaParser;
import japa.parser.ParseException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.expr.AnnotationExpr;
import japa.parser.ast.expr.MarkerAnnotationExpr;
import japa.parser.ast.expr.MemberValuePair;
import japa.parser.ast.expr.NormalAnnotationExpr;
import japa.parser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;
public class JavaSourceUtils {
public static void main(String[] args) throws Exception {
File f = new File("/home/mackaz/SourceFile.java");
inspectJavaFile(f);
}
public static void inspectJavaFile(File pFile)
throws FileNotFoundException, ParseException, IOException {
CompilationUnit cu;
FileInputStream in = new FileInputStream(pFile);
try {
cu = JavaParser.parse(in);
} finally {
in.close();
}
new MethodVisitor().visit(cu, null);
}
/**
* Simple visitor implementation for visiting MethodDeclaration nodes.
*/
private static class MethodVisitor extends VoidVisitorAdapter {
#Override
public void visit(MethodDeclaration n, Object arg) {
System.out.println(n.getName());
if (n.getAnnotations() != null) {
for (AnnotationExpr annotation : n.getAnnotations()) {
System.out.println(annotation.getClass());
// MarkerAnnotations, for example #Test
if (annotation.getClass().equals(MarkerAnnotationExpr.class)) {
System.out.println("MarkerAnnotation:" + ((MarkerAnnotationExpr)annotation).getName());
}
if (annotation.getClass().equals(NormalAnnotationExpr.class)) {
for (MemberValuePair pair : ((NormalAnnotationExpr)annotation).getPairs()) {
if (pair.getName().equals("groups"))
System.out.println("Group:\"" + pair.getValue() + "\"");
}
}
}
}
}
}
}
Now how can I get the Annotations of the class itself?
You are overriding public void visit(MethodDeclaration n, Object arg), which visits methods. You can also override public void visit(ClassOrInterfaceDeclaration n, A arg) or public void visit(ClassOrInterfaceType n, A arg), which should give you access to the information you are looking for.
This is how I solved it in the end - I added another Visitor "ClassVisitor":
private static class ClassVisitor extends VoidVisitorAdapter {
#Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
for (AnnotationExpr ann: n.getAnnotations()) {
System.out.println(ann.toString());
}
}
}
Looks like you need extend ModifierVisitorAdapter and implement
public Node visit(ClassOrInterfaceDeclaration n, A arg) {
Look at the implementation here for an idea of what you might want to do:
public Node visit(ClassOrInterfaceDeclaration n, A arg) {
if (n.getJavaDoc() != null) {
n.setJavaDoc((JavadocComment) n.getJavaDoc().accept(this, arg));
}
List<AnnotationExpr> annotations = n.getAnnotations();
if (annotations != null) {
for (int i = 0; i < annotations.size(); i++) {
annotations.set(i, (AnnotationExpr) annotations.get(i).accept(this, arg));
}
removeNulls(annotations);
}
List<TypeParameter> typeParameters = n.getTypeParameters();
if (typeParameters != null) {
for (int i = 0; i < typeParameters.size(); i++) {
typeParameters.set(i, (TypeParameter) typeParameters.get(i).accept(this, arg));
}
removeNulls(typeParameters);
}
List<ClassOrInterfaceType> extendz = n.getExtends();
if (extendz != null) {
for (int i = 0; i < extendz.size(); i++) {
extendz.set(i, (ClassOrInterfaceType) extendz.get(i).accept(this, arg));
}
removeNulls(extendz);
}
List<ClassOrInterfaceType> implementz = n.getImplements();
if (implementz != null) {
for (int i = 0; i < implementz.size(); i++) {
implementz.set(i, (ClassOrInterfaceType) implementz.get(i).accept(this, arg));
}
removeNulls(implementz);
}
List<BodyDeclaration> members = n.getMembers();
if (members != null) {
for (int i = 0; i < members.size(); i++) {
members.set(i, (BodyDeclaration) members.get(i).accept(this, arg));
}
removeNulls(members);
}
return n;
}