I am just trying to execute some Java code and print them out to the console, however, when I try to run it, it gives an error and says illegal start to expression. Does anyone know what is going on here?
package com.craneai;
public class Main {
public static void main(String[] args) {
public static void int F(int N) {
int X, Y, Z, I;
int X = 2;
if(N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (int I = 3; I <=N; I++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
}
public static void main(String[] args) {
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
public static int F(int N) {
int X, Y, Z, I;
X = 2;
if(N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (int i = 3; i <=N; i++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
A few things to consider:
1st. You're declaring a void return and then a int, the function must have only 1 return type.
public static void int F(int N)
2nd. The method should be outside the main method
3rd. You declared X twice in the code, the second time you call it, you don't have to declare the type, the compiler will try to process it as a new variable with a name that is already in use.
4th. In your for method, you declared X, once again, Java is case sensitive, so X and x are different in the compiler.
5th. You've also declared I twice, you don't need to provide a temporary variable before calling the for method, since you can do it inside the for loop;
Looks like you're starting to learn Java, a few tips from who works with it since the Java 5..
Don't declare your variables with a single letter;
Don't declare your functions/methods with a single letter;
Don't declare your variables in UPPER CASE, always low case and camelCase;
Even as an example you should make your code cleaner, improve the readability for others, other people will be happier in the future if you do this (this include yourself).
First: you're declaring a method inside another method - see that the F method is inside the main method. Java does not support nested methods.
Second: you're declaring X and I twice.
Third: You wrote two return types to your method: void and int.
This will work:
public class Main {
public static void main(String[] args) {
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
public static int F(int N) {
int X, Y, Z, I;
X = 2;
if (N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (I = 3; I <= N; I++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
}
Three main errors:
Nested method: F method inside main
Method F return int and void
You declared X and I twice.
Here is your class fixed:
public class Main {
public static void main(String[] args) {
System.out.println(F(6));
System.out.println(F(0));
System.out.println(F(1));
}
public static int F(int N) {
int X = 2, Y, Z;
if (N <= 0) {
X = 3;
} else {
Y = 1;
Z = 1;
for (int I = 3; I <= N; I++) {
X = Y + Z;
Z = Y;
Y = X;
}
}
return X;
}
}
Output is going to be this:
8
3
2
Related
I'm working on a program that first takes an even array of doubles and sequentially creates a second array of (x, y) coordinates. Then, an invoking PointArray has to be compared to the argument PointArray by comparing the x-coordinates and y-coordinates of each point in the array. I know conceptually that I'll have to sort each array and compare each point using the indeces and the defined equals method, but I don't know how to refer to a point of the invoking class-type array when it is not given as a parameter.
private double x;
private double y;
public Point(double x_coord, double y_coord)
{
x = x_coord;
y = y_coord;
}
public boolean equals(Point anotherPoint)
{
if(x == anotherPoint.x && y == anotherPoint.y)
{
return true;
}
return false;
}
int count;
private Point[] points = new Point[count];
public PointArray(double[] doubleArray)
{
count = (doubleArray.length) / 2;
if(doubleArray.length % 2 == 0)
{
count = (doubleArray.length) / 2;
for(int i = 0, j = 0; i < count; i++, j += 2)
{
double x = doubleArray[j];
double y = doubleArray[j + 1];
points[i] = new Point(x, y);
}
}
else
{
System.out.println("Error: The given array must be even.");
}
}
public boolean equals(PointArray anotherPointArray)
{
double x = 0;
double y = 0;
double xAnother = 0;
double yAnother = 0;
Point newPoint = new Point(x, y);
Point newAnotherPoint = new Point(xAnother, yAnother);
anotherPointArray.sort();
anotherPointArray.newPoint;
for(int i = 0; i < points.length; i++)
{
for(int j = 0; i < anotherPointArray.length; j++)
{
if(newPoint.equals(newAnotherPoint))
{
return true;
}
}
}
return false;
}
EDIT: To clarify, my problem is that I don't know how to set up the Point equals method using the PointArray objects.
When you call a method on an object like:
something.myMethod(argObject);
inside the myMethod you can then refer to something (the object the method is called on) as the this-object.
I hope this tuto demonstrates it better than words do.
Dear fellow Stackoverflowers,
My swap method isn't working inside the insertionSort method; it is not swapping my array elements.
What's wrong with my insertion sort algorithm?
package AlgoExercises;
import java.util.Arrays;
public class InsertionSort {
static int[] numbersArray = { 5, 2, 4, 6, 1, 3 };
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
static void insertionSort(int[] numbersArray) {
for (int i = 1; i < numbersArray.length - 1; i++) {
int j = i;
while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) {
swap(numbersArray[j], numbersArray[j - 1]);
j = j - 1;
System.out.println(Arrays.toString(numbersArray));
}
}
}
public static void main(String args[]) {
insertionSort(numbersArray);
}
}
Solution:
After fixing the swap method where int[] was included in its parameters, swap now works! I've also edited numbersArray.length-1 to numbersArray.length.
Thank you for your help guys!
package AlgoExercises;
import java.util.Arrays;
public class InsertionSort {
static int[] numbersArray = { 5, 2, 4, 6, 1, 3 };
static void swap(int i, int j) {
int temp = numbersArray[j];
numbersArray[j] = numbersArray[i];
numbersArray[i] = temp;
}
static void insertionSort(int[] numbersArray) {
for (int i = 1; i < numbersArray.length; i++) {
int j = i;
while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) {
swap(j, j - 1);
j = j - 1;
System.out.println(Arrays.toString(numbersArray));
}
}
}
public static void main(String args[]) {
insertionSort(numbersArray);
}
}
Java is a pass by value language, so swapping the int variables passed to the swap method makes no difference. You should pass the array itself + the two indices to swap to the method, and modify the array in the swap method.
static void swap(int[] arr, int i, int j) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
and call it
swap(numbersArray, j, j-1);
Note that I didn't check the logic of your insertion sort implementation. This answer only deals with the swap issue.
Just to give you another way of thinking why your existing swap method doesn't work: if you write code like this:
void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
void callSwap() {
int x = 1;
int y = 2;
swap(x, y);
System.out.println(x + ", " + y);
}
You can 'inline' the swap method, basically copying it into the callSwap method. The semantically equivalent code would be:
void callSwap() {
int x = 1;
int y = 2;
// Start of inlined swap method.
{
int a = x;
int b = y;
int t = a;
a = b;
b = t;
}
// End of inlined swap method.
System.out.println(x + ", " + y);
}
Hopefully, you wouldn't expect x and y to have swapped values.
Note that this behaviour has nothing to do with the fact that the variable names a and b are different to x and y; I simply chose them to be different. Were the parameters of swap called x and y, it would be necessary to rename them to something else when inlining, since they are completely separate from the x and y in callSwap.
I am stuck trying to manager a list of list of lists. I have declared and initialized my data structure as so:
List<Vector<ArrayDeque<Vector_t>>> mData = new ArrayList<Vector<ArrayDeque<Vector_t>>>(
6);
for (int i = 0; i < 6; ++i) {
mData.add(i, new Vector<ArrayDeque<Vector_t>>());
// mData.get(i).setSize(200);
}
for (int i = 0; i < 6; i++) {
for (int k = 0; k < 200; k++) {
mData.get(i).add(new ArrayDeque<Vector_t>());
mData.get(i).get(k).add(new Vector_t());
}
}
where Vector_t is:
class Vector_t {
float x;
float y;
float z;
}
Is this initialization correct? When adding values to the array deque at the last position, it replaces the whole arraydeque with the last element, and I have no idea why.
Also, when I changing values using the code mdata.get(1).get(42) the element at mdata.get(0).get(40) is also affected. Again, I have no idea why?
I have given hardcoded values for example..this is the way i m adding
if (mData.get(dir.value).get(slice).size() >= sMaxNum_c)
{
mData.get(dir.value).get(slice).removeFirst();
}
mData.get(dir.value).get(slice).addLast(result.acc);
when adding values to one direction other direction values are changing...:(
Please help me to solve this.
My suggestion would be to either introduce some classes as Amir suggested, or at least make your code easier to understand by introducing some well-named, temporary local variables.
I don't know what you're trying to acheive, but re-writing with the use of some local variables might allow you to spot an issue:
List<Vector<ArrayDeque<Vector_t>>> mData = new ArrayList<Vector<ArrayDeque<Vector_t>>>(
6);
for (int i = 0; i < 6; ++i) {
mData.add(i, new Vector<ArrayDeque<Vector_t>>());
}
for (Vector nextVector : mData) {
for (int k = 0; k < 200; k++) {
ArrayDeque<Vector_t> tempArray = new ArrayDeque<Vector_t>());
tempArray.add(new Vector_t());
nextVector add(tempArray);
}
}
I am not sure of what you are trying to achieve, but for starters, you should consider using another Data Structure besides Vector as it is obsolete.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
// Consider using another DataStructure such as Arraylist, as Vector<> is obsolete.
import java.util.Vector;
public class main {
public static void main(String[] args) {
// Use diamond inference.
List<Vector<ArrayDeque<Vector_t>>> mData = new ArrayList<>(6);
for (int i = 0; i < 6; i++) {
Vector<ArrayDeque<Vector_t>> vav = new Vector<>();
ArrayDeque<Vector_t> av = new ArrayDeque<>();
for (int k = 0; k < 200; k++) {
av.add(new Vector_t(2.0f, 2.0f, 2.0f));
}
vav.add(av);
}
}
}
Use variables instead of calling get() so much.
public class Vector_t {
private float x;
private float y;
private float z;
public Vector_t() {
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
public Vector_t(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public float GetX() {
return x;
}
public float GetY() {
return y;
}
public float GetZ() {
return z;
}
public void SetX(float x) {
this.x = x;
}
public void SetY(float y) {
this.y = y;
}
public void SetZ(float z) {
this.z = z;
}
}
use setters and getters for your class, it's all about using OOP programming concepts :)
If you are a little more specific on what you are trying to accomplish, I am sure we could help.
-Francisco
How can I return value in a for loop ? For example if I have a loop that give me 3 numbers: 1,2,3... How can I return the value of the last number (here it is 3)?
public class Cod {
public static void main(String[] args) {
exp();
}
public static int exp() {
int x=10;
for (int i=1; i<=3;i++) {
x=x*10;
int y=x/10;
System.out.println(y);
return y;
}
}
}
The easiest thing is to wait for the loop to finish, and then return the last value that it has produced.
The only valid reason why you need to wait for the loop to calculate all three results is that the calculation is dependent upon the value calculated by the prior iteration of the loop. In this case, here is how you can do it:
int res = 0;
for (int i = 0 ; i != 3 ; i++) {
res = calculateResult(i, res);
}
return res;
In case when you can calculate the value of the last iteration directly without running the previos iterations, there is no reason to run the loop at all.
If I understood what you are trying to do, here is your example modified:
public class Cod {
public static void main(String[] args) {
System.out.println(exp());
}
public static int exp() {
int x=10;
for (int i=1; i<=3;i++) {
x=x*10;
}
int y=x/10;
return y;
}
}
I don't understand why you do x/10 - instead you could just loop one less round.
I am not sure if you want to loop or break after a certain condition in a loop
To break you can do
public static int exp() {
int x=10;
int y = 0;
for (int i=1; i<=3;i++) {
x=x*10;
y=x/10;
System.out.println(y);
break;
}
}
This will break straight away so it will only loop once. The value of y is accessible at this point.
If you want the value of the counter variable then declare this outside the loop
int i = 1;
for (i = 1; i<=3;i++) {
x=x*10;
y=x/10;
...
}
System.out.println(i + "");
Then the value of i is accessible outside the loop.
EDIT: after comment
to get the value of y do
public static int exp() {
int x=10;
int y = 0;
for (int i=1; i<=3;i++) {
x *= 10;
y = y + (x/10);
}
System.out.println("y value after loop is "+ y);
}
or if y is not to be added to
public static int exp() {
int x=10;
for (int i=1; i<=3;i++) {
x *= 10;
}
int y = x/10;
System.out.println("y value after loop is "+ y);
}
I have a cell object with function
public class Cell {
static int X;
static int Y;
static int Val = 0;
static int Player = 0;
public Cell(int a, int b, int p) {
// TODO Auto-generated constructor stub
X = a;
Y = b;
Val = 0;
Player = p;
}
With additional function updateX, updateY, updateVal, updatePlayer and respective get functions. It is called by
Cell[][] grid = new Cell[7][6];
for(int i = 0; i < 7; i++)
for(int j = 0; j < 6; j++)
{
grid[i][j] = new Cell(i, j, 0);
}
System.out.println("wasd");
grid[0][1].updatePlayer(1);
grid[0][1].updateVal(1);
System.out.println("grid[0][1].getval = " + grid[0][1].getVal() + " grid[1][1].getval = " + grid[1][1].getVal());
But the output is
grid[0][1].getval = 1 grid[1][1].getval = 1
and should be
grid[0][1].getval = 1 grid[1][1].getval = 0
What is causing this error?
static int X;
static int Y;
static int Val = 0;
static int Player = 0;
These properties should not be static,following code should be ok:
int X;
int Y;
int Val;//the default int value is zero
int Player;
You made the X, Y, Val and Player variables in the class static. Which means they are shared by all instances of that class, which means their values in all those instances will be exactly the same. I'm pretty sure you wanted to declare those as instance variables instead:
public class Cell {
private int x, y, val, player;
// ...
}
You made Val a static variable, so only one Val variable exists and it is shared by all Cell objects.
change:
static int Val = 0;
to:
int Val = 0;
Similarly if you want individual Cell objects to retain separate instances of your variables (i.e. x,y,Val) you need to take away the static keyword from all of them