I have made a class called Iset that takes integers and modifies it's boolean array's index equivalent to the integer to true.
e.g. If I pass an integer 1 then the boolean array setI[1] is turned to true.
I have a method called include that returns true if the provided integer is in there and false if it isn't. However no matter what I do I always get true. I have made sure that everything in the array is set to false and I add in a number further up the code. Obviously I'm missing something really obvious here:
public class Iset {
public int size;
boolean[] setI;
Iset(int a) {
this.size = a;
this.setI = new boolean[size];
}
public boolean include(int i) {
for (int n = 0; n <= size; n++) {
if (setI[n]== setI[i]){
return true;
}
}
return false;
}
}
Please try this code, I think you should add a funktion: set(), and change a little of the include(int i)
public class Iset {
public int size;
boolean[] setI;
Iset(int a) {
this.size = a;
this.setI = new boolean[size];
}
public boolean include(int i) {
return setI[i];
}
//set your values in the boolean array "setI" to "true"
public void set(int... values) {
for (int i : values) {
setI[i] = true;
}
}
public static void main(String[] args) {
Iset mm = new Iset(100);
mm.set(25, 40, 22);
System.out.println(mm.include(25));
}
}
The other answers have given solutions, but I think we can also get an explanation going as to why your original code was slightly wrong as you say. Here is what your include() method is doing in pseudocode:
for each boolean called 'setI[n]' in the array:
if 'setI[n]' is the same as the boolean at 'setI[i]':
return true
So, it's not actually checking if either of those boolean are true or false, it's just checking if they are the same. This method will always return true unless the boolean at index i is the only one in the array with its value (I'd suggest trying that to see if I am right). For example, if i = 1 your method will return true for:
[false, true, false, false, ...]
[true, false, true, true, ...]
... and no other values.
Hopefully this makes things a little clearer.
You don't have to walk over the complete array, just ask the method if your number is included.
public boolean isIncluded(int i) {
if (setI[i] == true){
return true;
}
return false;
}
or even simpler:
public boolean isIncluded(int i) {
return setI[i];
}
P.S. I changed your method name to something more meaningful
Try this:
public boolean include(int i) {
if (i >= size){
// To avoid ArrayIndexOutOfBoundsException
return false;
}
return setI[i];
}
I'm not completely sure what you are after for, but, in you for-loop you are making a selfcomparison when n == i and thus return true always.
Related
The program's purpose was to teach me how to create a character list, and practice using toString and booleanequals(object other).
public class CharList {
private char[] Array = new char[100];
private int numElements = 0;
public CharList() {
}
public CharList(String startStr){
Array=startStr.toCharArray();
}
public CharList(CharList other){
other.Array=new char[100];
}
public void add(char next) {
Array[numElements++] = next;
}
public char get(int index) {
return Array[index];
}
private int size() {
return numElements;
}
#Override
public String toString() {
String str = new String(Array);
return str;
}
public boolean equals(Object other) {
if(other == null) {
return false;
}
if(other instanceof CharList == false) {
return false;
}
else {
CharList that = (CharList) other;
return this.Array == that.Array ;
}
}
public static void main(String[] args) {
System.out.println("uncomment the code to use the charListDriver");
CharList a = new CharList();
CharList b = new CharList("Batman");
CharList c = new CharList(b);
a.add('k');
a.add('a');
a.add('t');
a.add('n');
a.add('i');
a.add('s');
System.out.println("a is :"+a.toString() +" and has " + a.size() + " chars");
System.out.println("b is :"+b.toString() +" and has " + b.size() + " chars");
System.out.println("c is :"+c.toString() +" and has " + c.size() + " chars")
System.out.println("B and A are equal : " + b.equals(a));
System.out.println("B and C are equal : " + b.equals(c));
}
}
my output is:
a is: katnis and has 6 chars
b is: and has 0 chars
c is: and has 0 chars
The main function was provided for me by my instructor. I don't understand why it is not printing out "batman".
The issue is with your constructor that takes a CharList
public CharList(CharList other){
other.Array=new char[100];
}
You see that it is setting other.Array equal to a new array of size 100.
So when you do this
CharList c = new CharList(b);
You are setting the Array of b to be a new array wiping out the array that contained the characters from "Batman".
If you fix the constructor in question to be
Array = other.Array.clone()
it'll fix the problem. I cloned the other array so that b and c aren't pointing to the exact same array. If they were then when you added chars to one, it would add chars to the other as well.
Next you'll see an issue with your size() method. It returns numElements but numElements isn't set in your constructors that take a String or a CharList so it's always 0. So be sure to set numElements in those constructors. You'll see that because of this error that when you call add on a CharList that was initialized form a String it changes the first char instead of adding it to the end.
I've only really answered the question about Batman and then size. But there are several other issues with this code as well.
What happens if someone calls add more than 100 times on a CharList initialized with default constructor
equals method is doing a reference equality check rather than making sure the chars in the arrays are identical
What happens when you call add to a CharList instantiated with String or CharList? As I noted it currently changes the char at index 0. But even if you fix that and set numElements correctly what will happen? It'll try to write past the end of the Array.
2 Things to go over (plus a 0th thing):
0)
You need to have a getArray() function. Because Array is marked private, there is no way to access it from the outside. You can write other.Array, but because Array is private, it is better practice to use a getArray function. Adding a getArray() is the way to go. (it would be simple, and look like: getArray() {return this.Array;})
1)
Your constructors that you wrote that looks like:
public CharList() {
}
public CharList(CharList other){
other.Array=new char[100];
}
is wrong.
You should change these like so:
public CharList() {
this.Array=new char[100];
}
public CharList(CharList other){
this.Array=other.Array;
}
Here, we made the empty constructor initialize to a set char length of 100. For the other, we made it so that this.Array = other.Array by using other.getArray().
Now, if you try this, it should work.
2)
Lets say you had this:
CharList batman1 = new CharList("batman");
CharList batman2 = new CharList("batman");
Then, java batman1.equals(batman2) would return false. This is because of pointers in java, and the way variable assignment works. for batman1.Array to equal batman2.array, it is not enough for their values to be equal. They also have to have to be pointing to the same thing. See Shallow copy for arrays, why can't simply do newArr = oldArr? for more info.
To fix this, we need a getArray(). Assuming we have it:
public boolean equals(Object other) {
if(other == null) {
return false;
}
if(!(other instanceof CharList)) {
return false;
}
if(other.size()!=this.size()) {
return false;
}
CharList that = (CharList) other;
for (int i=0; i<other.size(); i++) {
if (that.get(i)!=other.get(i)) return false;
}
return true;
}
I did a lot of things here. First, we cleaned up the if statements. You don't need that else at the end. Then, I implemented what is known as a shallow check. It checks if the two Arrays have the same values. If everything is the same, then return true.
If you have followed all of these steps, then it should work.
I've got array. I've got an isFull method, which checks if the array is full, but I don't know how to use this to check if it's full, then if it's not full add to the array, otherwise disregard the add call.
The array should take 10 elements and then not accept any more. After 10 elements, it should 'be full' and disregard any addSpy calls.
How would you implement this?
public class ConcreteSubject extends AbstractSubject {
public int arySize;
private int i = 0;
private static AbstractSpy[] spies;
public ConcreteSubject(int a) {
arySize = a;
spies = new AbstractSpy[a];
}
#Override
public void addSpy(AbstractSpy spy) {
if (spies.length < 10) {
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
public void isFull() {
//1
boolean b = false;
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
b = true;
}
}
if (!b) {
System.out.println("Array is full");
} else {
System.out.println("Array not full");
}
}
public class TestSpies {
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject(10);
AbstractSpy spy = new ConcreteSpy();
AbstractSpy[] spies = new AbstractSpy[10];
cs.addSpy(spy);
cs.addSpy(spy);
cs.addSpy(spy);
cs.isFull();
}
}
spies.length < 10 isn't correct. It should be spies.length > 0 && i < spies.length to make sure that the following assignment spies[i] = spy; is always valid.
void isFull() should be boolean isFull(). Your implementation looks OK, just return b. full is a tricky word because technically an array is always "full". A better adjective would be populated, filled.
Since addSpy isn't filling null gaps but simply adds a spy to the end, isFull could be rewritten to return spies.length == i;.
The simplest way of doing it would be like that:
#Override
public void addSpy(AbstractSpy spy) {
if (!isFull())
{
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
To use that, you should change your isFull method to:
public boolean isFull() {
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
return false;
}
}
return true;
}
Keep a track of the number of filled cells of the array using a variable. And before inserting anything into it, check if the filled cells count strictly less than the size of the array (obviously you want to keep track of the array total size as well).
I am making a method of a class that takes two integers as arguments. It checks every single digit of the first one and makes sure they are less than or equal to the second one.
public static boolean digitRange(int x, int limit) {
String number= Integer.toString(x);
char[] digits=number.toCharArray();
boolean result=false;
for(char c: digits) {
if(Integer.parseInt(String.valueOf(c))>limit) {
result=false;
}
}
return result;
}
The expected output for say 0 and 5 would be:
public static void main(String[] args){
System.out.println(digitRange(0,5));//0 is les than or equal to 5.
//Therefore true is printed.
}
However, I am getting false in every single scenario and I cannot find why.
Could someone help me correct the digitRange method, please.
String number= Integer.toString(x);
char[] digits=number.toCharArray();
boolean result=false;
for(char c: digits) {
if(Integer.parseInt(String.valueOf(c))>limit) {
result=false;
}
}
return result;
You never set result to true anywhere. Change to
boolean result=true;
However, consider a totally different approach:
public static boolean digitRange(int x, int limit)
{
int t = Math.abs(x);
while (t > 0)
{
if (t % 10 > limit)
return false;
t /= 10;
}
return true;
}
You never set the result value to true. Simply return once you have established false as you no longer need to check, and if you make your way out of the iteration return true.
public static boolean digitRange(int x, int limit) {
String number= Integer.toString(x);
char[] digits=number.toCharArray();
for(char c: digits) {
if(Integer.parseInt(String.valueOf(c))>limit) {
return false;
}
}
return true;
}
The function accepts two numbers and checks each digit is within the range of the second number and return true if all digits are less than the second number or it returns false.
public boolean check(int one,int two){
while(one>0){
if(one%10>two)
return false;
one=one/10;
}
return true;
}
getting compile errors and just cannot get this code to work the way I need it to, it's beginning to drive me mad! Basically I am trying to get my boolean array in my method to iterate through the array, find out if False is listed more consecutively or if True is and return either true or false. In my program the array i have listed should return false. Any ideas? thanks in advance.
public class trueOrfalse
{
public static void main(String [] args)
{
boolean[] guess = {false,true,false,false,false,true,true};
boolean result = longerTF(guess);
}
public static boolean longerTF(boolean[] guess)
{
int variable = 0;
for(int x = 0; x < guess.length; x++)
{
if(guess[x] > true)
{
return true;
}
else
{
return false;
}
}
}
i don't know where to start
first of all this is wrong
if(guess[x] > true)
it should be
if(guess[x]==true)
since an if statement expects a boolean result and you have boolean values in your array this will have the same effect
if(guess[x])
you also missed a case. when the array is empty you would never run into the for loop, but your method still needs to return a boolean value. you could throw a runtime-exception or a default value like return false; at the end of your method
your for-loop does not make sense, since your method will return a result within the first iteration (if the array is not empty). your longerTF method could be also looking like this
public static boolean longerTF(boolean[] guess) {
if(guess.length>0)
return guess[0];
throw new IllegalArgumentException("The array must not be empty");
}
i'd suggest a general book like "programming: Learn the Fundamentals of Computer Programming Languages". you need to understand first the basics of programming before you try to implement anything.
The comparison​ operators >, etc., are neither legal nor meaningful for boolean operands. What did you intend guess[x] > true to accomplish?
Since guess is a boolean[] you are allowed to test
if (guess[x])
or
if (! guess[x])
and to
return guess[x];
EDIT
You want the loop to count consecutive values. This loop does not, but it shows how such a structure works for a simpler problem.
public boolean dominant(boolean[] guess) {
int tCount = 0;
for (int ix = 0; ix < guess.length; ++ix) {
if (guess[ix]) {
++tCount;
}
}
return tCount >= guess.length / 2;
}
Here is a "corrected" version:
public class trueOrfalse {
public static void main(String[] args) {
boolean[] guess = { false, true, false, false, false, true, true };
boolean result = longerTF(guess);
}
public static boolean longerTF(boolean[] guess) {
int variable = 0;
for (int x = 0; x < guess.length; x++) {
if (guess[x]) {
variable++;
}
}
return (variable > (guess.length-variable));
}
}
You forgot one closing braket }, a return statement and boolean compare cannot be with < or >.
As mentioned by everyone above. You can't use > to compare two booleans.
For your purpose to count the number of consecutive true/false, you need two different counters. You can run a loop and keep incrementing the counter as you encounter repeated item of true/false, if not you can just reset the counter to 1. I have put on a hasty solution below to give you an idea. I haven't tested it well it seems to work. Hope this helps.
public class trueOrfalse {
public static void main(String[] args) {
boolean[] guess = { false,true,false,false,false,true,true };
boolean result = longerTF(guess);
System.out.println("result: " +result);
}
public static boolean longerTF(boolean[] guess) {
int consecutiveFalseCount = 1;
int consecutiveTrueCount = 1;
for (int x = 0; x < guess.length; x++) {
if (guess[x] == true) {
if(x!=0 && x<guess.length){
if(guess[x-1] == true){
consecutiveTrueCount = consecutiveTrueCount + 1;
} else {
consecutiveTrueCount = 1;
}
}
} else {
if(x!=0 && x<guess.length-1){
if(guess[x-1] == false){
consecutiveFalseCount = consecutiveFalseCount + 1;
} else {
consecutiveFalseCount = 1;
}
}
}
}
System.out.println("Consecutive True count: " +consecutiveTrueCount);
System.out.println("Consecutive False count: " +consecutiveFalseCount);
if(consecutiveTrueCount>consecutiveFalseCount){
return true;
} else {
return false;
}
}
}
The one main thing I want to avoid while Java programming is excessive boolean variable declarations like this:
public static boolean mytruebool = true, myfalsebool = false, myothertruebool = true, myotherfalsebool = false;
Is there an efficient way (perhaps w/ array usage) of declaring and assigning variables? Any help is greatly appreciated!
If these are fields (static or otherwise), boolean will have an initial value of false. At that point, you set them according to the needs of your program. So at least, you don't have to worry about half of your boolean fields.
If you're discovering that you have too many boolean fields, then you may want to reconsider the design of your program instead of pre-initializing your values.
If you are comfortable with bit manipulation, you can store all your booleans as a single integer. In this case, you can store your initial state (and other various states) of all the "variables" as a single integer value.
boolean firstVar = false;
boolean secondVar = true;
boolean thirdVar = true;
...can become...
public class Test {
public static final int INITIAL_STATE = 6;
private static int myVar = INITIAL_STATE;
public static boolean getVar(int index) {
return (myVar & (1 << index)) != 0;
}
public static void setVar(int index, boolean value) {
if (value) {
myVar |= (1 << index);
} else {
myVar &= ~(1 << index);
}
}
public static void printState() {
System.out.println("Decimal: " + myVar + " Binary: " + Integer.toBinaryString(myVar));
}
public static void main(String[] args) {
System.out.println(getVar(0)); // false
System.out.println(getVar(1)); // true
System.out.println(getVar(2)); // true
printState();
setVar(0, true);
System.out.println(getVar(0)); // now, true
printState();
}
}
Learn more about bit manipulation here: Java "Bit Shifting" Tutorial?
This should work ; tested already;
boolean mytruebool,myothertruebool;
mytruebool = myothertruebool= true;
boolean myfalsebool,myotherfalsebool;
myfalsebool=myotherfalsebool=false;