i tried to generate bar chart from input
i would like have my code to get out put like this
enter image description here
this is my code but i have some error
i have some error in label that say should make method label and in main
can you guys help me fix this things
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
public class baronly
{
//Establish the placement of the fields for user entry
// get some error in this
Label LabelA = addLabel("A", 1,1,1,1);
IntegerField FieldA = addIntegerField(0,1,2,1,1);
Label LabelB = addLabel("B", 1,3,1,1);
IntegerField FieldB = addIntegerField(0,1,4,1,1);
Label LabelC = addLabel("C", 1,5,1,1);
IntegerField FieldC = addIntegerField(0,1,6,1,1);
Label LabelD = addLabel("D", 1,7,1,1);
IntegerField FieldD = addIntegerField(0,1,8,1,1);
Label LabelF = addLabel("F", 1,9,1,1);
IntegerField FieldF = addIntegerField(0,1,10,1,1);
//Establish a drop down menu for the drawing
//Right now we only have one choice -- Bar
//Establish variables for this program
int numberOfScores = 5;
int Xleft = 100;
int Xright = 300;
int Ytop = 100;
int Ybottom = 250; // y value entries can be up to 150
int BarWidth = 10;
int totalX , totalY;
int[ ] scores;
char graphChoice;
//Constructor to establish the initial values in the program
public baronly()
{
scores = new int[numberOfScores];
for (int i = 0; i < scores.length; i++)
scores[ i ] = 0;
totalX = Xright - Xleft + 1;
totalY = Ybottom - Ytop + 1;
}
//Allow for the menu choices
//Remember, we only have one choice right now
public void paint (Graphics g)
{
getInputData();
g.setColor (Color.red); //set color of the graph
g.drawString("Java Grades",170,290); //title
drawBarGraph(g);
}
//Get input from the screen
public void getInputData()
{
scores[0] = FieldA.getNumber();
scores[1] = FieldB.getNumber();
scores[2] = FieldC.getNumber();
scores[3] = FieldD.getNumber();
scores[4] = FieldF.getNumber();
}
//Draw the bar graph
public void drawBarGraph(Graphics g)
{
drawAxes(g);
int i, x, y, height, largestNumber, xIncrement, yIncrement;
//Compute the x and y increments
largestNumber = findLargest (scores);
xIncrement = totalX /numberOfScores;
if (largestNumber ==0)
yIncrement = 0;
else
yIncrement = totalY / largestNumber;
//Draw the bars
for(i=0; i < numberOfScores; i++)
{
x = getXCoordinate(i+1, xIncrement);
y = getYCoordinate(scores[i], yIncrement);
x = x - BarWidth / 2;
height = Ybottom - y + 1;
g.fillRect(x, y, BarWidth, height);
}
//Label x - axes with grade choices
String [ ] label = {"A", "B", "C", "D", "F"};
for(i=1; i<= numberOfScores; i++)
g.drawString(label[i-1], 100+ i*xIncrement, 270);
//Label y - axes with quantity of each grade
int topy;
if(largestNumber%10==0)
topy=largestNumber;
else
topy=(largestNumber/10+1)*10;
//i=i+5 controls y value label -- adjust for size of data
for (i=0; i<=topy; i=i+5)
{
g.drawString(String.valueOf(i), 70, Ybottom-i*yIncrement+5);
}
}
//Draw the axes for the graph
public void drawAxes (Graphics g)
{
g.drawLine(Xleft, Ytop, Xleft, Ybottom);
g.drawLine(Xleft, Ybottom, Xright, Ybottom);
}
//Determining x coordinate
public int getXCoordinate(int i, int xIncrement)
{
return Xleft + xIncrement *i;
}
//Determining y coordinate
public int getYCoordinate(int numStudents, int yIncrement)
{
return Ybottom - yIncrement * numStudents;
}
//Finding the largest value in the array
public int findLargest(int [ ] a)
{
int i;
int loc = 0;
for(i=1; i<a.length; i++)
if(a[i]>a[loc])
loc = i;
return a[loc];
}
//Main
public static void main(String[ ] args)
{
baronly frm = new baronly();
frm.setSize(400,300);
frm.setVisible(true);
}
}
that error gave says i should give method in label what that suppose to mean
Related
I am trying to create a 5x5 board of rectangles(squares) with a 2d array but my code draws the 25 squares in only 5 places so it looks like there's only 5 squares diagonally on the "board". I'm assuming something is wrong with the logic in the nested loop but after tinkering around for a while I can't figure out what it is. Thanks for any help!!
Object class:
public class Card
{
private double x, y, wd, ht;
private int cardNum;
private boolean faceUp;
private double space;
private Color bsC, fsC;
Random gen = new Random();
public Card(double x, double y, double width, double height, int cN, double sP)
{
this.x = x;
this.y = x;
wd = width;
ht = height;
faceUp = false;
this.cardNum = cN;
space = 0.1;
bsC = new Color(178, 178, 178);
fsC = new Color(211, 172, 250);
}
public void drawMe()
{
StdDraw.setPenColor(bsC);
StdDraw.filledRectangle(x, y, wd, ht);
}
}
Tester class:
public class ClientCardJordanHubbard
{
public static void ClientCardJordanHubbard()
{
Random gen = new Random();
Card[][] cards = new Card[5][5];
int count = 0;
StdDraw.setFont(new Font("Arial", Font.BOLD, 20));
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(0.5,0.5, "Press w a s d to move");
StdDraw.pause(2000);
StdDraw.clear();
for(int i = 0; i < cards.length; i++)
{
double x = 0.25+0.14*i;
for (int j = 0; j < cards[i].length; j++)
{
double y = 0.25+0.14*j;
double w = 0.07;
double h = 0.07;
int cN = gen.nextInt(5)+1;
cards[i][j] = new Card(x, y, w, h, cN, 0.1);
cards[i][j].drawMe();
System.out.println("The value of the card at index " +i+" " +j
+ " is: " +cards[i][j].getcN());
System.out.println("The coordinates of the card at index " +i+" " +j
+ " is: " +cards[i][j].getX() +" "+cards[i][j].getY());
}
}
}
Since your cards are displayed diagonally, the first thing you need to check whether your x will get an y value or vice-versa at some point. Knowing this, it is easy to find the error, which is the line of
this.y = x;
since your this.y gets an x value.
I'm trying to write an algorithm to satisfy this challenge. I've double, triple, and quadruple checked my logic, but I think I'm missing something obvious. This program should group each color next to similar colors, but it produces something more akin to noise.
This is sort of what I expect (taken from a similar answer):
And this is what I'm actually getting:
public class AllColors extends JFrame {
private static final int WIDTH = 256;
private static final int HEIGHT = 128;
private static long TOTAL_ITERATIONS = (WIDTH * HEIGHT) * 185000;
private static int VALUES_PER_CHANNEL =32;
private static int CHANNEL_DELTA = 256/VALUES_PER_CHANNEL;
static BufferedImage image;
private static final int SCALE = 5;
static int[][] kernel = { { 0, 0, 1, 0, 0 },
{ 0, 2, 3, 2, 0 },
{ 1, 3, 0, 3, 1 },
{ 0, 2, 3, 2, 0 },
{ 0, 0, 1, 0, 0 } };
public static void main(String[] args) {
AllColors f = new AllColors();
f.setTitle("All Colors");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
image = new BufferedImage(WIDTH * SCALE, HEIGHT * SCALE, BufferedImage.TYPE_3BYTE_BGR);
init();
//gui stuff
JPanel p = new JPanel(){
#Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.scale(SCALE, SCALE);
g2.drawImage(image, 0, 0, null);
}
};
p.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
f.add(p);
f.pack();
f.setVisible(true);
group(p);
}
//makes an image of all colors
private static void init() {
int x = 0;
int y = 0;
for(int r = 0; r < VALUES_PER_CHANNEL; r+= 1){
for(int g = 0; g < VALUES_PER_CHANNEL; g+= 1){
for(int b = 0; b < VALUES_PER_CHANNEL; b+= 1){
x++;
if(x % WIDTH == 0){
y++;
x = 0;
}
if(y >= HEIGHT)
return;
image.setRGB(x, y, new Color(r*CHANNEL_DELTA,g*CHANNEL_DELTA,b*CHANNEL_DELTA).getRGB());
}
}
}
}
//group together similar pixels
private static void group(JPanel panel){
Random rand = new Random();
for(long i = 0; i < TOTAL_ITERATIONS; i++){
Point first = new Point(rand.nextInt(WIDTH), rand.nextInt(HEIGHT));
Point second = new Point(rand.nextInt(WIDTH), rand.nextInt(HEIGHT));
trySwitch(first, second);
if(i % (WIDTH * HEIGHT) == 0){
System.out.println(i / (WIDTH * HEIGHT));
panel.repaint();
}
}
}
private static void swap(Point first, Point second){
int temp = image.getRGB(second.x, second.y);
image.setRGB(second.x, second.y, image.getRGB(first.x, first.y));
image.setRGB(first.x, first.y, temp);
}
//get how similar the neighbors are
private static int getNeighborDelta(int imageX, int imageY){
Color center = new Color(image.getRGB(imageX, imageY));
int sum = 0;
for (int x = 0; x < kernel[0].length; x++)
{
for (int y = 0; y < kernel.length; y++)
{
int weight = kernel[x][y];
if (weight <= 0)
{
continue;
}
int xOffset = x - (kernel[0].length / 2);
int yOffset = y - (kernel.length / 2);
try{
sum += getDistance(new Color(image.getRGB(imageX + xOffset, imageY + yOffset)), center) * weight;
}catch(ArrayIndexOutOfBoundsException e){
//if out of image
}
}
}
return sum;
}
//switches if the neighbors will be more similar
private static void trySwitch(Point first, Point second){
double firstDistance = getNeighborDelta(first.x, first.y);
swap(first, second);
double secondDistance = getNeighborDelta(first.x, first.y);
if(secondDistance > firstDistance)
swap(first, second);
}
//get similarity between colors
private static double getDistance(Color one, Color two){
int r = Math.abs(two.getRed() - one.getRed());
int g = Math.abs(two.getGreen() - one.getGreen());
int b = Math.abs(two.getBlue() - one.getBlue());
return r + g + b;
}
}
it keeps making the selection sort off by at least 1,
it sorts the insertion sort fine,
but it seems like the selection sort needs more time,
i cant figure it out...
its not doing a proper sort of the selection sort method.i think that my error is either in the reorderselection method.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.Random;
public class TwoSorts extends Applet {
private final int APPLET_WIDTH = 800, APPLET_HEIGHT = 600; // to make the applet size
private final int colNum = 15; // how many columns
int[] insertion = new int[colNum]; //insertion array for column heights
int[] selection = new int[colNum]; // selection array for column heights
public Random generator; // random numbers class
public int randomNum; // random number
public Button butn1 = new Button("Sort Arrays"); // buttons
public int selectionCount = 0; // how many times press the sort button
boolean selectionFlag, insertionFlag; // to stop looping when done
//**********************************************************************
//* initiates everything
//**********************************************************************
public void init()
{
setBackground (Color.black);
setSize(APPLET_WIDTH, APPLET_HEIGHT);
generator = new Random();
for (int column = 0; column < colNum; column++) // Creates the two arrays
{
randomNum = generator.nextInt(100) + 15;
insertion[column] = randomNum;
selection[column] = randomNum;
}
butn1.addActionListener(new Butn1Handler());
butn1.setBackground(Color.blue);
add(butn1);
}
//*************************************************************************
// Draws the columns
//************************************************************************
public void paint(Graphics g)
{
g.setColor(Color.white); // debugging code
g.drawString ("Count: " + selectionCount, 100, 495);
g.drawString("Selection Sort", 25, 220);
g.drawString("Insertion Sort", 25, 420);
int xs = 50, ys = 100, width = 40, heights = 0; // for the loops
int xi = 50, yi = 300, heighti = 0;
if ( insertionFlag == false && selectionFlag == false)
{
for (int count = 0; count < colNum + 1; count++ )
{
g.setColor(Color.green);
heights = selection[count];
heighti = insertion[count];
g.fillRect(xs, ys, width, heights);
g.fillRect(xi, yi, width, heighti);
xs = xs + width + 2;
xi = xi + width + 2;
}
}
else
{
g.setColor(Color.white);
g.drawString ("Sort is Done!", 5, 495);
for (int count = 0; count < colNum + 1; count++ )
{
g.setColor(Color.gray);
heights = selection[count];
heighti = insertion[count];
g.fillRect(xs, ys, width, heights);
g.fillRect(xi, yi, width, heighti);
xs = xs + width + 2;
xi = xi + width + 2;
}
}
}
//*****************************************************************************
//* Method to sort the array by Selection method
//******************************************************************************
public void reorderSelection()
{
int min = selectionCount;
int temp = 0;
for (int scan = (selectionCount); scan < selection.length; scan++)
{
if (selection[scan] < selection[min])
min = scan;
temp = selection[min];
selection[min] = selection[selectionCount];
selection[selectionCount] = temp;
}
}
//*****************************************************************************
//* Method to sort the arrary by Insertion method
//******************************************************************************
public void reorderInsertion()
{
int key = insertion[selectionCount];
int position = selectionCount;
while (position > 0 && key < (insertion[position-1]))
{
insertion[position] = insertion[position-1];
position--;
}
insertion[position] = key;
}
//-----------------------------------------------------
// Button 1 Listener and instructions
//-----------------------------------------------------
public class Butn1Handler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
reorderSelection();
reorderInsertion();
repaint();
selectionCount++;
if (selectionCount > 14)
selectionFlag = true;
if (selectionCount > 15)
insertionFlag = true;
}
}
}
Your selection sort method is incorrect. You need an inner loop.
public void reorderSelection()
{
int min = selectionCount;
int temp = 0;
for( int scan = selectionCount ; scan < selection.length - 1 ; scan++ )
{
min = scan;
for(int i = scan + 1; i < selection.length ; i++)
{
if(selection[min] > selection[i]) min = i;
}
if(min != scan)
{
temp = selection[scan];
selection[scan] = selection[min];
selection[min] = temp;
}
}
}
While using an ArrayList, I can't seem to figure out how to reset and re-apply the random color for each iteration of the for loop. I am trying to reset and apply my random color every time my XLeft position is changed. This is only a section of one class I am using, and my getMax() was defined by a Scanner input. Any suggestions?
import java.util.ArrayList;
import java.util.Random;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class BarChart {
private int width, height;
private ArrayList<Double> values = new ArrayList<Double>();
private Random generator = new Random();
int red = generator.nextInt(255);
int green = generator.nextInt(255);
int blue = generator.nextInt(255);
private Color randomColor = new Color(red, green, blue);
public BarChart(int aWidth, int aHeight) {
width = aWidth;
height = aHeight;
}
public void add(double inputValues) {
values.add(inputValues);
}
public double getMax() {
double max = values.get(0);
for (int i = 1; i < values.size(); i++) {
if ((values.get(i)) > max)
max = values.get(i);
}
return max;
}
public void draw(Graphics2D g2) {
int xLeft = 0;
double barWidth = width / values.size();
for (int i = 0; i < values.size(); i++) {
double barHeight = (values.get(i) / getMax()) * height;
Rectangle bar = new Rectangle(xLeft, height - ((int) barHeight),
(int) barWidth, (int) barHeight);
g2.setColor(randomColor);
g2.fill(bar);
xLeft = (int) (xLeft + barWidth);
xLeft++;
}
}
}
It sounds like you're defining your random color once, before the loop. This means that when you run the loop, it uses the same "random color" each time through. You need to move the definition of the random color into the loop, so that it runs with each iteration.
EDIT (based on your comments):
public void draw(Graphics2D g2) {
int xLeft = 0;
double barWidth = width / values.size();
for (int i = 0; i < values.size(); i++) {
double barHeight = (values.get(i) / getMax()) * height;
Rectangle bar = new Rectangle(xLeft, height - ((int) barHeight),
(int) barWidth, (int) barHeight);
red = generator.nextInt(255);
green = generator.nextInt(255);
blue = generator.nextInt(255);
randomColor = new Color(red, green, blue);
g2.setColor(randomColor);
g2.fill(bar);
xLeft = (int) (xLeft + barWidth);
xLeft++;
}
I've made this code that successfully creates a 16x12 grid by 50x50 squares on a 800x600px board.
As you can see, the player moves to the coordinates of the players mouseclick.
Each square of the grid has an object of Felt (field) on it, which can be laast (locked). If a fields lock attribute is set to 1, the player should not be moved to that position.
How do i detect the field a player tries to move on to achieve this?
public class SimpleGame extends BasicGame{
private Image plane;
private float planeX;
private float planeY;
public SimpleGame()
{
super("SpilTest");
}
#Override
public void init(GameContainer gc) throws SlickException {
plane = new Image("figur.png");
}
#Override
public void update(GameContainer gc, int delta) throws SlickException {
Input input = gc.getInput();
if (input.isMousePressed(input.MOUSE_LEFT_BUTTON)) {
this.planeX = input.getMouseX() - 30;
this.planeY = input.getMouseY() - 50;
}
}
public void render(GameContainer gc, Graphics g) throws SlickException {
Felt board[][] = nytGrid();
int distancex = 0;
int distancey = 0;
int counter = 0;
for (int i=0; i < board.length ; i++) {
for (int j=0; j < board[i].length ; j++) {
if (board[i][j].getLaast() == 1) {
g.setColor(Color.red);
g.fillRect(distancex, distancey, 50, 50);
}
distancex += 50;
counter++;
if (counter == 16) {
distancey += 50;
distancex = 0;
counter = 0;
}
}
}
g.drawImage(plane, planeX, planeY);
}
public static void main(String[] args) throws SlickException {
AppGameContainer app = new AppGameContainer(new SimpleGame());
app.setDisplayMode(800, 600, false);
app.setTargetFrameRate(60);
app.start();
}
public Felt[][] nytGrid() {
Felt [][] board = new Felt[16][12];
for (int i=0; i < board.length ; i++) {
for (int j=0; j < board[i].length ; j++) {
int x = i;
int y = j;
board[i][j] = new Felt(x, y);
if (i == 5 && j == 5) {
board[i][j].setLaast(1);
}
}
}
return board;
}
}
First off, you should probably initialize the board in the init() method instead of render, so it doesn't have to do it every frame, and move the declaration for the grid next to the plane, planeX and planeY declarations in the class.
Now to disable movement into a locked square, first add a method to check if a square at certain coordinates is locked, so something along the lines of:
private boolean isLocked(int x, int y) {
int square = board[x/50][y/50];
if (square == 1) return true;
else return false;
}
Next modify the part of your update() method where you update the plane coordinates, so vaguely something like:
if (input.isMousePressed(input.MOUSE_LEFT_BUTTON)) {
int destX = input.getMouseX() - 30;
int destY = input.getMouseY() - 50;
if (!isLocked(destX, destY)) {
this.planeX = destX;
this.planeY = destY;
}
}
It's easy!
int mx = Mouse.getX();
int my = Mouse.getY();
But, it gives you the world cordinates, and you have to translate it to pixels:
int mx = Mouse.getX();
int my = Mouse.getY() * -1 + (Window.WIDTH / 2) + 71;