i am having difficulty with 2D arrays and inserting objects that take 3 parameters (int x, int y, int cost)
This is the beginning of a search algorithm and admittedly im off to a very poor start. I will paste the code below. I am receiving a compiling error when i try to run this code and i'm very sure it is simple but i cannot resolve it.
The Map2 class i intend to use to implement the main bulk of the algorithms, such as sorting etc.
import java.util.Arrays;
public class Map2 {
public static void main (String args[]){
Points[][] grid = new Points[4][4];
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid.length; j++){
grid[i][j] = new Points(i,j,1);
}
}
System.out.print(Arrays.deepToString(grid));
}
}
This class is my object, it contains the movement cost from moving from one position to the next (the next step obviously would be to determine neighbors) and yes, this is part of trying to create a working A star algorithm.
public class Points {
int x;
int y;
int movement_cost;
public Points(int iX, int iY, int cost){
x = iX;
y = iY;
movement_cost = cost;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getMovementCost(){
return movement_cost;
}
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public void setMovementCost(int cost){
this.movement_cost = cost;
}
public String toString(){
return ""+getX()+ ""+getY()+""+getMovementCost();
}
}
This is the console read out after compiling (3 address spaces in memory)
run:[[001, 011, 021, 031], [101, 111, 121, 131],
[201, 211, 221, 231], [301, 311, 321, 331]]
BUILD SUCCESSFUL (total time: 2 seconds)
My hope here is simple, each object in the array will contain a reference of its coordinates in memory and contain a cost of movement, which would later be used to compare in order to determine the next best position (i will later implement things such as goal, start)
my question is: whats wrong with the code the way it is ?
I want to thank, in advance whomever responds as your responce will always be appreciated
CURRENT REVISION OF MY QUESTION V0.1:
Wow well thanks for the quick responces, i have learned something new today ^^ that Arrays.deepToString(grid)); is an amasing tool i was not aware of, however i am still receiving a runtime error . Thank you once again for your replies and once again for any further responces :). The code above has been revised as recommended, but the runtime error still exists
There are several things that are wrong with your code:
Your nested loops assume that the array is square (you iterate both dimensions to grid.length),
You print the entire array after initializing each row, and
You print the array incorrectly (Java array do not print their content when passed to System.out.println)
The first item is OK if your matrix is indeed always square. The second item is easy to fix by moving the output outside of the second nested loop.
The third item is the hardest. It would be a good exercise to write a static method that takes your 2D array, and prints it out element-by-element with two nested loops. You can also use System.out.println(Arrays.deepToString(grid)); if you would rather use a system function.
Related
i failed and now i need to take a resit exam. This question was on the final exam and i feel like similar one will come on resit exam. We cant use our computers on the exam we have to write everything on paper so that was big issue i couldnt understand if im doing it wrong or right. Please be kind while answering because im new at java and i dont want to lose my hope i need to pass.
(i cant remember %100 but this was the main idea)
Q: In this question write two methods. First method should take two random variables. And second method should compare those two random variables and gives the result as higher one.
My solution:
import acm.program.*;
import acm.util.RandomGenerator;
public class RandomGenereratorBaby extends ConsoleProgram {
public RandomGenerator rgen = RandomGenerator.getInstance();{
int x = rgen.nextInt(0,9);
int y = rgen.nextInt(0,9);
}
public char BiggerOneWins (int x, int y){
if(x>=y){
return (char) (x) ;
}else{
return (char) (y);
}
}}
Please help me.
So my interpretation of the question says the method should be taking in the variables and storing them, not making some random numbers. So my solution would look something like this
public class RandomGenereratorBaby extends ConsoleProgram {
private int x;
private int y;
public void takeInNumbers(int x, int y){
this.x = x;
this.y = y;
}
public int biggerOneWins(){
if(x>=y){
return x;
}else{
return y;
}
}
}
I've also changed the return type to int as returning as char seemed a little odd.
This is my interpretation of the question and the answer I would give. I hope that helps
I'm very new to programming. However, I've written a method called "succ" that's adds 1 to a given parameter. It looks like this:
int succ(int x) {
return x += 1;
}
Now I'm supposed to write another method that adds 2 numbers using my first method. This is what my attempt looks like:
int add(int x, int y) {
for(int i = 0; i < y; i++) {
succ(x);
}
return x;
}
Unfortunately it doesn't seem to work; it always returns the initial x. For example: If I type add(8,5) it just returns 8. Can someone help me? What am I doing wrong?
Thanks in advance.
You're not doing anything with the returned value. If you want to assign it back to x, do that:
x = succ(x);
Edit: Or, perhaps you mean to add to x, since you're doing it in a loop? It's not entirely clear what this code is meant to do, and I suspect more applicable variable/method names would help. But if you want to keep adding the result, you'd just do this:
x += succ(x);
Additionally, you don't need to modify x in your succ function. Doing so in this manner may lead to unexpected behavior in the future in other examples. Keep the operations as simple as possible. Just return the calculated value:
return x + 1;
You are missing the return value of the succ method, replace the succ(x); with x = succ(x);
int add(int x, int y) {
for(int i = 0; i < y; i++) {
x = succ(x);
}
return x;
}
You keep overwriting the x value with the return value from the function. You need to add to it in each iteration, not overwrite it.
to describe my issue I must first discuss what I am trying to do, http://i.imgur.com/rcHwze5.png here is an image of a letter with a 10*10 grid over it. For every box in the grid if 1/3 of the pixels are colored a 1 is added to the ArrayList, otherwise a 0 is added. Here is my 3 methods that I have created to do this: https://gist.github.com/VincentMc/7ddf3c282e80bbff7835 BoundBM is a bitmap object with the letter drawn onto it.
Here is an image of my desired output http://i.imgur.com/B0QnUW8.png
Here is an image of my actual output http://i.imgur.com/WgRVXLv.png
It seems once a 1 is added on a row it is constantly added until it reaches the next row, but I can't seem to see why??
Any help would be greatly appreciated I have been at this quite a while, Thanks!
do it in two step:
1: sort each string:
public String sortString(String s1){
char[] chars = s1.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
return sorted;
}
2: put each of your string in an array and use:
Arrays.sort(stringArray);
Out of the Code-Segmet you offered, i cant see an obvious mistake. But your design is inviting mistakes. To avoid these you may try:
Don't use count as a classwide variable, thou its not relevant for the hole class but only for the method. So make it an return statement, that you dont loose control over it, that it may be set anywhere or is only changed locally in a method.
totalp should not be calculated in every countPixel() method call, because it is a fixed value for your BoundBM. Initialize it in your constructor maybe, or with loading the bitmap.
At last, you know how large your output array is supposed to be, it doesnt make much sense for me, to keep it a list and to add it. Create an 2D array, and write it directly.
Hope it will help
reineke
EDIT: found the mistake!
in code line 27 you set x to 0 and not to the initial value of the input x, so you continue at the wrong position!!
Here is what i would do:
final int GRID=10;
totalp = boundBM.getWidth()/GRID * boundBM.getHeight()/GRID;
//this method now does not need to read boundBM, so it is more opject-oriented
public int countPixels(int x, int y, int h, int w){
count = 0;
for (i=x; i<x+w; i++){
for(k =y; k<y+h; k++){
if(c != boundBM.getPixel(i, k)) count++;
}
}
//funny thing
return (count>totalp/3) ? 1 : 0;
}
public void createNeuralInput(){
int h = boundBM.getHeight()/GRID;
int w = boundBM.getWidth()/GRID;
int[][] array= new int[GRID][GRID];
for(int i = 0; i < GRID; i++) {
for(int j = 0; j < GRID ; j++) {
n1.add(countPixels(i*h, j*w, h, w));
//i would prefer:
//array[i][j]=countPixels(i*h, j*w);
}
}
}
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed last month.
I am in AP Computer Science, and we just learnt how to use our own static methods. This is my second program using them, but this time arrays are involved, and I am getting really weird output. I was hoping that someone could help me figure out why, I assume that I am not properly returning the result array.
The purpose of the program is to calculate the surface gravity of all of the planets in the solar system. The 2 things that I need help with are:
I do not know how to format scientific notation using printf() so
that is really messed up.
My gravity array contains [D#7248989f for every number and I can't
figure out why.
public static double[] surfaceGravity (double[] r,double[] m) {
double[] g = new double[r.length];
for (int count = 0; count < r.length; count++) {
g[count] = (6.67 * m[count]) / (r[count] * r[count]);
}
return g;
}
public static void printIntro() {
System.out.printf("%8s%17s%12s%12s%n","Planet","Diameter (km)","Mass (kg)","g (m/s^2)");
System.out.println("-------------------------------------------------------------------");
}
public static void printData(String[] planet, double[] r, double[] m, double[] g) {
for (int count = 0; count < r.length; count++) {
System.out.printf("%9s%9.0f%17.6f%12.2f%n",planet[count],(r[count] * 2),m[count],g[count]);
}
}
public static void main (String[] args) {
//initialize arrays
String[] planetNames = {"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"};
//double[] mass = {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0};
double[] mass = {3.3E+23,4.87E+24,5.97E+24,6.42E+23,1.9E+27,5.69E+26,8.66E+25,1.03E+26};
double[] radius = {2440000,6051000,6378000,3397000,71492000,60268000,25559000,24754000};
double[] gravity = surfaceGravity(radius,mass);
printIntro();
printData(planetNames, radius, mass, gravity);
//I added the line below to test the contest of my gravity array
for (double grav: gravity) {
System.out.println(gravity);
}
}
Because I can't post images, I am not sure how to get the output on here to appear as it does on my computer. This is my full code, so that only thing that you have to do to see my output is to stick this all into a class and run it.
In closing: Yes I am a noob, but I hope that you guys can help me.
I think you must change this:
for (double grav: gravity) {
System.out.println(gravity);
}
to:
for (double grav: gravity) {
System.out.println(grav);
}
because you want to print the elements, not the array.
You're printing the Array reference, instead of the Array values - You could modify your for loop,
for (double grav : gravity) {
System.out.println(grav);
}
or you could eliminate that loop by using Arrays.toString(double[]) like so -
System.out.println(java.util.Arrays.toString(gravity));
I'm working on a self-assigned project over break, and am running into one major sticking point. This is a basic line-recognition program in Java.
I have a Points class which creates the Point from the ordered pairs & sends it to the Line class for slope & intercept calculation. The results are sent back to the Points class which deposits the results into the ArrayList linelist. There are three parts to each Line object: the slope & intercept integers and the Point from which they were calculated from.
From a loop, how can I access the slope & intercept variables from each object in the linelist for comparison? Since I don't want to compare the points, just the slope & intercept, the equals() method is not what I need.
It sounds like you want something like this:
class Point {
final int x;
final int y;
Point(int x, int y) { this.x = x; this.y = y; }
}
class Line {
final int slope;
final int intercept;
Line(Point p1, Point p2) {
this.slope = ...;
this.intercept = ...;
}
}
class Points {
public void doIt(ArrayList<Point> points) {
ArrayList<Line> lines = new ArrayList<Line>();
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
lines.add(new Line(points.get(i), points.get(j));
}
}
for (int i = 0; i < lines.size(); i++) {
for (int j = i + 1; j < lines.size(); j++) {
Line line1 = lines.get(i);
Line line2 = lines.get(j);
if (line1.slope == line2.slope && line1.intercept == line2.intercept) {
// blah blah blah
}
}
}
}
}
(For the peanut gallery, yes there is scope for micro-optimization. But no, it isn't worth the effort unless you've profiled the program and found there to be a real and significant bottleneck.)
[For a more elegant and scalable solution, override the equals(Object) (and hashcode()) methods on Line class and replace the lines list with a TreeSet. This will reduce O(N**2) comparisons to O(NlogN) comparisons. But that's overkill for a basic programming exercise.]
From a loop, how can I access the slope & intercept variables from each object in the linelist for comparison?
Just add another loop over the same list inside the loop and do the comparison in there.
You could have your Line object implement the Comparable interface. You could then put the comparison logic within the Line class in the compareTo method. The logic there will test whether the slope and the intercept match, and if so return 0. Other results could return 1 or -1 to enforce ordering, if you want.
Obviously, you don't need to implement this interface to effect your desired results. However, as this is homework, doing so will allow you to play around with some features of the JDK, like using sorted Lists, etc. With a sorted list, for example, you could obviate the need for a nested loop, as you would only need to compare the object in question against one you just removed from the Iterator in the previous iteration to see if you need to add it to an existing linelist or start a new one.