I have some java code which reads text files, adds the contents to a vector and then prints these points to screen using a graph windower.
I have three pointdata.txt files, pointdata1.txt, pointdata2.txt and pointdata3.txt.
The problem i am having is that, even when i change the input file in my driver to pointdata1 or pointdata2, it still runs for pointdata3. I have ensured that there are no occurences of pointdata3 anywhere else in the code. It only appears twice, but i have made sure it is the same.
I have checked the files themselves, they are different. Checked and checked and checked the pathnames, they are different!
Even when i comment out every System.out.println() in the entire code, it still prints everything!
It is asif the code is no longer refereing the the text files, or even running, eclipse just keeps printing what was previously added to the viewport?
Here is the code from my driver:
import java.util.*;
public class PointDriver {
private PointField pointfield;
// testing
public void doAllTests() throws Exception{
this.test1();
this.test2();
}
// Display all points in the file
public void test1() throws Exception{
SimpleIO sIO = new SimpleIO();
System.out.println("Contents of Point File: ");
sIO.displayFile("pointdata1.txt");
//sIO.displayFile("pointdata2.txt");
//sIO.displayFile("pointdata3.txt");
System.out.println();
}
// Load points from a file into a vector and echo them back to the screen
// This uses the StringTokenizer to split the lines into two Strings, then
// uses the Point class to assign the two Strings to x,y double variables
// which form Points. Within the same loop, the points are also displayed
// in a window using the Graph Window class. Maximum x and y values are used
// to determine the dimensions of the GraphWindow, adding 10 units to each
// value to provide a border.
public void test2() throws Exception{
System.out.println("Contents of Point File: ");
System.out.println();
System.out.println("Points are Displayed in a Graph Window");
System.out.println();
Vector lines;
lines = pointfield.getlines("pointdata1.txt");
//lines = pointfield.getlines("pointdata2.txt");
//lines = pointfield.getlines("pointdata3.txt");
Iterator IT;
IT = lines.iterator();
Vector v;
v = new Vector();
double maxX, maxY;
PointField pointfield;
pointfield = new PointField();
GraphWindow gw;
gw = new GraphWindow();
while (IT.hasNext()) {
StringTokenizer st;
String ID = (String)IT.next();
st = new StringTokenizer(ID);
double x = Double.parseDouble(st.nextToken());
double y = Double.parseDouble(st.nextToken());
Point p;
p = new Point(x,y);
v.addElement(p);
int i = v.size();
System.out.println("Point ID: " +i+ " X: "+x+", Y: "+y);
gw.plotPoint(x, y);
}
this.pointfield = new PointField(v);
maxX = this.pointfield.findMaxXPoint();
maxY = this.pointfield.findMaxYPoint();
int width = (int)maxX + 10;
int height = (int)maxY + 10;
gw.setMap(width, height);
}
// Short main method to kick of all tests sequence in doAllTests method
public static void main(String[] args) throws Exception {
PointFieldDriver pfd;
pfd = new PointFieldDriver();
pfd.doAllTests();
}
}
It looks like Eclipse is running an old version of your class file. I'm gathering this as you said that you commented out the printlns, but the output is still displaying.
A few things to check:
In the menu, make sure that Project > Build Automatically is set. If that isn't set, set it, and your problem should be solved.
See whether the timestamp on your class file is changing when you change the source. If it isn't, then Eclipse isn't recompiling it for some reason. You can find the class file probably under the bin folder (if you are using the Eclipse project defaults).
If you find the timestamp is old, try removing the bin folder from outside of Eclipse. Next, right-click on the project and select refresh. Finally, select Project > Clean. This should cause the code to be recompiled into a new class file.
Related
I have a file shapes.txt that has the following data:
Circle:15;
Rectangle:5,8;
Triangle:4,10,10;
In my Java program, I have an interface Shapes and I should use it for the calculation of the area of each shape (the interface contains one method calcArea()). I should read the file, and then create an array of objects and invoke the method calcArea for each object, so that it will calculate the areas (polymorphism).
I didn't know how to achieve that, so, this is the code I have written for reading the data from the file (I think it's not a good practice...):
in = new BufferedReader(new FileReader(new File(loc)));
String line = in.readLine();
StringBuffer buf = new StringBuffer(line);
String s1 = buf.substring(buf.lastIndexOf(":") + 1);
if (line.contains("Circle")) {
Circle circle = new Circle(Integer.parseInt(s1));
}
For the Rectangle:
else if (line.contains("Rectangle")) {
String[] a = ((line.substring(line.lastIndexOf(":") + 1)).split(","));
int arf = Integer.parseInt(a[0]);
int ars = Integer.parseInt(a[1]);
Rectangle rect = new Rectangle(arf, ars);
}
Maybe I need to create a different method that will return an object of type Shapes, but if I start that way I don't know how to read the values from the file, so that I'll give them to the constructor of each object of type Shapes.
I would be grateful for any given opinions and help.
How would I write "if sticker1 is placed and in the array" then... My goal is for the sticker to be placed and entered into the array as a name with coordinates then saved to a save.txt file. From there, I can click a load button and it will load the sticker and place it at the exact coordinates.
if (hatSoundPlay){ //if hatSoundPlay is true
hatsound.play(); //and a hatsound will play
sticker sticker1 = new sticker();//creates a new sticker1
sticker1.arraysticker(hatPicture, "hat.png", clickX, clickY);//places sticker
image ++;//increments image by 1
arraysticker[image] = sticker1;//puts sticker 1 into the array
Then for the save code.
else if (savePicture.isPointInElement(clickX, clickY)){
FileWriter fw = new FileWriter("save.txt");
for (int i = 0; i < arraysticker.length; i++);
if (sticker1.images[images].isShowing){
//I want the iff statement ^^ to say if sticker if placed in the array
//fw.write name and coords into save.txt
}
}
You should have class Stricker, which should looks like this :
public class Sticker(){
private String name;
private int X;
private int Y;
//There You should place Getters and Setters to variables name,X and Y
//... and your method named 'arraysticker(Object, Image, Integer, Integer)'
}
... next step is to create the correct type of list ArrayList<Sticker> list = new ArrayList<>();
I'll do this like that:
if(hatSoundPlay){
hatsound.play();
Sticker sticker1 = new Sticker();
sticker1.arraysticker(hatPicture, "hat.png", clickX, clickY);
image ++;
list[image] = sticker1;
}
and finally at your save code should looks like:
else if (savePicture.isPointInElement(clickX, clickY)){
FileWriter fw = new FileWriter("save.txt");
for(int i = 0; i < list.length; i++){
if(list[i]!=null){ //if object exist, do...
String name;
int x,y;
name = list.getName();
x = list.getX();
y = list.getY();
fw.write(name + " " + x + " " + y + "\n"); //write all elements to file separated with space and symbol of new line
}
}
fw.close(); //necessary to close connection with file
}
To solve this problem I need rest of code, because I don't have information about Yours methods and otherr arrays like images
As far as you need save and restore objects, I suggest you to use some ready solutions like Jackson library. This simplifies the logic and you can control what to save and restore just by using annotations.
There are a lot of examples. So you get your class, mark properties with annotations and that is. Jackson lib will do everything for you. Take a look this tutorial: http://www.journaldev.com/2324/jackson-json-processing-api-in-java-example-tutorial
I'm finishing up a GUI program that'll act as an online ordering menu for a restuarant, however I seem to be having two problems..
My calculate handler method seems to just freeze the entire java applet. It doesnt show any error or anything as well it just freezes. heres the event handler:
ArrayList<Double> yourOrderPrices = new ArrayList<Double>();
ArrayList<String>yourOrderName = new ArrayList<String>();
ArrayList<String> specifications = new ArrayList<String>();
Iterator<Double> it1 = yourOrderPrices.iterator();
private void calcButtonActionPerformed(java.awt.event.ActionEvent evt) {
int x = 0;
double temp;
while(it1.hasNext()){
temp = yourOrderPrices.get(x);
orderTotal += temp;
}
subTotalLabel.setText("Sub Total: " + orderTotal);
totalPriceLabel.setText("Tax Rate: " + orderTotal / TAX_RATE);
totalPriceLabel.setText("Total: " + (orderTotal / TAX_RATE) + orderTotal);
//Reset Variable
orderTotal = 0;
}
Basically what this is supposed to do is calculate the sub total by adding all of the prices in the yourOrderPrices ArrayList, its supposed to divide by the tax rate and display it, and its supposed to add the tax rate for a Total Price. The variables inside are representing prices for food and are doubles.
But everytime I press the button the entire program freezes.
Also, i'm trying to wrap the text in 2 textArea boxes, but everytime I try and call the method setLineWrap(true); it shows up on eclipse as not ablee to do that. Heres the two Text areas im trying to put it in:
detailTextArea.setEditable(false);
detailPanel.add(detailTextArea, java.awt.BorderLayout.CENTER);
and
orderTextArea.setEditable(false);
eastPanel.add(orderTextArea);
Use a for each instead.
double orderTotal = 0;
for(Double price : yourOrderPrices) {
orderTotal += price;
}
As for setLineWrap(true), exactly what does Eclipse say?
Solution:
I installed java and Eclipse and tried it out by myself. I created a JTextArea and set the lineWrap to true and it works without complaints. Have you checked that you imported javax.swing.JTextArea and not something else?
My code for reference:
import javax.swing.JTextArea;
public class Main {
public static void main(String[] args) {
JTextArea area = new JTextArea();
area.setLineWrap(true);
}
}
I have a program that runs and doesnt throw a runtime error in eclipse which should set up an image to a JButton at the end of the program as the result but the image is never put on to the button. The program worked fine in DrJava but I transferred to eclipse in order to make a jar file.
I saw in another question posted that someone had a similar problem that said the images should be put into the project directory not the src directory but it didnt explain how to actually fix the problem... im new to eclipse so if someone could help me out id appreciate it thanks.
here is how the images are set up in my code:
public void tempSelection70 (int fRate, int wbTemp, int rcTons, int a, int r)
{
for (int model = 0; model < 7; model++)
{
MyArray y = new MyArray(tons70FCharts[model], "t");
int[][] x = y.getArray();
int t = x[a][r];
if (rcTons == t)
{
tableButton = new JButton(new ImageIcon(tablesFor70[model], tablesFor70[model]));
break;
}
else
{
tableButton = new JButton(new ImageIcon("CANNOT_FIND_MODEL.GIF", "SCROLL"));
}
}
for (int model = 0; model < 7; model++)
{
MyArray y = new MyArray(flow70FCharts[model], "f");
int[][] x = y.getArray();
int t = x[a][r];
if (fRate == t)
{
tableButton = new JButton(new ImageIcon(tablesFor70[model], tablesFor70[model]));
break;
}
else
{
tableButton = new JButton(new ImageIcon("CANNOT_FIND_MODEL.GIF", "SCROLL"));
}
}
}
You're passing a file name as argument. I guess this file name is a relative file name. So the file is relative to the directory from which your IDE launches the java command to execute your application: the working directory.
This directory can be changed from the run configuration in Eclipse, under the tab "Arguments". But this is probably not what you want. The icons should certainly be bundled with your application, and loaded with the class loader. Put them under a package in your source folder. Eclipse will copy them to the output directory, along with the compiled classes. And if you generate a jhar for your app, they will be bundled in the jar with your classes. Once this is done, you just have to use the constructor taking a URL as argument, and pass
SomeClassOfYourApp.getResource("/the/package/of/the/image.png")
as this URL argument.
This will allow you to bundle the icons with the app easily, and will load the icons whatever the working directory is.
I wrote a Minesweeper game that worked fine last week, but now when I try to run it, I get a NullPointerException, and I didn't change the code.
There is one thing that probably is the cause: I installed Ubuntu on my laptop 2 days ago and I tried to copy my user folder from Windows to my Ubuntu desktop. I stupidly used the "move here" option because I thought that would copy the folder (there wasn't any copy option). But when I logged back into Windows, it was as if I were a new user. So I copied that folder from my Ubuntu desktop back to Windows and fortunately all my files were back.
Here is my code. It does say MinesweeperBoard.show() is deprecated (that class extends JFrame), but the NullPointerException occurs at board = new MinesweeperBoard(9, 9, 10); even though I declared board before.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Do you want to play beginner (b), intermediate (i), or EXPERT (e)?");
String input = in.next();
MinesweeperBoard board;
if (input.equals("b"))
board = new MinesweeperBoard(9, 9, 10);
else if (input.equals("i"))
board = new MinesweeperBoard(16, 16, 40);
else if (input.equals("e"))
board = new MinesweeperBoard(30, 16, 99);
else
board = new MinesweeperBoard(30, 30, 100);
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
board.show();
}
Further down in the stack trace, it points to this line of code in another class:
icons[0] = new ImageIcon(this.getClass().getClassLoader().getResource("0.gif"));
The stack trace line after that is at javax.swing.ImageIcon.<init>(Unknown Source)
I tried build all and clean, but doing those didn't fix anything.
Edited
Entire stack trace:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at MBox.<init>(MBox.java:25)
at MinesweeperBoard.<init>(MinesweeperBoard.java:50)
at MinesweeperGame.main(MinesweeperGame.java:16)
This is from MinesweeperBoard:
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
boxes[i][j] = new MBox(i, j); //Line 50
boxes[i][j].setBounds(i * SIZE + 5, j * SIZE + 65, SIZE, SIZE);
boxes[i][j].putSelfInBoard(this);
cont.add(boxes[i][j]);
}
}
This is from MBox:
icons = new ImageIcon[12];
icons[0] = new ImageIcon(this.getClass().getClassLoader().getResource("0.gif")); //Line 25
icons[1] = new ImageIcon(this.getClass().getClassLoader().getResource("1.gif"));
icons[2] = new ImageIcon(this.getClass().getClassLoader().getResource("2.gif"));
...
The NullPointerException is probably occurring because this.getClass().getClassLoader().getResource("0.gif") is returning null.
It sounds like the file "0.gif" isn't in your jar file (or wherever), so getClass().getClassLoader().getResource("0.gif") is returning null. That's then being passed to the ImageIcon constructor, which is throwing an exception.
its also possible the files have other rights after you have copied the files with ubuntu.
so you should check the rights of the files and wether they actually exits.