I stack in this code I do not understand what happens in some of its lines .. I commented next to each line I did not understand it ..
here is the code
public class C
{
boolean [] b = new boolean[3]; // Is this a vector of size 3 ?
int count = 0;
void set(boolean [] x, int i)
{
x[i] = true;
++count;
}
public static void main(String [] args)
{
C ba = new C();
ba.set(ba.b, 0); // what does ba.b do?
ba.set(ba.b, 2); // what does ba.b do?
ba.test();
}
void test()
{
if ( b[0] && b[1] | b[2] ) // what is this if statement do?
count++;
if ( b[1] && b[(++count - 2)] ) // what is this if statement do?
count += 7;
System.out.println("count = " + count);
}
}
Can you discribe to me what happens there ? thanks
boolean[] b = new boolean[3] is a boolean array with 3 data points
b[0] = true; //or false
b[1] = false; //or true
b[2] = true; //or false
int count = 0; is a variable of type int
void set(boolean [] x, int i) sets a boolean array to equal true in position one. For example
set(b,1)
would set the variables to
b[1] = true
count = 1
ba is an instance of your class C. In this case it allows you to call your method set(boolean [] x, int i) and your boolean array, b from your code
Finally the first if statement if(b[0]&&b[1]||b[2]) says if(the first position, b[0] in b is true and either position two, b[1], or the third position, b[2], is true) then add one to the count variable.
The second if statement if(b[1]&&b[++count-2]) says if(the second position in the array, b[1], is true and b[count-1] is true) then add 7 to the variable count.
The last line of test() says print out the value of the variable count to the command console
Edit
A vector is another method of storing values in Java but it is not limited to one datatype, such as int or double. For example
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
Whereas an array can only hold one type of data and its size is specified when it is declared. For example
int[] intArray = new int[2];
intArray[0] = 1;
intArray[1] = 250;
or it can be declared as
int[] intArray = {1,250};
See here for more information on Vectors and here for more information on Arrays.
If you have access to a debugger, put a break point at C ba = new C(); , and then step through, it will give you an idea of what this code is doing.
hope this helps.
boolean[] b = new boolean[3]; // Is this a vector of size 3 ?
Its an array of fix size holding 3 elements
ba.set(ba.b, 0); // what does ba.b do?
It sends reference of array b defined above which holds 3 element, so when you pass that value to set method, it sets b's 0th index to true.
ba.set(ba.b, 2); // what does ba.b do?
same as above
if (b[0] && b[1] | b[2]) // what is this if statement do?
treat it like (condition1 && condition2)
if (b[1] && b[(++count - 2)]) // what is this if statement do?
treat it like (condition1 && condition2) where you are saying if b[1] is true and b[count+1-2] is true too
b is an array of booleans
ba.b points to the objects instance variable b.
b[0] && b[1] | b[2] means if b[0] is true and b[1] is true xor b[3] is true
b[1] && b[(++count - 2) means if b[1] is true and b[count - 1] is true
Generally it is not a clear code.
Specifically:
boolean [] b = new boolean[3]; // Is this a vector of size 3 ?
Yes, this line define an array of 3 boolean values. Each single value could be accessed by using selector index, starting from 0 (i.e. b[0], b[1], b[2]).
ba.set(ba.b, 0); // what does ba.b do?
Then, ba is an instance of C class. Using ba.b it is possible to access the array b defined in C. Access to single values it is possible using selectors (i.e. b.ba[0], b.ba[1], b.ba[2]).
if ( b[0] && b[1] | b[2] ) // what is this if statement do?
This statement verifies a logical condition. In this case the condition is verified if both b[0] and b[1] values are TRUE, or simple b[2] is TRUE. Otherwise the condition is not verified.
if ( b[1] && b[(++count - 2)] ) // what is this if statement do?
Really, not a good programming example. This statement verify a condition but also has a side effect of increment the value of count variable. In this case the condition is verified if both b[1] is TRUE and b[(++count - 2)] are TRUE. If count < 1 the code will exit with a RuntimeException because we are trying to access the array outside the valid range of indexes.
boolean [] b = new boolean[3]; // Is this a vector of size 3 ?
Yes, this is how you create a new array (allocates memory on heap)
C ba = new C();
ba.set(ba.b, 0); // what does ba.b do?
ba is your instantiated object from class C, in the second line you call the object's set method, passing ba.b which is your object's boolean array of size 3, and an integer (0).
if ( b[0] && b[1] | b[2] ) // what is this if statement do?
So b[0] && b[1] will be true only if b[0] is true and b[1] is also true. Let c hold this partial result. The next condition will be c | b[2].
This operation is a bitwise operation, namely XOR. It will be true if the two operands are differs from each other, otherwise it will be false. (ex. true | true = false, false | false = false, but true | false = true)
if ( b[1] && b[(++count - 2)] ) // what is this if statement do?
Simply check if both b[1] and b[++count - 2] are true.
++count means increasing the count value by one before evaluating it. Assume count = 2. Then the right side is b[1].
boolean[] b=new boolean[3];
//creates a boolean array of length 3.
Indices-0,1,2
example: b[0]=true;
b[2]=false;
C ba=new C();
C bc=new C();
ba and bc are 2 objects of class C.They can also be termed as instances.Now every instance/object of a class has it's own copy of the instance variables and the functions in the class.
That means,object ba has it's own copy of the boolean array b and object bc has it's own unique copy of boolean array b.
You refer to ba's copy of array using
ba.b and bc's copy of array using bc.b.
Both the objects have a different copy and therefore,the value of b could be different for both.
Example:
b[0]=true; //ba's copy
b[0]=false; //bc's copy
Now if that boolean array b was static,it means that only one copy of b is shared between all the objects.So static objects can not be referred using object name.It's referred using class name.
Related
I have an array of 8 booleans which I want to simply convert to a byte. Is there a simple way to do this? Or do I have to use for loop?
Personally I'd prefer a simple up to two lines solution if it exists.
Thanks for help.
EDIT: Possible duplicate is just one boolean to a byte, I have an array.
ANOTHER EDIT: I get a byte from a udp packet then I set the first bit (boolean) to false, then I would need to get a byte out of that again.
I think a loop is better, but if you must have a one liner :
byte b = (byte)((bool[0]?1<<7:0) + (bool[1]?1<<6:0) + (bool[2]?1<<5:0) +
(bool[3]?1<<4:0) + (bool[4]?1<<3:0) + (bool[5]?1<<2:0) +
(bool[6]?1<<1:0) + (bool[7]?1:0));
For the input :
boolean[] bool = new boolean[] {false,false,true,false,true,false,true,false};
you get the byte 42.
if i understood your question correct, then you want to convert a byte that is represented by it's bit pattern as an array of booleans ...
if that is the case then this is one solution :
public static void main(String[] args) {
// The integer where the result will be build up
int result = 0;
// The bit-pattern as an array of booleans
// 2^0 Position is at bools[0] !!
// so this is the byte '0 1 0 1 0 1 0 1' --> decimal : 85
boolean[] bools = new boolean[]{ true, false, true, false, true, false, true, false };
// iterate through the 'bits'
// and set the corresponding position in the result to '1' if the 'bit' is set
for (int i = 0; i < bools.length; i++) {
if (bools[i]) {
result |= 1 << i;
}
}
System.out.println(result); // Prints '85'
}
I'd do it like this:
byte b = 0;
for(int i=0;i<8;i++) if(binaryValues[i]) b |= (128 >> i);
return b;
Lets say I have four Boolean Variables,
Boolean a;
Boolean b;
Boolean c;
Boolean d;
Now, before I select one of these variables, I run a function to find out if they are true or false (it's not relevant why they are true or false).
So lets say:
a = false;
b = true;
c = false;
d = true;
Now, because b and d are true, I want to randomly select one of those two; and, if three variables are true, then I would want to randomly select one from those three.
I am lost how I would be able to accomplish this.
You can use the class java.util.Random and generate a random number and set the bound to 1. Then it generates 0 or 1. Now you can check, if the random number is 0 or 1 and if it's 0 you select b and if its 1 you select d. And the same with 3 Booleans that are true.
// Import the class
import java.util.Random;
// Create an Instance of Random
Random r = new Random();
// Generate a random number between 0 and 1
short randomNumber = r.nextInt(1);
if (randomNumber == 0)
{
// do something with b
}
if (randomNumber == 1)
{
// do something with d
}
It seems that you try to select somehow a specific Boolean variable (a, b, c, d).
However, if unboxed boolean values are assigned to Boolean variable, they will be using the same shared instance:
Boolean a = false;
Boolean b = true;
Boolean c = false;
Boolean d = true;
System.out.println(a == c); // prints true, identical Boolean.FALSE
System.out.println(b == d); // prints true, identical Boolean.TRUE
In order to be distinguished, different Boolean variables need to be created with a constructor (which is deprecated):
Boolean a = new Boolean(false);
Boolean b = new Boolean(true);
Boolean c = new Boolean(false);
Boolean d = new Boolean(true);
System.out.println(a == c); // prints false, non-identical
System.out.println(a.equals(c)); // prints true, equal
System.out.println(b == d); // prints false, non-identical
System.out.println(b.equals(d)); // prints true, equal
Now, upon ensuring that we have different Boolean objects, we can select it randomly:
public static Boolean getTrueIndexRandomly(Boolean... flags) {
List<Boolean> list = Arrays.asList(flags);
// get indexes of flags whose values are true
int[] indexes = IntStream.range(0, list.size())
.filter(list::get)
.toArray();
Random random = new Random();
int randomIndex = indexes[random.nextInt(indexes.length)]; // select one index
System.out.print("random index=" + randomIndex);
return flags[randomIndex];
}
Test:
Boolean random;
System.out.println("Selecting from b, d");
for (int i = 0; i < 4; i++) {
System.out.print("#" + (i + 1) + ": ");
random = getTrueRandomly(a, b, c, d);
System.out.println(" -> " + (random == b ? "b": "d"));
}
a = new Boolean(true);
System.out.println("Selecting from a, b, d");
for (int i = 0; i < 4; i++) {
System.out.print("#" + (i + 1) + ": ");
random = getTrueRandomly(a, b, c, d);
System.out.println(" -> " + (random == a ? "a" : random == b ? "b" : "d"));
}
Output
Selecting from b, d
#1: random index=3 -> d
#2: random index=1 -> b
#3: random index=3 -> d
#4: random index=1 -> b
Selecting from a, b, d
#1: random index=3 -> d
#2: random index=1 -> b
#3: random index=1 -> b
#4: random index=0 -> a
In trying to find to work out a programming puzzle in java, I'm getting some errors that I don't understand even though I've tried editing the code / narrowing the code down to try figure it out.
My entire program is below and can be run as soon as you paste it (main method is written with the current test parameters that I want in the method that I made already). The description of the puzzle is written in the right after the start of the class, but in short the puzzle is to make a method that takes 3 parameters a, b, and c, and the method returns the sum of these 3 unless any of them is the integer 13 - in this case this 13 and the parameters to the right are omitted from the sum.
When I try run my current test it says there is an ArrayIndexOutOfBoundsException: 3 error under the line if(x == 0 && x == 13) which is found under the for loop for(int x=0; x<params.length; x++).
I don't understand how this error is coming about - I'm adding making x the counter for the parameter inside the array, and adding 1 and 2 to it to make the elements on the right 0. I understand it could go out of bounds here but it's under an if statement that checks if the x is 13 and 0, meaning it has to only perform this when I'm checking the first param (at index 0). But for some reason it is still out of bounds, as if the it is doing the check at x>=1 where the +1 and +2 after will send it out of bounds.
Can any one see what's causing the error?
Note: My idea solving this was store the params in the array, check if they are 13, if it is make that number 0 and ones stored to its right 0, then return the sum of the array after.
public class Logic2Q3 {
/*
* Given 3 int values, a b c, return their sum. However, if one of the values is 13
* then it does not count towards the sum and values to its right do not count.
* So for example, if b is 13, then both b and c do not count.
*
* e.g.:
* luckySum(1, 2, 3) -> 6
* luckySum(1, 2, 13) -> 3
* luckySum(1, 13, 3) -> 1
*
*/
public int luckySum(int a, int b, int c) {
int[] params = new int[3]; // array to store params
int sum = 0; // for storing the final sum
// store params for checking here
params[0] = a;
params[1] = b;
params[2] = c;
// check the array of parameters and alter them according to specs
for(int x=0; x<params.length; x++) {
// in the case 13 is found
if(params[x] == 13) {
// case that it's the first element (a) and is also the 13
if(x == 0 && x == 13)
// make both elements on the right 0 to not add to the sum
params[x] = 0;
params[x+1] = 0;
params[x+2] = 0;
// case that it's the second element (b)
if(x == 1 && x == 13)
// make only the element on the right 0
params[x] = 0;
params[x+1] = 0;
}
}
// after the array is altered to omit a, b, and c being 13 or to the right of 13, sum everything
for(int x=0; x<params.length; x++) {
// += must be used on initialised instance variable only
sum += params[x];
}
return sum;
}
public static void main(String[] args) {
Logic2Q3 test = new Logic2Q3();
System.out.println(test.luckySum(3,13,7));
}
}
the second time your for-loop runs, if param[x] equals 13 or any time later than 0, the line params[x+2] = 0 is always executed! please read a coding guideline for java and never ever use an if-statement without setting the correct scope with {//if statement stuff} !!!
After reading the guidelines you should be able to solve your problem!
EDIT: in addition those if statements can never be true! x cannot equal 0 and 13 at the same time
Whilst your code potentionally creates a IndexOutOfBoundExeption because you do access the values at either x+1 or x+2 there are also other mistakes. There are missing paranthesis and the if condition will never be true, as you check if one value will be equal to two values (unlogical right?).
All in all my best guess is, that you are making this complete luckySum "puzzle" a bit to complicate, because all you actually need is one loop and a variable sum. Once you found a value you can simply break out of the loop and return the sum. HereĀ“s a more simplified version of what you are doing.
public static void main(String[] args) {
System.out.println(luckySum(1, 2, 3));
System.out.println(luckySum(1, 2, 13));
System.out.println(luckySum(1, 13, 3));
}
/**
* Given 3 int values, a b c, return their sum. However, if one of the values is 13
* then it does not count towards the sum and values to its right do not count.
* So for example, if b is 13, then both b and c do not count.
*
* e.g.:
* luckySum(1, 2, 3) -> 6
* luckySum(1, 2, 13) -> 3
* luckySum(1, 13, 3) -> 1
*
*/
public static int luckySum(int... values) {
// Using varargs for dynamic amound of values
// Sum variable
int sum = 0;
// loop over all values
for(int x=0; x<values.length; x++) {
// in the case 13 is found break out of the loop
if(values[x] == 13) {
break;
// As a second option you could just return sum here
// return sum;
}
// add value to the sum
sum += values[x];
}
return sum;
}
O/P
6
3
1
This question already has answers here:
post increment operator java
(3 answers)
Closed 9 years ago.
public static void main(String[] args) {
int a = 1;
int b = a++;
System.out.println(b);
}
Why does the code above print 1? I was told that a++ means you would get the value of a. then increment it. But the code above never incremented a and just printed 1. Could someone please explain what is going on here?
It works as expected; Here is the code explained:
public static void main(String[] args) {
// a is assigned the value 1
int a = 1;
// b is assigned the value of a (1) and THEN a is incremented.
// b is now 1 and a is 2.
int b = a++;
System.out.println(b);
// if you had printed a here it would have been 2
}
This is the same code but with pre-increment of a:
public static void main(String[] args) {
// a is assigned the value 1
int a = 1;
// a is incremented (now 2) and THEN b is assigned the value of a (2)
// b is now 2 and so is a.
int b = ++a;
System.out.println(b);
// if you had printed a here it would have been 2 so is b.
}
int b = a++ is equivalent to int b = a; a += 1. When you print b, a==2 && b==1
a++ is like saying a-then increment a by 1. So after you say b = a++, b = 1 and a = 2.
If you were to preincrement b = ++a, you would get b = 2 Preincrement increases before it assigns value.
Conclustion
a++ assign value before incrementing
++a increments, then assigns value.
The reason is is as follow.
If it is i++, then equalent code is like this.
result = i;
i = i+1;
return result
If it is ++i. then the equlent code is like this.
i=i+1;
result =i;
return i
So considering your case, even though the value of i is incremented, the returned value is old value. (Post increment)
Post Increment Meaning = First complete assignment then Increment.
Pre Increment Meaning = First Increment then assign .
ex:
int a=0,b;
b=a++; // ie. Step1(First complete assignment): b=0, then a++ ie a=a+1; so a=1 now.
System.out.println(b); // prints 0
System.out.println(a); // prints 1
if
int a=0,b;
b=++a; // ie. Step1(First Increment ): a++ ie a=a+1; so a=1 now, b=a , ie b=1.
System.out.println(b); // prints 1
System.out.println(a); // prints 1
my code is:
public class Box
{
public static void main(String[] args)
{
Integer z = new Integer(43);
z++;
Integer h = new Integer(44);
System.out.println("z == h -> " + (h == z ));
}
}
Output:-
z == h -> false
why the output is false when the values of both the objects is equal?
Is there any other way in which we can make the objects equal?
No. Use h.equals(z) instead of h == z to get the equality behavior you expect.
h == z would work only if you assign the value via auto-boxing (i.e Integer a = 43) and the value is in between -128 and 127 (cached values), i.e:
Integer a = 44;
Integer b = 44;
System.out.println("a == b -> " + (a == b));
OUTPUT:
a == b -> true
If the value is out of the range [-128, 127], then it returns false
Integer a = 1000;
Integer b = 1000;
System.out.println("a == b -> " + (a == b));
OUTPUT:
a == b -> false
However, the right way to compare two objects is to use Integer.equals() method.
Integer is Object not primitive (int) And Object equality compare with equals method.
When you do z == h it will not unbox into int value unless it checks both Integer reference(z & h) are referring same reference or not.
As it is derived in documentation -
The result is true if and only if the argument is not null and is an
Integer object that contains the same int value as this object.
System.out.println("z == h -> " + h.equals( z));
It will print true.
You are trying to compare two different object and not their values. z and h points to two different Integer object which hold same value.
z == h
Will check if two objects are equal. So it will return false.
If you want to compare values stored by Integer object use equals method.
Integer z = new Integer(43); // Object1 is created with value as 43.
z++; // Now object1 holds 44.
Integer h = new Integer(44); // Object2 is created with value as 44.
So at the end we have two different Integer object ie object1 and object2 with value as 44.
Now
z = h
This will check if objects pointed by z and h is same. ie object1 == object2
which is false.
If you do
Integer z = new Integer(43); // Object1 is created with value as 43.
z++; // Now object1 holds 44. Z pointing to Object1
Integer h = z; // Now h is pointing to same object as z.
Now
z == h
will return true.
This might help http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
Integer is an object, not a primitive. If z & h were primitives, == would work just fine. When dealing with objects, the == operator doesn't check for equality; it checks if the two references point to the same object.
As such, use z.equals(h); or h.equals(z); These should return true.
Read this: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html
Integer is Object you compare address/references/pointers of objects not values.
Integer a = Integer(1);
Integer b = Integer(1);
a == b; // false
a.compareTo(b); // true
check to make sure you can use z++ on the Integer object.