Help with dynamic programming, knapsack problem
Hi, I wrote a code to solve the knapsack 0-1 problem by dynamic programming. At a certain point, around 30 max capacity, the code stops adding new values based on the incrementing max capacity and item values. I have no idea why, it finds the correct solution until the max capacity of the knapsack gets to around 30, and then the answers are screwed up. My code is below. Thanks in advance for the help!
public Knapsack packDP(int capacity)
//initialize 2d array
Knapsack [][] knapsackSolutions = new Knapsack[safe.size() + 1][capacity + 1];
//fill 1st row and 1st columns with empty knapsacks as sentinel values
for (int i = 0; i <= safe.size(); i++)
knapsackSolutions[0] = new Knapsack();
for (int j = 0; j <= capacity; j++)
knapsackSolutions[0][j] = new Knapsack();
//each row of the 2d array represents an item. for loop to calculate solutions for each item
for (int itemNum = 1; itemNum <= safe.size(); itemNum++)
Item currentItem = safe.get(itemNum - 1);
//get optimal solutions for each weight value in the current item row
for (int weight = 0; weight <= capacity; weight++)
if (currentItem.size <= weight)
System.out.println("weight = " + weight);
if ( (currentItem.value + knapsackSolutions[itemNum - 1][weight - currentItem.size].value) >
knapsackSolutions[itemNum - 1][weight].value )
//create a new knapsack with the new item
knapsackSolutions[itemNum][weight] = new Knapsack(knapsackSolutions[itemNum - 1][weight - currentItem.size], currentItem);
else
knapsackSolutions[itemNum][weight] = new Knapsack(knapsackSolutions[itemNum - 1][weight]);
else
knapsackSolutions[itemNum][weight] = new Knapsack(knapsackSolutions[itemNum - 1][weight]);
count++;
//return last item of the 2d array, which is the optimal solution for the capacity
return knapsackSolutions[safe.size()][capacity];
I've been debugging forever and I can't figure out where I went wrong. The test driver for this is:
public class ThiefDriver
public static void main(String[] args) {
/// Set up experiment:
int INITIAL = 10 ;
int INCREMENT = 10 ;
/// Create objects with add(NAME,SIZE,VALUE):
Thief thief = new Thief();
thief.add("A",3,4) ;
thief.add("B",4,5) ;
thief.add("C",7,10) ;
thief.add("D",8,11) ;
thief.add("E",9,13) ;
/// Run experiment:
Thief.Knapsack knapsack;
for (int capacity=INITIAL ; capacity <= thief.safe.capacity ; capacity+=INCREMENT) {
System.out.println("Capacity = " + capacity) ;
thief.count = 0 ;
knapsack = thief.packDP(capacity) ;
System.out.println( " DP value/COUNT: " + knapsack.value + " " + thief.count ) ;
}
Similar Messages
-
Help with add file name problem with Photoshop CS4
Frustrating problem: Help with add file name problem with Photoshop CS4. What happens is this. When I am in PS CS4 or CS3 and run the following script it runs fine. When I am in Bridge and go to tools/photoshop/batch and run the same script it runs until it wants interaction with preference.rulerunits. How do I get it to quit doing this so I can run in batch mode? Any help is appreciated. HLower
Script follows:
// this script is another variation of the script addTimeStamp.js that is installed with PS7
//Check if a document is open
if ( documents.length > 0 )
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.INCHES;
try
var docRef = activeDocument;
// Create a text layer at the front
var myLayerRef = docRef.artLayers.add();
myLayerRef.kind = LayerKind.TEXT;
myLayerRef.name = "Filename";
var myTextRef = myLayerRef.textItem;
//Set your parameters below this line
//If you wish to show the file extension, change the n to y in the line below, if not use n.
var ShowExtension = "n";
// Insert any text to appear before the filename, such as your name and copyright info between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextBefore = "Lower© ";
// Insert any text to appear after the filename between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextAfter = " ";
// Set font size in Points
myTextRef.size = 10;
//Set font - use GetFontName.jsx to get exact name
myTextRef.font = "Arial";
//Set text colour in RGB values
var newColor = new SolidColor();
newColor.rgb.red = 0;
newColor.rgb.green = 0;
newColor.rgb.blue = 0;
myTextRef.color = newColor;
// Set the position of the text - percentages from left first, then from top.
myTextRef.position = new Array( 10, 99);
// Set the Blend Mode of the Text Layer. The name must be in CAPITALS - ie change NORMAL to DIFFERENCE.
myLayerRef.blendMode = BlendMode.NORMAL;
// select opacity in percentage
myLayerRef.opacity = 100;
// The following code strips the extension and writes tha text layer. fname = file name only
di=(docRef.name).indexOf(".");
fname = (docRef.name).substr(0, di);
//use extension if set
if ( ShowExtension == "y" )
fname = docRef.name
myTextRef.contents = TextBefore + " " + fname + " " + TextAfter;
catch( e )
// An error occurred. Restore ruler units, then propagate the error back
// to the user
preferences.rulerUnits = originalRulerUnits;
throw e;
// Everything went Ok. Restore ruler units
preferences.rulerUnits = originalRulerUnits;
else
alert( "You must have a document open to add the filename!" );you might want to try the scripting forum howard:
http://www.adobeforums.com/webx?13@@.ef7f2cb -
Help with Paint program.
Hello. I am somewhat new to Java and I was recently assigned to do a simple paint program. I have had no trouble up until my class started getting into the graphical functions of Java. I need help with my program. I am supposed to start off with a program that draws lines and changes a minimum of 5 colors. I have the line function done but my color change boxes do not work and I am able to draw inside the box that is supposed to be reserved for color buttons. Here is my code so far:
// Lab13110.java
// The Lab13 program assignment is open ended.
// There is no provided student version for starting, nor are there
// any files with solutions for the different point versions.
// Check the Lab assignment document for additional details.
import java.applet.Applet;
import java.awt.*;
public class Lab13110 extends Applet
int[] startX,startY,endX,endY;
int currentStartX,currentStartY,currentEndX,currentEndY;
int lineCount;
Rectangle red, green, blue, yellow, black;
int numColor;
Image virtualMem;
Graphics gBuffer;
int rectheight,rectwidth;
public void init()
startX = new int[100];
startY = new int[100];
endX = new int[100];
endY = new int[100];
lineCount = 0;
red = new Rectangle(50,100,25,25);
green = new Rectangle(50,125,25,25);
blue = new Rectangle(50,150,25,25);
yellow = new Rectangle(25,112,25,25);
black = new Rectangle(25,137,25,25);
numColor = 0;
virtualMem = createImage(100,600);
gBuffer = virtualMem.getGraphics();
gBuffer.drawRect(0,0,100,600);
public void paint(Graphics g)
for (int k = 0; k < lineCount; k++)
g.drawLine(startX[k],startY[k],endX[k],endY[k]);
g.drawLine(currentStartX,currentStartY,currentEndX,currentEndY);
g.setColor(Color.red);
g.fillRect(50,100,25,25);
g.setColor(Color.green);
g.fillRect(50,125,25,25);
g.setColor(Color.blue);
g.fillRect(50,150,25,25);
g.setColor(Color.yellow);
g.fillRect(25,112,25,25);
g.setColor(Color.black);
g.fillRect(25,137,25,25);
switch (numColor)
case 1:
g.setColor(Color.red);
break;
case 2:
g.setColor(Color.green);
break;
case 3:
g.setColor(Color.blue);
break;
case 4:
g.setColor(Color.yellow);
break;
case 5:
g.setColor(Color.black);
break;
case 6:
g.setColor(Color.black);
break;
g.setColor(Color.black);
g.drawRect(0,0,100,575);
public boolean mouseDown(Event e, int x, int y)
currentStartX = x;
currentStartY = y;
if(red.inside(x,y))
numColor = 1;
else if(green.inside(x,y))
numColor = 2;
else if(blue.inside(x,y))
numColor = 3;
else if(yellow.inside(x,y))
numColor = 4;
else if(black.inside(x,y))
numColor = 5;
else
numColor = 6;
repaint();
return true;
public boolean mouseDrag(Event e, int x, int y)
int Rectheight = 500;
int Rectwidth = 900;
currentEndX = x;
currentEndY = y;
Rectangle window = new Rectangle(0,0,900,500);
//if (window.inside(Rectheight,Rectwidth))
repaint();
return true;
public boolean mouseUp(Event e, int x, int y)
int Rectheight = 500;
int Rectwidth = 900;
startX[lineCount] = currentStartX;
startY[lineCount] = currentStartY;
endX[lineCount] = x;
endY[lineCount] = y;
lineCount++;
Rectangle window = new Rectangle(0,0,900,500);
if (window.inside(Rectheight,Rectwidth))
repaint();
return true;
public void Rectangle(Graphics g, int x, int y)
g.setColor(Color.white);
Rectangle screen = new Rectangle(100,0,900,600);
}If anyone could point me in the right direction of how to go about getting my buttons to work and fixing the button box, I would be greatly appreciative. I just need to get a little bit of advice and I think I should be good after I get this going.
Thanks.This isn't in any way a complete solution, but I'm posting code for a mouse drag outliner. This may be preferable to how you are doing rectangles right now
you are welcome to use and modify this code but please do not change the package and make sure that you tell your teacher where you got it from
MouseDragOutliner.java
package tjacobs.ui;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
* See the public static method addAMouseDragOutliner
public class MouseDragOutliner extends MouseAdapter implements MouseMotionListener {
public static final BasicStroke DASH_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL, 10.0f, new float[] {8, 8}, 0);
private boolean mUseMove = false;
private Point mStart;
private Point mEnd;
private Component mComponent;
private MyRunnable mRunner= new MyRunnable();
private ArrayList mListeners = new ArrayList(1);
public MouseDragOutliner() {
super();
public MouseDragOutliner(boolean useMove) {
this();
mUseMove = useMove;
public void mouseDragged(MouseEvent me) {
doMouseDragged(me);
public void mousePressed(MouseEvent me) {
mStart = me.getPoint();
public void mouseEntered(MouseEvent me) {
mStart = me.getPoint();
public void mouseReleased(MouseEvent me) {
Iterator i = mListeners.iterator();
Point end = me.getPoint();
while (i.hasNext()) {
((OutlineListener)i.next()).mouseDragEnded(mStart, end);
//mStart = null;
public void mouseMoved(MouseEvent me) {
if (mUseMove) {
doMouseDragged(me);
public void addOutlineListener(OutlineListener ol) {
mListeners.add(ol);
public void removeOutlineListener(OutlineListener ol) {
mListeners.remove(ol);
private class MyRunnable implements Runnable {
public void run() {
Graphics g = mComponent.getGraphics();
if (g == null) {
return;
Graphics2D g2 = (Graphics2D) g;
Stroke s = g2.getStroke();
g2.setStroke(DASH_STROKE);
int x = Math.min(mStart.x, mEnd.x);
int y = Math.min(mStart.y, mEnd.y);
int w = Math.abs(mEnd.x - mStart.x);
int h = Math.abs(mEnd.y - mStart.y);
g2.setXORMode(Color.WHITE);
g2.drawRect(x, y, w, h);
g2.setStroke(s);
public void doMouseDragged(MouseEvent me) {
mEnd = me.getPoint();
if (mStart != null) {
mComponent = me.getComponent();
mComponent.repaint();
SwingUtilities.invokeLater(mRunner);
public static MouseDragOutliner addAMouseDragOutliner(Component c) {
MouseDragOutliner mdo = new MouseDragOutliner();
c.addMouseListener(mdo);
c.addMouseMotionListener(mdo);
return mdo;
public static interface OutlineListener {
public void mouseDragEnded(Point start, Point finish);
public static void main(String[] args) {
JFrame f = new JFrame("MouseDragOutliner Test");
Container c = f.getContentPane();
JPanel p = new JPanel();
//p.setBackground(Color.BLACK);
c.add(p);
addAMouseDragOutliner(p);
f.setBounds(200, 200, 400, 400);
f.addWindowListener(new WindowClosingActions.Exit());
f.setVisible(true);
} -
Is it possible to make a search help with dynamic selection table?
Hi Experts,
Is it possible to create search helps with dynamic seletion tables means
i dont know the selection table names at the time of creation of search help.
These tables will be determined at runtime.
if yes, Please give an idea how to create and pass the table names at runtime.
Thanks
Yogesh GuptaHi Yogesh,
Create and fill your itab and show it with FM F4IF_INT_TABLE_VALUE_REQUEST
CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
EXPORTING
retfield = 'field to return from itab'
dynpprog = sy-repid
dynpnr = sy-dynnr
dynprofield = 'field on your screen to be filled'
stepl = sy-stepl
window_title = 'some text'
value_org = 'S'
TABLES
value_tab = itab
EXCEPTIONS
parameter_error = 1
no_values_found = 2
OTHERS = 3.
Darley -
Who can help me :)--a problem with java program(reset problem in java )
I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
correspond to the black square.The code like this,first one is shapes:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class shapes extends JFrame {
private JPanel buttonPanel; // panel for buttons
private DrawPanel myPanel; // panel for shapes
private JButton resetButton;
private JComboBox colorComboBox;
private JRadioButton circleButton, squareButton;
private ButtonGroup radioGroup;
private JCheckBox filledButton;
private JSlider sizeSlider;
private boolean isShow;
private int shape;
private boolean isFill=true;
private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
"green", "lightgray", "magenta", "orange",
"pink", "red", "white", "yellow"}; // color names list in ComboBox
private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
Color.gray, Color.green, Color.lightGray, Color.magenta,
Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
public shapes() {
super("Draw Shapes");
// creat custom drawing panel
myPanel = new DrawPanel(); // instantiate a DrawPanel object
myPanel.setBackground(Color.white);
// set up resetButton
// register an event handler for resetButton's ActionEvent
resetButton = new JButton ("reset");
resetButton.addActionListener(
// anonymous inner class to handle resetButton events
new ActionListener() {
// draw a black filled square shape after clicking resetButton
public void actionPerformed (ActionEvent event) {
// call DrawPanel method setShowStatus and pass an parameter
// to decide if show the shape
myPanel.setShowStatus(true);
isShow = myPanel.getShowStatus();
shape = DrawPanel.SQUARE;
// call DrawPanel method setShape to indicate shape to draw
myPanel.setShape(shape);
// call DrawPanel method setFill to indicate to draw a filled shape
myPanel.setFill(true);
// call DrawPanel method draw
myPanel.draw();
myPanel.setFill(true);
myPanel.setForeground(Color.black);
}// end anonymous inner class
);// end call to addActionListener
// set up colorComboBox
// register event handlers for colorComboBox's ItemEvent
colorComboBox = new JComboBox(colorNames);
colorComboBox.setMaximumRowCount(5);
colorComboBox.addItemListener(
// anonymous inner class to handle colorComboBox events
new ItemListener() {
// select shape's color
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED)
// call DrawPanel method setForeground
// and pass an element value of colors array
myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
myPanel.draw();
}// end anonymous inner class
); // end call to addItemListener
// set up a pair of RadioButtons
// register an event handler for RadioButtons' ItemEvent
squareButton = new JRadioButton ("Square", true);
circleButton = new JRadioButton ("Circle", false);
radioGroup = new ButtonGroup();
radioGroup.add(squareButton);
radioGroup.add(circleButton);
squareButton.addItemListener(
// anonymous inner class to handle squareButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
shape = DrawPanel.SQUARE;
myPanel.setShape(shape);
myPanel.draw();
}// end anonymous inner class
);// end call to addItemListener
circleButton.addItemListener(
// anonymous inner class to handle circleButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
shape = DrawPanel.CIRCLE;
myPanel.setShape(shape);
myPanel.draw();
else
System.out.println("Please click Reset button first");
}// end anonymous inner class
);// end call to addItemListener
// set up filledButton
// register an event handler for filledButton's ItemEvent
filledButton = new JCheckBox("Filled", true);
filledButton.addItemListener(
// anonymous inner class to handle filledButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
if (event.getStateChange() == ItemEvent.SELECTED) {
isFill=true;
myPanel.setFill(isFill);
myPanel.draw();
else {
isFill=false;
myPanel.setFill(isFill);
myPanel.draw();
else
System.out.println("Please click Reset button first");
}// end anonymous inner class
);// end call to addItemListener
// set up sizeSlider
// register an event handler for sizeSlider's ChangeEvent
sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
sizeSlider.setMajorTickSpacing(10);
sizeSlider.setPaintTicks(true);
sizeSlider.addChangeListener(
// anonymous inner class to handle sizeSlider events
new ChangeListener() {
public void stateChanged(ChangeEvent event) {
myPanel.setShapeSize(sizeSlider.getValue());
myPanel.draw();
}// end anonymous inner class
);// end call to addChangeListener
// set up panel containing buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
buttonPanel.add(resetButton);
buttonPanel.add(filledButton);
buttonPanel.add(colorComboBox);
JPanel radioButtonPanel = new JPanel();
radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
radioButtonPanel.add(squareButton);
radioButtonPanel.add(circleButton);
buttonPanel.add(radioButtonPanel);
// attach button panel & draw panel to content panel
Container container = getContentPane();
container.setLayout(new BorderLayout(10,10));
container.add(myPanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.EAST);
container.add(sizeSlider, BorderLayout.SOUTH);
setSize(500, 400);
setVisible(true);
public static void main(String args[]) {
shapes application = new shapes();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}second one is drawpanel:
import java.awt.*;
import javax.swing.*;
public class DrawPanel extends JPanel {
public final static int CIRCLE = 1, SQUARE = 2;
private int shape;
private boolean fill;
private boolean showStatus;
private int shapeSize = 100;
private Color foreground;
// draw a specified shape
public void paintComponent (Graphics g){
super.paintComponent(g);
// find center
int x=(getSize().width-shapeSize)/2;
int y=(getSize().height-shapeSize)/2;
if (shape == CIRCLE) {
if (fill == true){
g.setColor(foreground);
g.fillOval(x, y, shapeSize, shapeSize);
else{
g.setColor(foreground);
g.drawOval(x, y, shapeSize, shapeSize);
else if (shape == SQUARE){
if (fill == true){
g.setColor(foreground);
g.fillRect(x, y, shapeSize, shapeSize);
else{
g.setColor(foreground);
g.drawRect(x, y, shapeSize, shapeSize);
// set showStatus value
public void setShowStatus (boolean s) {
showStatus = s;
// return showstatus value
public boolean getShowStatus () {
return showStatus;
// set fill value
public void setFill(boolean isFill) {
fill = isFill;
// set shape value
public void setShape(int shapeToDraw) {
shape = shapeToDraw;
// set shapeSize value
public void setShapeSize(int newShapeSize) {
shapeSize = newShapeSize;
// set foreground value
public void setForeground(Color newColor) {
foreground = newColor;
// repaint DrawPanel
public void draw (){
if(showStatus == true)
repaint();
}If any kind people who can help me.
many thanks to you!4 widgets???
maybe this is what you mean.
add this inside your actionPerformed method for the reset action
squareButton.setSelected(true);
colorComboBox.setSelectedIndex(0);
if not be more clear in your post. -
Need some help with a program Please.
Well, im new here, im new to java, so i need your help, i have to make a connect four program, my brother "Kind of" helped me and did a program for me, but the problem is i cant use some of those commands in the program and i have to replace them with what ive learned, so i will post the program and i will need your help to modify it for me.
and for these programs, also i want help for:
They have errors and i cant fix'em
the commands that i've leaned:
If statements, for loops, while loops,do while, strings, math classes, swithc statement, else if,logical operators,methods, one and two dimensional arrays.
Thanx in advance,
truegunner
// Fhourstones 3.0 Board Logic
// Copyright 2000-2004 John Tromp
import java.io.*;
class Connect4 {
static long color[]; // black and white bitboard
static final int WIDTH = 7;
static final int HEIGHT = 6;
// bitmask corresponds to board as follows in 7x6 case:
// . . . . . . . TOP
// 5 12 19 26 33 40 47
// 4 11 18 25 32 39 46
// 3 10 17 24 31 38 45
// 2 9 16 23 30 37 44
// 1 8 15 22 29 36 43
// 0 7 14 21 28 35 42 BOTTOM
static final int H1 = HEIGHT+1;
static final int H2 = HEIGHT+2;
static final int SIZE = HEIGHT*WIDTH;
static final int SIZE1 = H1*WIDTH;
static final long ALL1 = (1L<<SIZE1)-1L; // assumes SIZE1 < 63
static final int COL1 = (1<<H1)-1;
static final long BOTTOM = ALL1 / COL1; // has bits i*H1 set
static final long TOP = BOTTOM << HEIGHT;
int moves[],nplies;
byte height[]; // holds bit index of lowest free square
public Connect4()
color = new long[2];
height = new byte[WIDTH];
moves = new int[SIZE];
reset();
void reset()
nplies = 0;
color[0] = color[1] = 0L;
for (int i=0; i<WIDTH; i++)
height[i] = (byte)(H1*i);
public long positioncode()
return 2*color[0] + color[1] + BOTTOM;
// color[0] + color[1] + BOTTOM forms bitmap of heights
// so that positioncode() is a complete board encoding
public String toString()
StringBuffer buf = new StringBuffer();
for (int i=0; i<nplies; i++)
buf.append(1+moves);
buf.append("\n");
for (int w=0; w<WIDTH; w++)
buf.append(" "+(w+1));
buf.append("\n");
for (int h=HEIGHT-1; h>=0; h--) {
for (int w=h; w<SIZE1; w+=H1) {
long mask = 1L<<w;
buf.append((color[0]&mask)!= 0 ? " @" :
(color[1]&mask)!= 0 ? " 0" : " .");
buf.append("\n");
if (haswon(color[0]))
buf.append("@ won\n");
if (haswon(color[1]))
buf.append("O won\n");
return buf.toString();
// return whether columns col has room
final boolean isplayable(int col)
return islegal(color[nplies&1] | (1L << height[col]));
// return whether newboard lacks overflowing column
final boolean islegal(long newboard)
return (newboard & TOP) == 0;
// return whether newboard is legal and includes a win
final boolean islegalhaswon(long newboard)
return islegal(newboard) && haswon(newboard);
// return whether newboard includes a win
final boolean haswon(long newboard)
long y = newboard & (newboard>>HEIGHT);
if ((y & (y >> 2*HEIGHT)) != 0) // check diagonal \
return true;
y = newboard & (newboard>>H1);
if ((y & (y >> 2*H1)) != 0) // check horizontal -
return true;
y = newboard & (newboard>>H2); // check diagonal /
if ((y & (y >> 2*H2)) != 0)
return true;
y = newboard & (newboard>>1); // check vertical |
return (y & (y >> 2)) != 0;
void backmove()
int n;
n = moves[--nplies];
color[nplies&1] ^= 1L<<--height[n];
void makemove(int n)
color[nplies&1] ^= 1L<<height[n]++;
moves[nplies++] = n;
public static void main(String argv[])
Connect4 c4;
String line;
int col=0, i, result;
long nodes, msecs;
c4 = new Connect4();
c4.reset();
BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
for (;;) {
System.out.println("position " + c4.positioncode() + " after moves " + c4 + "enter move(s):");
try {
line = dis.readLine();
} catch (IOException e) {
System.out.println(e);
System.exit(0);
return;
if (line == null)
break;
for (i=0; i < line.length(); i++) {
col = line.charAt(i) - '1';
if (col >= 0 && col < WIDTH && c4.isplayable(col))
c4.makemove(col);
By the way im using Ready to program for the programming.You can't really believe that his brother did this
for him...I did miss that copyright line at the beginning when
I first looked it over, but you know, if it had been
his brother, I'd be kinda impressed. This wasn't a
25 line program. It actually would have required
SOME thought. I doubt my brother woulda done that
for me (notwithstanding the fact that I wouldn't need
help for that program, and my brother isn't a
programmer).I originally missed the comments at the top but when I saw the complexity of what was written then I knew that it was too advanced for a beginner and I relooked through the code and saw the comments. -
Hello I need help with the following code for a Payroll program.
//CheckPoint: Payroll Program Part 3
//Java Programming IT215
//Arianne Gallegos
//05/02/2007
//Payroll3.java
//Payroll program that calculates the weekly pay for an employee.
import java.util.Scanner; // program uses class Scanner
public class Payroll3
private string name;
private double rate;
private double hours;
// Constructor to store Employee Data
public EmployeeData( String nameOfEmployee, double hourlyRate, double hoursWorked )
name = nameOfEmployee;
rate = hourlyRate;
hours = hoursWorked;
} // end constructor
} //end class EmployeeData
// main method begins execution of java application
public static void main( String args[] )
System.out.println( "Welcome to the Payroll Program! " );
boolean quit = false; // This flag will control whether we exit the loop below
// Loop until user types "quit" as the employee name:
while (!quit)
// create scanner to obtain input from command window
Scanner input = new Scanner ( System.in );
System.out.println(); // outputs a blank line
System.out.print( "Please enter the employee name or quit to terminate program: " );
// prompt for and input employee name
String nameOfEmployee = input.nextLine(); // read what user has inputted
if ( nameOfEmployee.equals("quit")) // Check whether user indicated to quit program
System.out.println( "Program has ended" );
quit = true;
else
// User did not indicate to stop, so continue reading info for this iteration:
float hourlyRate; // first number to multiply
float hoursWorked; // second number to multiply
float product; // product of hourlyRate and hoursWorked
System.out.print( "Enter hourly rate: " ); // prompt
hourlyRate = input.nextFloat(); // read first number from user
while (hourlyRate <= 0) // prompt until a positive value is entered
System.out.print( "Hourly rate must be a positive value. " +
"Please enter the hourly rate again: " ); // prompt for positive value for hourly rate
hourlyRate = input.nextFloat(); // read first number again
System.out.print( "Enter hours worked: " ); // prompt
hoursWorked = input.nextFloat(); // read second number from user
while (hoursWorked <= 0) // prompt until a positive value is entered
System.out.print( "Hours worked must be a positive value. " +
"Please enter the hours worked again: " ); // prompt for positive value for hours worked
hoursWorked = input.nextFloat(); // read second number again
product = (float) hourlyRate * hoursWorked; // multiply the hourly rate by the hours worked
// Display output for this iteration
System.out.println(); // outputs a blank line
System.out.print( nameOfEmployee ); // display employee name
System.out.printf( "'s weekly pay is: $%,.2f\n", product); // display product
System.out.println(); // outputs a blank line
// Display ending message:
System.out.println( "Thank you for using the Payroll program!" );
System.out.println(); // outputs a blank line
} // end method main
} // end class Payroll3I am getting the following errors:
Payroll3.java:18: invalid method declaration; return type required
public EmployeeData( String nameOfEmployee, double hourlyRate, double hours
Worked )
^
Payroll3.java:28: class, interface, or enum expected
public static void main( String args[] )
^
Payroll3.java:33: class, interface, or enum expected
boolean quit = false; // This flag will control whether we exit the loop b
elow
^
Payroll3.java:36: class, interface, or enum expected
while (!quit)
^
Payroll3.java:42: class, interface, or enum expected
System.out.println(); // outputs a blank line
^
Payroll3.java:43: class, interface, or enum expected
System.out.print( "Please enter the employee name or quit to terminate p
rogram: " );
^
Payroll3.java:45: class, interface, or enum expected
String nameOfEmployee = input.nextLine(); // read what user has inputted
^
Payroll3.java:48: class, interface, or enum expected
if ( nameOfEmployee.equals("quit")) // Check whether user indicated to q
uit program
^
Payroll3.java:51: class, interface, or enum expected
quit = true;
^
Payroll3.java:52: class, interface, or enum expected
^
Payroll3.java:57: class, interface, or enum expected
float hoursWorked; // second number to multiply
^
Payroll3.java:58: class, interface, or enum expected
float product; // product of hourlyRate and hoursWorked
^
Payroll3.java:60: class, interface, or enum expected
System.out.print( "Enter hourly rate: " ); // prompt
^
Payroll3.java:61: class, interface, or enum expected
hourlyRate = input.nextFloat(); // read first number from user
^
Payroll3.java:64: class, interface, or enum expected
while (hourlyRate <= 0) // prompt until a positive value is entered
^
Payroll3.java:68: class, interface, or enum expected
hourlyRate = input.nextFloat(); // read first number again
^
Payroll3.java:69: class, interface, or enum expected
^
Payroll3.java:72: class, interface, or enum expected
hoursWorked = input.nextFloat(); // read second number from user
^
Payroll3.java:75: class, interface, or enum expected
while (hoursWorked <= 0) // prompt until a positive value is entered
^
Payroll3.java:79: class, interface, or enum expected
hoursWorked = input.nextFloat(); // read second number again
^
Payroll3.java:80: class, interface, or enum expected
^
Payroll3.java:86: class, interface, or enum expected
System.out.println(); // outputs a blank line
^
Payroll3.java:87: class, interface, or enum expected
System.out.print( nameOfEmployee ); // display employee name
^
Payroll3.java:88: class, interface, or enum expected
System.out.printf( "'s weekly pay is: $%,.2f\n", product); // display
product
^
Payroll3.java:89: class, interface, or enum expected
System.out.println(); // outputs a blank line
^
Payroll3.java:91: class, interface, or enum expected
^
Payroll3.java:96: class, interface, or enum expected
System.out.println(); // outputs a blank line
^
Payroll3.java:98: class, interface, or enum expected
} // end method main
^
The problem I am having is getting the constructor to work with the rest of the program can someone please point out to me how to correct this. I have read my textbook as well as tutorials but I just don't seem to get it right. Please help.
P.S. I have never taken a programming class before so please be kind.Ok, I changed the name of the constructor:
//CheckPoint: Payroll Program Part 3
//Java Programming IT215
//Arianne Gallegos
//04/23/2007
//Payroll3.java
//Payroll program that calculates the weekly pay for an employee.
import java.util.Scanner; // program uses class Scanner
public class Payroll3
private string name;
private float rate;
private float hours;
// Constructor to store Employee Data
public void Payroll3( string nameOfEmployee, float hourlyRate, float hoursWorked )
name = nameOfEmployee;
rate = hourlyRate;
hours = hoursWorked;
} // end constructor
} //end class EmployeeData
// main method begins execution of java application
public static void main( String args[] )
System.out.println( "Welcome to the Payroll Program! " );
boolean quit = false; // This flag will control whether we exit the loop below
// Loop until user types "quit" as the employee name:
while (!quit)
// create scanner to obtain input from command window
Scanner input = new Scanner ( System.in );
System.out.println(); // outputs a blank line
System.out.print( "Please enter the employee name or quit to terminate program: " );
// prompt for and input employee name
String nameOfEmployee = input.nextLine(); // read what user has inputted
if ( nameOfEmployee.equals("quit")) // Check whether user indicated to quit program
System.out.println( "Program has ended" );
quit = true;
else
// User did not indicate to stop, so continue reading info for this iteration:
float hourlyRate; // first number to multiply
float hoursWorked; // second number to multiply
float product; // product of hourlyRate and hoursWorked
System.out.print( "Enter hourly rate: " ); // prompt
hourlyRate = input.nextFloat(); // read first number from user
while (hourlyRate <= 0) // prompt until a positive value is entered
System.out.print( "Hourly rate must be a positive value. " +
"Please enter the hourly rate again: " ); // prompt for positive value for hourly rate
hourlyRate = input.nextFloat(); // read first number again
System.out.print( "Enter hours worked: " ); // prompt
hoursWorked = input.nextFloat(); // read second number from user
while (hoursWorked <= 0) // prompt until a positive value is entered
System.out.print( "Hours worked must be a positive value. " +
"Please enter the hours worked again: " ); // prompt for positive value for hours worked
hoursWorked = input.nextFloat(); // read second number again
product = (float) hourlyRate * hoursWorked; // multiply the hourly rate by the hours worked
// Display output for this iteration
System.out.println(); // outputs a blank line
System.out.print( nameOfEmployee ); // display employee name
System.out.printf( "'s weekly pay is: $%,.2f\n", product); // display product
System.out.println(); // outputs a blank line
// Display ending message:
System.out.println( "Thank you for using the Payroll program!" );
System.out.println(); // outputs a blank line
} // end method main
} // end class Payroll3I still get the following error codes:
C:\IT215\Payroll3>javac Payroll3.java
Payroll3.java:28: class, interface, or enum expected
public static void main( String args[] )
^
Payroll3.java:33: class, interface, or enum expected
boolean quit = false; // This flag will control whether we exit the loop b
elow
^
Payroll3.java:36: class, interface, or enum expected
while (!quit)
^
Payroll3.java:42: class, interface, or enum expected
System.out.println(); // outputs a blank line
^
Payroll3.java:43: class, interface, or enum expected
System.out.print( "Please enter the employee name or quit to terminate p
rogram: " );
^
Payroll3.java:45: class, interface, or enum expected
String nameOfEmployee = input.nextLine(); // read what user has inputted
^
Payroll3.java:48: class, interface, or enum expected
if ( nameOfEmployee.equals("quit")) // Check whether user indicated to q
uit program
^
Payroll3.java:51: class, interface, or enum expected
quit = true;
^
Payroll3.java:52: class, interface, or enum expected
^
Payroll3.java:57: class, interface, or enum expected
float hoursWorked; // second number to multiply
^
Payroll3.java:58: class, interface, or enum expected
float product; // product of hourlyRate and hoursWorked
^
Payroll3.java:60: class, interface, or enum expected
System.out.print( "Enter hourly rate: " ); // prompt
^
Payroll3.java:61: class, interface, or enum expected
hourlyRate = input.nextFloat(); // read first number from user
^
Payroll3.java:64: class, interface, or enum expected
while (hourlyRate <= 0) // prompt until a positive value is entered
^
Payroll3.java:68: class, interface, or enum expected
hourlyRate = input.nextFloat(); // read first number again
^
Payroll3.java:69: class, interface, or enum expected
^
Payroll3.java:72: class, interface, or enum expected
hoursWorked = input.nextFloat(); // read second number from user
^
Payroll3.java:75: class, interface, or enum expected
while (hoursWorked <= 0) // prompt until a positive value is entered
^
Payroll3.java:79: class, interface, or enum expected
hoursWorked = input.nextFloat(); // read second number again
^
Payroll3.java:80: class, interface, or enum expected
^
Payroll3.java:86: class, interface, or enum expected
System.out.println(); // outputs a blank line
^
Payroll3.java:87: class, interface, or enum expected
System.out.print( nameOfEmployee ); // display employee name
^
Payroll3.java:88: class, interface, or enum expected
System.out.printf( "'s weekly pay is: $%,.2f\n", product); // display
product
^
Payroll3.java:89: class, interface, or enum expected
System.out.println(); // outputs a blank line
^
Payroll3.java:91: class, interface, or enum expected
^
Payroll3.java:96: class, interface, or enum expected
System.out.println(); // outputs a blank line
^
Payroll3.java:98: class, interface, or enum expected
} // end method main
^
27 errors
Any other suggestions? -
Help with maze program/importing txt
Hi everybody
im having a very hard time figuring out how to program a problem given to me. Im fairly new to java (im more of a c++ kinda guy but we must do this in java.. unfortunately) and the problem states this
Problem Description
you will write an application that searches a maze in order to help a trapped mouse find the hidden cheese. The maze can be represented using 4 symbols as follows: 1 represents a wall 0 represents space m represents the initial mouse position c represents the cheese position
The following is an example input maze:
111111111111
101000001001
1c0000100001
101111111111
100111100001
110111111001
110000000m11
111110111101
111111111111
Your application must search the maze, starting at the m position, and stops when it reaches the c position. Note that not all mazes have solutions. So, it must also stop if the maze has no solution.
For simplicity, you may assume the following: the maze is surrounded by 1?s the cheese (c position) can be found anywhere in the maze, except at the border (surrounding 1?s)
Programming
Write an application that inputs the maze from the user (Do NOT hardcode the maze in your program), and searches for the c position, starting from the m position.
Your application must print the updated maze, every time a new position is tried, until a solution is found, or the application discovers that a solution cannot be found.
Now so far hopefully my logic is correct. We are allowed to input a txt file with any given maze inside the txt file. However, the maze must be a maximum of 100 x 100 but can be any size under that.
Now first things first.. importing a txt
heres what i have so far
public static void main (String [] args){
Scanner mazefile;
try {
Scanner mazefile = new Scanner (new File("maze.txt")); //maze.txt being the txt file with the maze inside it
catch (FileNotFoundException e){
System.out.println("Could not Open file");
return;
while (mazefile.hasNext());
String x = inf.nextLine();
System.out.print(x);
mazefile.close();
personally i think this is totally wrong...i cant seem to figure out where to put the bounded so that the maze is a max of 100 by 100 and what happens if the txt is like
1111111111111
111c111111111
1110111111111
111000m11111
will the scanner import it into java so its like this?!Just use a 2D array of ints, no stack needed.
int maze[][];
int maze1[][]=new int[100][100];
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream("maze.txt")));
String str="";
int count=0,width=0;
while((str=reader.readLine())!=null){
if(str.length()>100)error();
if(str.length()>width)width=str.length();
for(int i=0;i<str.length();i++)maze1[count]=Integer.paseInt(""+str.charAt(i));
count++;
if(count>=100)error();
maze=new int[count][max];
for(int i=0;i<count;i++)for(int j=0;j<max;j++)maze[i][j]=maze1[i][j];
} catch(Exception ex){} -
I seem to be having a little problem with my program. In my main program, depending on which method comes first, the other methods wont work for example the way my main program is not, with occurance method before removeLetter method, the occurance method works fine, but my removeLetter meth won't remove the letter. But if i switch the two and have removeLetter first then it will remove the letter, but my occurance method will come back say the letter is not in the word even when it is...can someone help me? Thanx in advance...
class CharacterRecurrance{
private int i=0;
private int occur=0;
void inString(String s, char n){
if(i<s.length()){
if(s.charAt(i)==n)
System.out.println("Yes, the letter" + " " + n + " " + "is present");
else{
i++;
inString(s,n);
else System.out.println("No, the letter" + " " + n + " " + "is not present");
void occurance(String s, char n){
if(i < s.length()){
if(s.charAt(i)==n){
occur++;
i++;
occurance(s,n);
else{
i++;
occurance(s,n);
else System.out.println("The letter" + " " + n + " " + "appears" + " " + occur + " " + "times");
void removeLetter(String s, char n){
if(i < s.length()){
if(s.charAt(i)==n){
s = s.replace(s.charAt(i),' ');
i++;
removeLetter(s,n);
else{
i++;
removeLetter(s,n);
else System.out.println(s);
class Program3_10{
public static void main(String[] a) {
CharacterRecurrance find = new CharacterRecurrance();
String word = "mississippi";
char letter = 's';
find.inString(word, letter);
System.out.println();
find.occurance(word, letter);
System.out.println();
find.removeLetter(word, letter);
}Or make it zero in the last step of each function. Like this-void occurance(String s, char n){
if(i < s.length()){
if(s.charAt(i)==n){
occur++;
i++;
occurance(s,n);
else{
i++;
occurance(s,n);
else{
System.out.println("The letter" + " " + n + " " + "appears" + " " + occur + " " + "times");
i=0; // reset to zero.
} -
Help with dynamic text and and css !
My second question of the day.
I'm trying to build a feature in my app in which the user can
hide/reveal
bolding and or
italics and or
underlining. The text is being loaded in from an xml file
and I was thinking about styling it with css in order to get the
underlining. My problem is that the only way I can think about
pulling this off is to have a css style sheet that has a defined
bold,italic and underline class defined- - then another one that
just has a italic and underline class defined -- then another one
that has just a bold and underline class defined . . . and so on
and so on. You can see why I would prefer a much more streamlined
system. Unfortunately my experience with dynamic text styling is
somewhat limited. Hopefully someone can help me out here.Perfect. I knew it was some little snippet that I was
forgetting. I made a temporary fix of creating a 0% alpha box over
the button like a fake click area above the text, and that worked
but I know that it was a half-arsed way of working around it.
Thanks. -
I need help with an Apple ID problem...
I own a Macbook and an iPod touch, I have downloaded numerous apps for the iPod over the years. 18 months ago my boyfriend got an iPhone 3GS and created an Apple ID but it would not let him download apps due to some kind of issue registering his bank card. At the time I tried to sort it out and told him to get in touch with Apple support but he was impatient and wanted to start getting apps right away so I caved in and let him use my Apple ID. The next day I realised this was a stupid thing to do when all his apps started appearing in my iTunes. However I didn't see it as too much of a problem at the time...
Tomorrow I am going to pick up my shiny new iPhone 5 (my first iPhone ) and I am worried about plugging it into my Mac and having all these apps that I really don't want around in my iTunes. I am imagining an absolute pain in the bum trying to sort all these apps out and syncing them to the right devices? I would absolutely love to just shift all his apps over to his Apple ID, he has loads of stuff that he needs to keep now. He does not have a computer himself, but there is no real need to plug his iPhone into my macbook ever again. After having a quick read around the forums, there seems to be no simple answer to this problem. If anyone could help with this I would be extremely grateful!DoubleSkin wrote:
I would absolutely love to just shift all his apps over to his Apple ID,
You can't. All apps are forever tied to the ID used to originally obtain them. In your case, that would be your ID. He really needs to get his own ID, delete these apps, then purchase them using his ID.
For you, just delete what you don't want from your iTunes library. -
Need help with Dynamic Excel File Name please.
I am try to output an excel file with dynamic date.
Here what I done.
I am using SQL 2012.
Create Execute SQL Task Connect Type: Excel
Create Data Flow Task set to DelayValidation: True
Create OLE DB Sourc
Create Data Converstion
Excel Destination
Excel Connection, Expression, select ExcelFilePath
@[User::sXLFilePath] + @[User::sFileName] + RIGHT("0" + (DT_WSTR, 2) DATEPART("DD", GETDATE()), 2)+ RIGHT("0" + (DT_WSTR, 2) DATEPART("MM", GETDATE()), 2) + RIGHT((DT_WSTR,
4) DATEPART("YYYY", GETDATE()), 2) +".csv"
C:\ExcelOutPut\SOX_CAM_SQL_Report_010215.xls
What I try to accomplish is output the file with each day append to it, date must be DDMMYY.
I google it and found many samples, tested it, and none of them is work for me.
Any suggestions or some examples to share is greatly appreciate.
I am new to SSIS. I found one poster have similar issue and inside the posted below, there was one suggestion to create variable and connection string but how do I bind that variable to Excel Connection manger.
Please help.
Thank you so much in advance.
Ex: SOX_CAM_SQL_Report _020215.csv
SOX_CAM_SQL_Report _030215.csv
--Similar issue:
https://social.msdn.microsoft.com/Forums/en-US/bda433aa-c8f8-47c9-9e56-efd20b8354ac/creating-a-dynamic-excel-file?forum=sqlintegrationservices
Suggestion in the above posted but where can bind this to Excel Connection Manger.
Please help provide step by step. Thanks.
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\temp\\" + "ExcelTarget" + (DT_WSTR,4)DATEPART("yyyy",GETDATE()) +
".xls" + ";Extended Properties=\"EXCEL 8.0;HDR=YES\";"
And yes, as you were intimating, the delay validation on the dataflow should be set.Hi NguyenBL,
According to your description, you created ssis package to export data from database to excel, when the package runs, you want to create new excel and name the file with time stamp. If that is the case, we can achieve the goal by following steps:
Create a script task used to create excel files.
Create a data flow task to export data from database to excel.
Add OLE DB source to data flow task.
Add Excel Destination to data flow task.
Create connection manager for OLE DB and Excel.
Click Excel Connection Manager, in Properties window, click (…) button next to Expressions, then set ExcelFilePath with expression like below:
"C:\\ETL Lab\\CreateNewExcel\\ExportData_"+REPLACE((DT_STR, 20, 1252)(DT_DBTIMESTAMP)@[System::StartTime], ":", "")+".xls"
For detail information, please refer to the document:
https://sqljourney.wordpress.com/2013/01/12/ssis-create-new-excel-file-dynamically-to-export-data/
If you have any more questions, please feel free to ask.
Thanks,
Wendy Fu
Wendy Fu
TechNet Community Support -
I'm having some problems with my program. It's a binary tree of names but they aren't organized in any particular order and names can repeat. I built the tree correctly but the problem comes in writing a method. I have to write method pathLength with parameters (Treenode, Person (object), and level (starts as 1) ) it returns the longest path from the TreeNode to the node containing the Person. My code seems to work for most of the names on the tree except for one or two and I can't see why. Here's my code:
public int pathLength(TreeNode t, String name, int level)
if(t==null)
return 0;
else if((name.equals(t.getValue())&&(t.getLeft()==null||t.getRight()==null)))
return level;
return max(pathLength(t.getLeft(),name,level+1),pathLength(t.getRight(),name,level+1));
max is a method that returns the larger of two integers (x,y)
next I have to write method rootPath with parameter (TreeNode) that returns the longest path from the root of the tree to a node containing the same as root.........this method I'm not even close on but I would have thought that all I needed to do for code was
public int rootPath(TreeNode t)
return pathLength(t,(String)t.getValue(),1);
so that it would go from t to another node with t's value.........maybe its because pathLength doesn't workand also another part of my program that i'm having trouble with is a different tree which has letters as leaves and null's as parents etc. To get to a letter u follow a code of 1's and 0's so 1110 would be left left left right and u'd get a letter.....i wrote the code that i'll get a code and i can find the letter but now i hafta make it go opposite so i type a letter and it gives the code
they provided me with the main code
public String wordToBits(String word)
String result="";
for(int k=0; k<word.length(); k++)
result+=wordToBitsHelper(word.substring(k,k+1),myRoot,"""");
return result;
i hafta write method private String wordToBitsHelper(String s, Treenode t, String pathSoFar)
and im really lost -
hi,
i study java at school and i need help with my project.
im doing a simple demonstration of a pathfinding program whose algoritm i read off Wikipedia (http://en.wikipedia.org/wiki/Pathfinding)where the co-ordinates of the start and end points
are entered and the route is calculated as a list of co-ordinates. Here is the section of code i am having trouble with-
void find_path(int x,int y,int p,int q)
int t1;int t2;
int temp_pool[][]=new int[4][3];//stores contagious cells of elements in grid pool
int grid_pool[][]= new int[100000][3];
int pass_pool[][]=new int[4][3];//stores the pool of squares which can be added to the list of direction
int path[][]= new int[10000][3];//stores actual path
int count=1;int note=10;int kk=0;
int curx,cury;
//the above arrays contain 3 columns - to store x and y co-ordinate and a counter variable(the purpose of which will become clear later)
grid_pool[0][0]=p;
grid_pool[0][1]=q;
grid_pool[0][2]=0;
int counter=grid_pool[0][2];
for(int i=0;i<=100;i++)
counter++;
curx=grid_pool[0];
cury=grid_pool[i][1];
temp_pool[0][0]=curx-1;
temp_pool[0][1]=cury;
temp_pool[0][2]=counter;
temp_pool[0][0]=curx;
temp_pool[0][1]=cury-1;
temp_pool[0][2]=counter;
temp_pool[0][0]=curx+1;
temp_pool[0][1]=cury;
temp_pool[0][2]=counter;
temp_pool[0][0]=curx;
temp_pool[0][1]=cury+1;
temp_pool[0][2]=counter;
int pass=0;
for(int j=0;j<=3;j++)
int check=0;
int in=temp_pool[j][0];
int to=temp_pool[j][1];
if(activemap[in][to]=='X')
{check++;}
if(linear_search(grid_pool,in,to)==false)
{check++;}
if(check==2)
pass_pool[pass][0]=in;
pass_pool[pass][1]=to;
pass++;
}//finding which co-ordinates are not walls and which are not already present
for(int k=0;k<=pass_pool.length-1;k++)
grid_pool[count][0]=pass_pool[k][0];
grid_pool[count][1]=pass_pool[k][1];
count++;
if(linear_search(grid_pool,x,y)==true)
break;
//in this part we have isolated the squares which run in the approximate direction of the goal
//in the next part we will isolate the exact co-ordinates in another array called path
int yalt=linear_searchwindex(grid_pool,p,q);
t1=grid_pool[yalt][2];
int g1;int g2;int g3;
for(int u=yalt;u>=0;u--)
g3=find_next(grid_pool,p,q);
g2=g3/10;
g1=g3%10;
path[0]=g2;
path[u][1]=g3;
path[u][2]=u;
for(int v=0;v<=yalt;v++)
System.out.println(path[v][0]+','+path[v][1]);
ill be grateful if anyone can fix it. im done with the rest thoughdeath_star12 wrote:
hi,
i study java at school and i need help with my project.
im doing a simple demonstration of a pathfinding program whose algoritm i read off Wikipedia (http://en.wikipedia.org/wiki/Pathfinding)where the co-ordinates of the start and end points
are entered and the route is calculated as a list of co-ordinates. Here is the section of code i am having trouble with-
...The part "i am having trouble with" means absolutely nothing to the people who are answering questions here. It's like going to the doctor with a broken rib and just saying "doc, I don't feel so well". Get my point?
Also, please take the trouble to properly spell words and use a bit of capitalization. Your question is hard to read as it is, which will most probably cause (some) people not to help you. And lastly, please use code tags when posting code: it makes it so much easier to read (see: [Formatting Messages|http://mediacast.sun.com/users/humanlever/media/forums_text_editor.mp4]).
Thanks. -
A problem with java program(reset problem in java GUY)
I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
correspond to the black square.
import java.awt.*;
import javax.swing.*;
public class DrawPanel extends JPanel {
public final static int CIRCLE = 1, SQUARE = 2;
private int shape;
private boolean fill;
private boolean showStatus;
private int shapeSize = 100;
private Color foreground;
// draw a specified shape
public void paintComponent (Graphics g){
super.paintComponent(g);
// find center
int x=(getSize().width-shapeSize)/2;
int y=(getSize().height-shapeSize)/2;
if (shape == CIRCLE) {
if (fill == true){
g.setColor(foreground);
g.fillOval(x, y, shapeSize, shapeSize);
else{
g.setColor(foreground);
g.drawOval(x, y, shapeSize, shapeSize);
else if (shape == SQUARE){
if (fill == true){
g.setColor(foreground);
g.fillRect(x, y, shapeSize, shapeSize);
else{
g.setColor(foreground);
g.drawRect(x, y, shapeSize, shapeSize);
// set showStatus value
public void setShowStatus (boolean s) {
showStatus = s;
// return showstatus value
public boolean getShowStatus () {
return showStatus;
// set fill value
public void setFill(boolean isFill) {
fill = isFill;
// set shape value
public void setShape(int shapeToDraw) {
shape = shapeToDraw;
// set shapeSize value
public void setShapeSize(int newShapeSize) {
shapeSize = newShapeSize;
// set foreground value
public void setForeground(Color newColor) {
foreground = newColor;
// repaint DrawPanel
public void draw (){
if(showStatus == true)
repaint();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class shapes extends JFrame {
private JPanel buttonPanel; // panel for buttons
private DrawPanel myPanel; // panel for shapes
private JButton resetButton;
private JComboBox colorComboBox;
private JRadioButton circleButton, squareButton;
private ButtonGroup radioGroup;
private JCheckBox filledButton;
private JSlider sizeSlider;
private boolean isShow;
private int shape;
private boolean isFill=true;
private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
"green", "lightgray", "magenta", "orange",
"pink", "red", "white", "yellow"}; // color names list in ComboBox
private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
Color.gray, Color.green, Color.lightGray, Color.magenta,
Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
public shapes() {
super("Draw Shapes");
// creat custom drawing panel
myPanel = new DrawPanel(); // instantiate a DrawPanel object
myPanel.setBackground(Color.white);
// set up resetButton
// register an event handler for resetButton's ActionEvent
resetButton = new JButton ("reset");
resetButton.addActionListener(
// anonymous inner class to handle resetButton events
new ActionListener() {
// draw a black filled square shape after clicking resetButton
public void actionPerformed (ActionEvent event) {
// call DrawPanel method setShowStatus and pass an parameter
// to decide if show the shape
myPanel.setShowStatus(true);
isShow = myPanel.getShowStatus();
shape = DrawPanel.SQUARE;
// call DrawPanel method setShape to indicate shape to draw
myPanel.setShape(shape);
// call DrawPanel method setFill to indicate to draw a filled shape
myPanel.setFill(true);
// call DrawPanel method draw
myPanel.draw();
myPanel.setFill(true);
myPanel.setForeground(Color.black);
}// end anonymous inner class
);// end call to addActionListener
// set up colorComboBox
// register event handlers for colorComboBox's ItemEvent
colorComboBox = new JComboBox(colorNames);
colorComboBox.setMaximumRowCount(5);
colorComboBox.addItemListener(
// anonymous inner class to handle colorComboBox events
new ItemListener() {
// select shape's color
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED)
// call DrawPanel method setForeground
// and pass an element value of colors array
myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
myPanel.draw();
}// end anonymous inner class
); // end call to addItemListener
// set up a pair of RadioButtons
// register an event handler for RadioButtons' ItemEvent
squareButton = new JRadioButton ("Square", true);
circleButton = new JRadioButton ("Circle", false);
radioGroup = new ButtonGroup();
radioGroup.add(squareButton);
radioGroup.add(circleButton);
squareButton.addItemListener(
// anonymous inner class to handle squareButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
shape = DrawPanel.SQUARE;
myPanel.setShape(shape);
myPanel.draw();
}// end anonymous inner class
);// end call to addItemListener
circleButton.addItemListener(
// anonymous inner class to handle circleButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
shape = DrawPanel.CIRCLE;
myPanel.setShape(shape);
myPanel.draw();
else
System.out.println("Please click Reset button first");
}// end anonymous inner class
);// end call to addItemListener
// set up filledButton
// register an event handler for filledButton's ItemEvent
filledButton = new JCheckBox("Filled", true);
filledButton.addItemListener(
// anonymous inner class to handle filledButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
if (event.getStateChange() == ItemEvent.SELECTED) {
isFill=true;
myPanel.setFill(isFill);
myPanel.draw();
else {
isFill=false;
myPanel.setFill(isFill);
myPanel.draw();
else
System.out.println("Please click Reset button first");
}// end anonymous inner class
);// end call to addItemListener
// set up sizeSlider
// register an event handler for sizeSlider's ChangeEvent
sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
sizeSlider.setMajorTickSpacing(10);
sizeSlider.setPaintTicks(true);
sizeSlider.addChangeListener(
// anonymous inner class to handle sizeSlider events
new ChangeListener() {
public void stateChanged(ChangeEvent event) {
myPanel.setShapeSize(sizeSlider.getValue());
myPanel.draw();
}// end anonymous inner class
);// end call to addChangeListener
// set up panel containing buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
buttonPanel.add(resetButton);
buttonPanel.add(filledButton);
buttonPanel.add(colorComboBox);
JPanel radioButtonPanel = new JPanel();
radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
radioButtonPanel.add(squareButton);
radioButtonPanel.add(circleButton);
buttonPanel.add(radioButtonPanel);
// attach button panel & draw panel to content panel
Container container = getContentPane();
container.setLayout(new BorderLayout(10,10));
container.add(myPanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.EAST);
container.add(sizeSlider, BorderLayout.SOUTH);
setSize(500, 400);
setVisible(true);
public static void main(String args[]) {
shapes application = new shapes();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}Many thanksWho is this Java guy anyway?
Maybe you are looking for
-
Clicking a tree node does not refresh the fields in the table component
hi all, I am using a tree component along with a table component in my page.so whenever i am clicking on a node it should display the relevant information of that node in the table from the database.But whenever i am doing the page is not refreshing
-
Get current password in a basic authentication JSP
Hello. I've written some JSP pages and I've protected them with BASIC authentication. I'd like to get the password that the user used to log in, because I need to execute a EJB method running on other server and this EJB method is also protected. Tha
-
States I am working in the trial vesion where as I paid for subscription today. Ron Reger
-
Sun Ultra 10 with SunStorEDGE A1000/D1000 unable to setup
I realise this covers old ground but I have not been able to trace a uitable resolvement and would be grateful for assistance. I have a Sun Ultra 10 with 256MB RAM and 440GHz cpu.. It has a pci Adaptec 2944UW HVD SCSI interface card. The storage syst
-
with following code response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition"," filename=OpportunityReport.xls"); dialog shows download dialog with three buttons Open, Save, Cancel i want to show only Save and Canc