transfer of the value inside function - java

public boolean judge(Parcelle p) {
int xx,yy;
int co;
for(int aa=0;aa<9;aa++) {
for(int bb=0;bb<5;bb++) {
if (p.equals(alist.get(aa).get(bb))) {
xx=aa;
yy=bb;
break;
}
}
}
co=alist.get(xx+1).get(yy).exist+alist.get(xx-1).get(yy-1).exist+alist.get(xx-1).get(yy).exist+alist.get(xx).get(yy-1).exist+alist.get(xx+1).get(yy+1).exist+alist.get(xx).get(yy+1).exist;
return co>=2;
}
Here alist is a 2-dimension arraylist of class Parcelle.
and Parcelle has a public int exist.
I wrote this loop for judge if the sum of the exist of Parcelles around this Parcelle is bigger than 2.
and it alerts that I should initialize the int xx,yy,
but in the loop I've set the value of them.
So I don't know what the problem is!

I don't really get what you're doing here either (no context), but I'd start by setting the variables to zero first:
int xx = 0;
int yy = 0;
int co = 0;
I have a suspicion that is not going to fix everything, but that's where I start when hitting that particular error in java. For some reason, it's really finicky about declaring without setting a value.

Related

Variable is assigned but never accessed

I'm new to Java and trying to do a simple count operation in a for loop:
public boolean play(Matrix matrix){
int dimension = matrix.getDimension();
int count=0;
for(int x=0;x<dimension;x++){
for(int y=0;y<dimension;y++){
count++;
}
}
return true;
}
The error I get is related to count and is as in the title: Variable is assigned but never accessed.
The variable count should have been initialized outside the for loop and then accessed inside the for loop, I don't understand where the problem is located.
Like GriffeyDog wrote: You never use (read from) the variable count, you just assign to it. That was the problem.

int cannot be converted to int []

new to programming here and i keep getting the error message, incompatible types, int cannot be converted to int [], the question is to add R1 & R2 together if they are of equal lengths and if not, print a message that says 'the arrays must be same length', if that matters, not sure where im going wrong, any help would be greatly appreciated
public int[] arrayAdd(int[] R1, int[] R2)
{
int[] sumArray= new int[R1.length];
if( R1.length!= R2.length)
{
System.out.println("The arrays must be same length");
}
else
{
for(int i=0; i< R1.length; i++)
for (int j=0; j<R2.length; j++)
{
sumArray= R1[i]+ R2[j]; // Error
}
}
return sumArray;
}
not sure where im going wrong
You are attempting to assign an int to a variable whose type is int[].
That is not legal ... and it doesn't make sense.
This:
sumArray= R1[i]+ R2[j];
should be this
sumArray[something_or_other] = R1[i] + R2[j];
... except that you have a bunch of other errors which mean that a simple "point fix" won't be correct.
Hint: you do not need nested loops to add the elements of two arrays.
sumArray[i]= R1[i]+ R2[j]; // updated line
you need to assign to an array element, but you were doing it wrong.
Your code is broken in many several ways, at least:
You declared returning an array but what is the value of it when inputs are of the wrong size? Manage such errors in better ways (stop, throw exception, return error code, etc). At least never display something at this place, this is not the place were you have to tackle the error, this is the place here you detect it, just report it to caller(s).
You (tried to) created space for the returned value but how could this be if conditions for having a return value is not met?
You used Java syntax to declare an array, int []sumArray should be `int sumArray[0].
You can't dynamically allocate an array like this, to capture a dynamic allocation you must use a pointer, an array is not a pointer. But a pointer can be set to the memory address of an allocated array, like int *sumArray = new int[10]
sumArray is an array so to set an element of it use sumArray[index] = ...
So this may be better:
public int *arrayAdd(int[] R1, int[] R2) {
if( R1.length!= R2.length) {
return nullptr;
}
int *sumArray= new int[R1.length];
for(int i=0; i< R1.length; i++) {
sumArray[i] = R1[i]+ R2[i];
}
return sumArray;
}
After question editing
If you want to sum two arrays, element by element, then a single loop is sufficient...
Actually in that line sumArray is an integer array and you are assigning it as integer only and also you haven't declared variable j.
Try this-
public int[] arrayAdd(int[] R1, int[] R2)
{
int[] sumArray= new int[R1.length];
if( R1.length!= R2.length)
{
System.out.println("The arrays must be same length");
}
else
{
for(int i=0; i< R1.length; i++)
{
sumArray[i]= R1[i]+ R2[i]; // Error
}
}
return sumArray;
}

Array in Method Header: error ']' expected (Java)

I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!

Having trouble understanding how to maintain state using classes

I'm new to using OOP, I typically just put all my code in a single class and use methods. But I want to maintain state information and think classes are the best fit but I'm having trouble wrapping my head around it.
Say I have a list of items and I want to stop when the total sum of all previous items in the list equals X(in this case 10 so it takes item 1 + 2, then 2+3.etc..until it hits the threshold 10), I can use a method to calculate it but it involves me doing the entire process all over again when all I really need to do is increment by the last item and then see if my data exceeds the threshold. Here's my code so far but I know its not good because although it works its really just using the class as an independent method and recalculating on every loop. My goal is to,using this structure, reduce loops if not necessary to check thresholds.
Any suggestions?
Code:
public class LearningClassesCounter {
public static void main(String[] args) {
int[] list = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] data_list = new int[list.length];
for (int current_location = 0; current_location<list.length;current_location++) {
//can only put commands in here. Nothing above.
Counter checker = new Counter(data_list);
System.out.println(checker.check_data(current_location));
for (int i =0; i<100; i++){
if (checker.check_data(current_location) == false) {
break;
}
data_list[current_location] = (list[current_location]+1); //this is just a random function, it could be any math function I just put it in here to show that some work is being done.
}
}
//its done now lets print the results
for (Integer item : data_list) {
System.out.println(item);
}
}
}
class Counter {
private int[] data_list;
private int total_so_far;
// create a new counter with the given parameters
public Counter(int[] data_list) {
this.data_list = data_list;
this.total_so_far = 0;
}
public boolean check_data(int current_location) {
// TODO Auto-generated method stub
int total_so_far = 0;
//System.out.println(total_so_far);
for (int item : data_list) {
total_so_far = item + total_so_far;
if (total_so_far >= 10) {
break;
}
}
if (total_so_far>=10) {
return false;
} else {
return true;
}
}
}
I don't need anyone to fix my code or anything(I want to do it myself, the code is just to give an idea of what I'm doing). I'm more interested in the flaw in my logic and maybe a way for me to better think about designing classes so I can apply them to my own situations better.
So the solution is that you do not update the data_list directly. Instead have a setter method in the Counter class that takes the index and value to update. It updates the value in the array and also updates a count value.
Something like this:
class Counter{
private final int[] list;
private count = 0;
private final maxCount = 10;
public Counter(int[] list){
this.list = list;
}
public boolean updateValueAndCheckPastMax(int index, int value){
list[index] = value;
count += value;
return count >= maxCount;
}
}
You are way over thinking this, and a counter class is not really necessary in this case.
I'm also interested as to why you'd be doing this line:
data_list[current_location] = (list[current_location]+1);
Do you want your data_list to be the same as list, but each value is incremented by 1?
If you are merely trying to return a sub-array of the values that are < 10, i would suggest just doing this in a for loop, and using an int as a counter.

Java: Adding to an array list

public class Maze
{
public static final int ACTIVE = 0;
public static final int EXPLORER_WIN = 1;
public static final int MONSTER_WIN = 2;
private Square[][] maze;
private ArrayList<RandomOccupant> randOccupants;
private Explorer explorer;
private int rows;
private int cols;
public Maze(Square[][] maze, int rows, int cols, int numTreasures, int numMonsters, String name)
{
int i;
this.maze = maze;
this.cols = cols;
this.rows = rows;
randOccupants = new ArrayList<RandomOccupant>();
for (i = 0; i < numTreasures; i++)
{
randOccupants.add(i) = new Treasure(this); //COMPILE ERROR
}...
Why can't I add this to the arraylist? I believe the java docs says that I'm doing this correctly.
You can do either:
randOccupants.add( i, new Treasure(this) );
...or...
randOccupants.add( new Treasure(this) );
Both are equivalent, since you're always appending the new element to the end of the array.
See https://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html.
First, Treasure would need to either inherit from RandomOccupant or implement it (if it is an interface).
Second, if you want to add it at a particular point in the list, the syntax is
randOccupants.add(i,new Treasure(this));
Although it's hard to see why you don't just do
randOccupants.add(new Treasure(this));
since the items will be added in order even if you don't specify a location.
You're trying to add a Treasure to an ArrayList of RandomOccupants, so unless Treasure is a RandomOccupant, that's not going to work. The given code does not make it clear whether Treasure is a subclass of RandomOccupant, so it's not possible from the code here to say whether that's part of the problem.
What you're actually doing is adding an int to the list here, which is definitely not a RandomOccupant.
ArrayList's add() method returns either boolean or void depending on the version that you're using, so you can't assign to it. You're using the method incorrectly.
The two versions of add() are:
boolean add(E e)
void add(int index, E element)
The second version inserts the element at the specified position, and the first one inserts it at the end. Presumably, what you're intending to do is this:
for(i = 0; i < numTreasures; ++i)
randOccupants.add(new Treasure(this));
But of course, that assumes that Treasure is a subclass of RandomOccupant. If it isn't, then you'll need to change the type of the ArrayList for it to hold Treasures.
Because it is not a RandomOccupant.
Because you're using the add method wrong. You would call:
randOccupants.add(new Treasure(this));

Categories