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
Related
Hey I am a high school and I found the solution to my problem but confused on why it's doing what it's doing can someone explain? Also I tried looking for the answer but couldn't find it so sorry if someone's already answered this.
So at getAverage() I state int i; and initialize it in the foreach loop but when it runs it says "variable i might not have been initialized"? I found the solution to this was just make int i = 0; but i'm confused because I know you can state a variable and not initialize it at that time as long as you initialize it later. So what makes this so special?
public class ArrayAverage
{
private int[] values;
public ArrayAverage(int[] theValues)
{
values = theValues;
}
public double getAverage()
{
// Problem here
int i; // Solution: int i = 0;
for(int value : values){
i += value;
}
double avg = (double)i / values.length;
return avg;
}
}
// This pseudo code code has nothing to do with above code
// but is example of what I know can be done but isn't
int i;
i = 10;
System.out.println(i);
//Output would be 10
The issue is that the you're adding the variable i to itself, and another value. However, the initial value for i has not been defined in the previous code. This is the reason that i = 0 would make the code work, as the program now understands that for the first loop, it has to add the value to 0, then the second loop will know to add the previous value, to the new value.
Hope this helped.
I made a Point class to manage xy coordinate (I know some java default packages already have some Point object that behave in a similar way, I use it as a lazy alternative and this is an example, please dont mind it ^^).
Before using it I was using the int primitive type.
thing is, when passing a class or a primitive type as parameter of a method, both don't act the same way, if I change the value of a primitive variable in a method, the original variable is unaffected, unlike if I was using an object since its the reference that is passed as parameter.
my problem is that since I use Point for math (example below), I have to manually create new object to save the result and I never use it to have a "link" between two variables as I could with how object behave usually.
My Point class:
public class Point {
public int x;
public int y;
public Point(int nx, int ny) {
this.x = nx;
this.y = ny;
}
public Point() {
this(0, 0);
}
}
An example of method:
public Point getAdjacent(int x, int y, Direction dir) {
Point pt = new Point(x, y);//basically, i would like to do that automatically
switch (dir) {
case Up:
pt.y -= 1;
break;
case Down:
pt.y += 1;
break;
case Right:
pt.x -= 1;
break;
case Left:
pt.x += 1;
break;
default:
//do nothing
}
return pt;
}
To summarize, is it possible to make Point behave like a primitive type?
EDIT: i mean that it would automatically copy it when passing it as parameter or doing point1=point2
The question might be a bit too broad, because one could argue quite extensively about what the word "behave" should mean. But to some extent, we can sort this out:
The shortest answer might be: No, this is not possible.
A slightly more elaborate answer might be: No, it is not yet possible to let a class (or more precisely: an object) behave like a primitive value.
The long answer:
There are efforts to achieve a behavior that might come close to what you're trying to accomplish. The relevant keyword here is Value Types.
Some resources:
The original value types proposal by John Rose, Brian Goetz, and Guy Steele: http://cr.openjdk.java.net/~jrose/values/values-0.html
The relevant JEP for Value Objects: http://openjdk.java.net/jeps/169
The Wiki describing the goals and current state of value types: https://wiki.openjdk.java.net/display/valhalla/L-World+Value+Types
The relevant mailing list: https://mail.openjdk.java.net/pipermail/valhalla-dev/
However, this is not supported in current versions of Java and the JVM, and it might still take a while until the details are sorted out.
Until then, there are some conceivable workarounds to achieve the desired goal.
The simplest solution is the one that you already proposed: You always return a new instance instead of modifying a given object.
The example that you showed in the question might not be the best to illustrate this, because the method getAdjacent that you showed could in fact be a static method. It does not use the instance that it is called on in any way.
Then you could always be sure that you received a new instance for each modification. Otherwise, imagine this code snippet:
Point a = new Point(1,2);
Point b = new Point(3,4);
a.add(b);
System.out.println(a); // What does this print?
Depending on the implementation of the add method, the behavior might not be clear. If it was implemented like this:
public void add(Point other) {
this.x += other.x;
this.y += other.y;
}
then the point a would be modified, and the output would be (4,6).
But if it was implemented like this
public Point add(Point other) {
return new Point(this.x+other.x, this.y+other.y);
}
then a would remain unaffected, and the output would still be (1,2).
In general, making something like a Point immutable basically enforces this style of programming. So you could make the variables x and y in your class final, so that you could always be sure that the object cannot be modified after it was created:
public class Point {
// Note that these are FINAL:
private final int x;
private final int y;
public Point(int nx, int ny) {
this.x = nx;
this.y = ny;
}
...
}
There are some further design considerations for such a seemingly trivial thing like a Point class (some of which I mentioned in this answer), but discussing them is beyond the scope of this answer.
First of all: be sure to use break statements in your switch code. Otherwise when case Up is matched, the switch block will "fall through" and will execute:
pt.y -= 1;
pt.y += 1;
pt.x -= 1;
pt.x += 1;
(Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html)
According to the question, you can indeed use the Point class. Below code will:
1. Use a Point as input.
2. Extract the variables x and y from the input Point into a copy primitive.
3. Change the copied primitives.
4. Create a new Point, based on the copies.
In this way the "old" Point will be left untouched.
public Point getAdjacent(final Point point, final Direction dir) {
int x = point.x;
int y = point.y;
switch (dir) {
case Up:
y -= 1;
break;
case Down:
y += 1;
break;
case Right:
x -= 1;
break;
case Left:
x += 1;
break;
default:
break;
}
return new Point(x, y);
}
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.
I need help with a lab. My teacher did not tell us anything and he told us to figure it out. So i can use any help I can get. Thank You
Step 1: Is everything good with step one including my distance formula and I am trying to set xx equal to x and yy equal to y so I have not clue how to do that could could you help me with that.
class Point {
private int x;
private int y;
public Point() // (0, 0)
{
x = 0;
y = 0;
}
public Point(int xx, int yy)
{
xx = x;
yy = y;
}
public int getX() // return field values
{
return x;
}
public int getY()
{
return y;
}
// Use the distance formula to find the distance of this point from the origin (0,0)
public double distanceFromOrigin()
{
int d = 0;
d = Math.squrt(Math.pow(xx - x) + (Math.pow(yy - y);
}
Is my distance formula good if not what is wrong and can you help me fix it.
Step 2: I need to find the manhattan distance
// Find the "manhattan" distance between current point and other.
// You can look at http://x...content-available-to-author-only...t.gov/dads//HTML/manhattanDistance.html for help
public double distance(Point other)
{/*write the code for here*/}
I really have no clue how to do step 2 so i can really use a lot of help thank you guys so much
Step 3: After i find the manhattan distance between current point and other. I need to change it to its new values which i have no clue how to get the new value and how to change it. After that i need to shift the point by the translation T which i have no clue how to do that so i need help on that
// Changes the coordinate to new values
public void setLocation(int x, int y)
{/*write the code for here*/}
//Shift the point by the translation T<x+h,y+k>
public void translate(int h, int k)
{/*write the code for here*/}
by the way guys I am just on the basic computer science so I can't use all the fancy stuff so keep it basic and simple
Like torvin said in the comments, that really looks like Java and not Javascript. Those are two different languages, despite the similar names.
Generally looking at your code, there are obvious mistakes, which make me wonder what IDE (integrated development environment) you are using to write code. A proper program that helps you write code will spot those.
Just in your distanceFromOrigin() you are missing:
2 closing bracets
Math.squrt() should be Math.sqrt()
You are not returning a value, despite having set the methods return type to double
You should probably first set up an IDE and do a basic Java tutorial before continuing, honestly.
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.