private void buildDeck(ArrayList<Card> Monsters, ArrayList<Card> Spells) {
int monstersQouta = 15;
int spellsQouta = 5;
Random r = new Random();
for (; monstersQouta > 0; monstersQouta--) {
int randomIndex = r.nextInt(monsters.size());
MonsterCard monster = (MonsterCard) monsters.get(randomIndex);
MonsterCard clone = new MonsterCard(monster.getName(),
monster.getDescription(), monster.getLevel(),
monster.getAttackPoints(), monster.getDefensePoints());
clone.setMode(monster.getMode());
clone.setHidden(monster.isHidden());
clone.setLocation(Location.DECK);
deck.add(clone);
}
I need to know why we used here clone()
and how this for loop in this code works
As Andy Turner said for your first question :
clone() is not being used. It just so happens that the variable is called clone, but that has no semantic importance to the code.
Concerning the for statement he's composed of 3 parts ,each separated by one ; , and none of them is obligated to be there :
The first part is where you can, or not, declare your incremental variable : int i = 0;
The second part is where you must put an evaluation resulting on a boolean value : kappa.lengh >= i;
The thrid part is where you will modify the variable(s) values : i--;
Since none of these parts are obligated, you could write a correct for loop like this one : for(;;).
Here's a link to the documentation : For statement.
Related
I wrote a for loop that is supposed to determine if there is user input. If there is, it sets the 6 elements of int[] valueArr to the input, a vararg int[] statValue. If there is no input, it sets all elements equal to -1.
if (statValue.length == 6) {
for (int i = 0; i < 6; i++) {
valueArr[i] = statValue[i];
}
} else {
for (int i : valueArr) {
i = -1;
}
}
I am using Visual Studio Code, and it is giving me a message in for (int i : valueArr) :
"The value of the local variable i is not used."
That particular for loop syntax is still new to me, so I may be very well blind, but it was working in another file:
for(int i : rollResults) {
sum = sum + i;
}
I feel that I should also mention that the for loop giving me trouble is in a private void method. I'm still fairly new and just recently started using private methods. I noticed the method would give the same message when not used elsewhere, but I do not see why it would appear here.
I tried closing and reopening Visual Studio Code, deleting and retyping the code, and other forms of that. In my short experience, I've had times where I received errors and messages that should not be there and fixed them with what I mentioned, but none of that worked here.
for (int i : valueArr) {
.... CODE HERE ...
}
This sets up a loop which will run CODE HERE a certain number of times. Inside this loop, at the start of every loop, an entirely new variable is created named i, containing one of the values in valueArr. Once the loop ends this variable is destroyed. Notably, i is not directly the value in valueArr - modifying it does nothing - other than affect this one loop if you use i later in within the block. It does not modify the contents of valueArr.
Hence why you get the warning: i = -1 does nothing - you change what i is, and then the loop ends, which means i goes away and your code hasn't changed anything or done anything, which surely you didn't intend. Hence, warning.
It's not entirely clear what you want to do here. If you intend to set all values in valueArr to -1, you want:
for (int i = 0; i < valueArr.length; i++) valueArr[i] = -1;
Or, actually, you can do that more simply:
Arrays.fill(valueArr, -1);
valueArr[i] = -1 changes the value of the i-th value in the valueArr array to -1. for (int i : valueArr) i = -1; does nothing.
Is this code safe in Java?
public class HelloWorld {
public static void main (String args[]) {
HelloWorld h = new HelloWorld();
int y = h.getNumber(5);
int z = h.getNumber (6);
if (y == 10)
System.out.println("true");
}
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
}
My co-worker says that int number will be placed on the stack and when getNumber returns it will be popped off and could potentially be overwritten.
Is the same code potentially unsafe in C?
The HelloWorld class has no fields, and is therefore immutable. You can call your getNumber(x) function as many times as you'd like, from any thread, using the same object, and it will always give the same result for the same argument.
Maybe your co-worker is recalling horror stories in C where you can have something like static int number, which "belongs" to the method and which would get overwritten. Or maybe she's thinking about "return by reference"; even if it were, you'd be referencing a brand-new object every time because number is newly instantiated for every method call.
Your coworker is correct, sort of, but they apparently misunderstand what is going on.
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
Yes the value of 5 + 5 or 5 + 6 will be placed on the stack, but there is no danger of them being overwritten, they will properly be placed into y or z.
I suspect the confusion is from C (this type code works fine in C as well), but for pointers instead of primitives. Returning a result of malloc from a function in C can be "challenging" if you don't do it right.
which is faster creating new variable or reusing old one for java programming language?
example
case 1: creating
int x = 5;
int var = 1;
case 2: reusing old one
int x = 5;
x = 1;
"Which is faster?" is the wrong question. "Which is correct for the algorithm?" is the right question.
As a rule, you only reuse a variable if it needs to hold a new primitive value or point to a different object, because it is the variable that represents the current state. If the variable is reassigned to hold something that means something different, you should not do that but use a new variable.
So sum += item; is a valid reuse of the variable sum. But
foo = 42;
buyQuantity(foo);
...
foo = 23;
sendMessages(foo);
is not a valid reuse of foo.
A related but different question is whether you should reuse an object to hold new values. Not usually. For example:
Foo foo = new Foo();
for (int ix = 0; ix < MAX_ITERS; ++ix )
{
foo.clear();
foo.fill();
process(foo);
}
is worse than:
for (int ix = 0; ix < MAX_ITERS; ++ix )
{
Foo foo = new Foo();
foo.fill();
process(foo);
}
I did an small and simple test: Running a loop on a large (10 million) array and fill each element with a number.
Test1 : define a var before the loop and use that
Test2 : define a const inside the loop
To make the test as honest as possible, all other operations were removed.
Code
//#ts-nocheck
const maxInt = 10000000
// fill Array with a number
let A = [...Array(maxInt)].map(x => 10);
// Test 1 : Variable declared before
let x
console.time('test1')
B = A.map((a) => {
x = 3
return x
})
console.timeEnd('test1')
// Test 2 : Const variable declared in the Loop, every time
console.time('test2')
C = A.map((a) => {
const x = 3
return x
})
console.timeEnd('test2')
Test results
The test was run multiple times and on avarage (not calculated) the results were:
test1: 190.656ms
test2: 282.766ms
(Running on a Macbook with enough memory and normal CPU)
My careful conclusion: Creating a Const every time does have a slight performance impact.
I get the error message cannot find symbol, symbol: method books(int[], int) when I try to compile the following code.
For further explanation about what I want the code to do, see below the code.
public class books {
public void main(String[] args) {
int searchValue = 0, index;
int refNum[] = new int[4]; // the array
refNum[0] = 4; //numbers to refer to (aka to find)
refNum[1] = 6;
refNum[2] = 10;
refNum[3] = 12;
refNum[4] = 14;
int input = Integer.parseInt(enterValue.getText()); //takes user's input
for (int x = 0; x < refNum.length; x++) {
refNum[x] = input; //Tells refNum value to be
}
searchValue = input;
index = books(refNum, searchValue); //"books" is underlined
if (index != -1) {
binarySearchField.setText("We found: " + index);
} else {
binarySearchField.setText("Sorry! Not Found!");
}
public static Boolean binarySearch(String [] refNum, int left, int right, String search){
//Boolean code for later
}
This program uses binary search to find values stored in array after user inputs number, if they match then the item is successfully found. User inputs desired number in 'enterNumber' which is a TextField. Now in my code )which I'm 78% sure will work if it wasn't for this one little thing) there is an all important that is underlined which shouldn't be, (I've commented beside the line to show)
Now I had thought I was suppose to put the class name there, but apparently since it is underlined that is not the case. Any ideas on what I should be putting there in it's place?
And I apologize for the question may be a bit misleading on what I'm really asking, I just wasn't sure how to word the question.
The line
index = books(refNum, searchValue);
seems to be underlined because you have no method called books that takes an int[] and an int as arguments in your books class definition.
Now I had thought I was suppose to put the class name there Why do you assume you have to put the class name there? Figure out what you are trying to do with this code and then you will understand what goes in that line (at least in pseudocode).
Also it seems like you have a method declared directly inside another method. That is not legal in java. If this is not the case, please show us correct code.
books is your class's name..that might be the reason you are getting this error. You can't call constructor like a method. Change class's name to Books or something else..or change method's name
How can I generate the sum of minterms (boolean algebra) in java? We can generate sum of minterms throw ANDing with (X+X'). The following example explains the algorithm for a function with three variables A,B and C:
F(A,B,C)= A + B´*C
= A*(B+B´) + B´*C
= A*B + A*B´ + B´*C
= A*B*(C+C´) + A*B´*(C+C´) + B´*C*(A+A´)
= A*B*C+A*B*C´+A*B´*C+A*B´*C´+B´*C*A+B´*C*A´
= A*B*C+A*B*C´+A*B´*C+A*B´*C´+A*B´*C+A´*B´*C
The method in java looks like this:
String generateSumOfMinterms(String termsOfTheFunction, String variables){}
// Examples for functions with 2 variables A,B
generateSumOfMinterms("A", "A,B"){
//The result should looks like this
return "A*B+A*B'";
}
generateSumOfMinterms("A+B'", "A,B"){
//The result should looks like this (repeated terms are ok for example A*B')
return "A*B+A*B'+A'*B'+A*B'";
}
// Example for a function with 3 variables A,B,C
generateSumOfMinterms("A", "A,B,C"){
//The result should looks like this
return "A*B*C+A*B*C'+A*B'*C+A*B'*C'";
}
I have tried the following:
public List<Minterm> completeMinterm(Minterm minterm, String variables){
List<Minterm> minterms=new ArrayList<Minterm>();
minterms.add(minterm);
Minterm m1=new Minterm();
Minterm m2=new Minterm();
for (int k = 0; k < minterms.size(); k++) {
//A AB--> AB+AB'
for (int i = 0; i < variables.length(); i++) {
boolean varInMinterm=false;
for (int j = 0; j < minterms.get(k).atoms.size(); j++) {
if(minterms.get(k).atoms.get(j).variable==variables.charAt(i)){
varInMinterm=true;
break;
}
}
if(!varInMinterm){
varInMinterm=false;
m1= minterms.get(k);
m1.addAtom(new Atom(variables.charAt(i),false));
m2 = minterms.get(k);
m2.addAtom(new Atom(variables.charAt(i),true));
minterms.remove(k);
minterms.add(m1);
minterms.add(m2);
k=0;
}
}
}
I used eclipse debugger to find errors, I don't understand, why the atom added to m2 is added to m1 too in the same time, when this line is run:
m2.addAtom(new Atom(variables.charAt(i),true));
Here is an outline of a possible approach: First, you should create a more convenient representation of the expression - for example, the expression could be a list of instances of a Minterm class, and Minterm could contain a list of instances of an Atom class, each of which could contain a char that tells which variable it is and a boolean that tells whether the variable is negated or not. The first thing you should do is to loop through termsOfTheFunction and create such objects that represent the expression. Then, you can loop through the minterms, and every time you see a minterm that is missing one variable, you can remove it from the list and add two new minterms with the missing variable. Finally, you can loop through the finished minterms and "print" them to a result String.
Class declarations per request and for clarity (using public fields for brevity):
public class Atom {
public final char variable;
public final bool negated;
public Atom(char variable, bool negated) {
this.variable = variable;
this.negated = negated;
}
}
public class Minterm {
public final List<Atom> atoms = new ArrayList<Atom>();
}
In generateSumOfMinterms():
List<Minterm> expression = new ArrayList<Minterm>();
Minterm currentMinterm = new Minterm();
expression.add(currentMinterm);
Then, loop through the characters of termsOfTheFunction. Each time you see a letter, look at the next character to see if it is a ´, and add an Atom with that letter and with the correct negation. Each time you see a +, create a new Minterm and add it to expression, and keep going. Afterwards, you can start analyzing the minterms and expanding them.
Edit in response to your code: Looks like you're well on your way! The reason both atoms get added to the same minterm is that both m1 and m2 refer to the k'th minterm since you say m1 = minterms.get(k); and m2 = minterms.get(k);. get() does not copy or remove an element from a list; the element will still be inside the list. So for m2, you need to create a new minterm that has all of the atoms from the old one, plus the new atom.