Strange Output in Java [duplicate] - java

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));

Related

Can't round decimals to 4 decimal points in java for gravity program

So, I'm trying to get the decimals in a table I have for a gravity program that I created to round after 4 decimals. However, whenever I've tried to round it, it either will print the table without rounding, or it will start to print the table, and then throw an error at me.
I'm sure what I doing wrong, and I've tried to look online for help, but it hasn't helped.
I have a few lines commented out below to show where I have tried to round to 4 decimals places, but hasn't worked.
I'll post my code below to see if you guys could please help me figure out what I'm doing wrong.
public class Gravity
{
public static void main(String[] args)
{
Gravity g = new Gravity();
System.out.printf("%5s%20s%20s\n", "Time", "Distance Earth", "Distance Moon");
// Gravity.format()
// DecimalFormat df = new DecimalFormat("###.####");
// System.out.println(df.format(g));
for (int i = 1; i <= 10; i++)
{
System.out.printf("%5d%20fm%20fm\n", + i,g.distanceFallen(i, 9.8), g.distanceFallen(i, 1.625));
// System.out.format("%.4f", i);
}
}
/* private static Gravity format(String string, int i)
{
//
return i;
}*/
public double distanceFallen (double time, double gAcc)
{
// System.out.format("%.4f");
// System.out.format("%.4f", time);
return (0.5)*gAcc*Math.pow(time, 4);
}
}
EDIT: Also, here's what the table looks like, just to make clear up any potential confusion.
Time Distance Earth Distance Moon
1 4.900000m 0.812500m
2 78.400000m 13.000000m
3 396.900000m 65.812500m
4 1254.400000m 208.000000m
5 3062.500000m 507.812500m
6 6350.400000m 1053.000000m
7 11764.900000m 1950.812500m
8 20070.400000m 3328.000000m
9 32148.900000m 5330.812500m
10 49000.000000m 8125.000000m
Change your formatting to:
"%5d%20.4fm%20.4fm\n"
You'll want to change your header formatting to 24 instead of 20 too.

Nested Loop is giving me same or wrong answers when i need to calculate the equity return

Background: Greetings! I had to randomly sample a value from normal distribution (done) and use that value (mean is "that value") to see how much an initial equity value of 100 increases in 3582weeks and provide the final profited value. As in:
equity=100
equity = equity + 100*mean
I need to run 1000 trials to see how different values of "mean" give different profited values.
I'm able to get the answer for the 3582 weeks for the first trial, but when i'm adding another loop for "1000 trials," it's either giving me the same values or wrong values.
Problem: The loop is either giving me the same values or completely in-correct values. method: computeStats(){..}
Note: I've shown the constructor in the blog just for reference to show what i'm really doing.
class Sample extends SimulateMarket{ //SimulateMarket is the Application class
ArrayList<Double> data = new ArrayList<Double>();
private double mean, stdDev;
private Random random;
SimulateMarket mySim = new SimulateMarket(); //mySim is an instance of SimulateMarket class used to access variables of Simulate Class
public Sample(int size, double theMean, double theStdDev){ //Comstructor used for the Distributional Technique
random = new Random();
for(int i=0; i<3582 ; i++)
data.add(theMean+random.nextGaussian()*theStdDev); //Random sampling from Normal Distribution
mean = getMean(); //getMean() method is used to get Mean
stdDev = getStdDev(mean);
Collections.sort(data);//getStdDev is used for getting Standard Deviation
System.out.println(this); //for printing the results
}
public void computeStats(){
ArrayList<Double> myData = new ArrayList<Double>();
for(int j=0; j<1000; j++){
equity = 100;
for(int i=0; i<3582; i++){
equity = equity + 100*mean;
}
myData.add(equity);
}
for(Double num: myData){
System.out.println(num);
}
}
Apparently, i was adding the 1000 loop in the wrong place. That's where it needs to be- in the main method
public static void main(String[] args) throws java.io.IOException{
for(int j=0; j<1000; j++){
Sample equity = new Sample(3582, 0.0016, 0.0205);
equity.computeStats();
}
}

Java Android trying to place a 10*10 grid over a bitmap to see how much of a colour is in each grid section

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);
}
}
}

Math I did the program but need to know a little more

I did the problem but I only found out How to do it for one value of x? Here is the program.
public class PointsOnACircleV1 {
public static void main(String[ ] args)
{
double r = 1;
double x = 0.1;
double equation1= Math.pow(r,2);
double equation2= Math.pow(x,2);
double y = Math.sqrt(equation1-equation2);
System.out.println(y);
}
}
I got the correct answer .99 (......)
I need mine to show multiple values of x. Here is how the output should be. Please help if you can.
Use a for loop.
Related Documentation
The for statement.
In order to get it to print multiple values you first need to fill the "String [] args" but you need to ahve them as double to be able to multiply them with other values. In your case that's the X-values, so lets say over the code you posted
public class PointsOnACircleV1 {
//initialize your array with your values
double [ ] args = { 1.0, 0.9, 0.8,.... and so on until you reach 0.1, 0.0};
//you could fill it other more effective ways but just to show you!
public static void main(double[ ] args)
{
double r = 1;
// no need to fill this as you already done
// it double x = 0.1;
for(Iterator<double> i = args.iterator(); args.hasNext(); )
{
//this is the number you want to multiply with
double numbertomultiply = args.next();
double equation1= Math.pow(r,2);
double equation2= Math.pow(numbertomultiply,2);
double y = Math.sqrt(equation1-equation2);
System.out.println(y);
}
}
Just written from my head havent checked it but just to give you a sample :)
EDIT Use the other answers to initialize your array.

Object Creation and putting them into a 2D array

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.

Categories