I've been trying this project in Blue Pelican Java for over an hour, and I'm not quite sure why it's not working. Basically what I have to do is turn a regular number into a binary number, and, assuming that 1 means the switch is open and 0 means it's closed, go through each digit in the binary number and print whether it's open or closed. They stated how they want me to do this:
"Suppose we wish to look at the third bit from the left. Use a mask as illustrated below to bitwise AND with the original number in order to look only at the third bit. 1 0 1 1 0 0 0 1bin = 177dec 0 0 1 0 0 0 0 0bin = 32dec (this is the mask)
0 0 1 0 0 0 0 0bin = 32dec = (177 & 32)
Notice this scheme of bitwise AND-ing a mask value of 32 (25, since the third bit position from the left has a positional value of 25) yields a value in the third bit position exactly equal to the third bit position of the original number. All other bit positions are guaranteed to be 0’s. Thus, this result of bitwise AND-ing can be tested to see if its entire value is 0. If it’s greater than 0, this means that the bit in the tested position was a 1."
At this point I am just testing the first number, 22, in the Switches.in folder, instead of importing the entire folder just yet, for the code. My code compiles, it begins to start printing what I want but suddenly cuts and goes to an error message that looks like this:
Switch sw57is "off
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:332)
at Tester.main(Tester.java:32)
Here's my code:
import java.io.*;
import java.util.*;
import java.text.*;
public class Tester
{
public static void main(String args[])
{
int j=22;
String jj=Integer.toBinaryString(j);
StringTokenizer sc=new StringTokenizer(jj,"");
int l=(sc.countTokens());
int a[]=new int[l];
int xx=0;
for(int x=l; x>-1; x--)
{
xx=xx++;
double p=(Math.pow(2,xx));
int pp=(int)p;
int n=((j)&(pp));
String nn=Integer.toBinaryString(n);
StringTokenizer nnn=new StringTokenizer(nn);
int po=(nnn.countTokens());
int sum=0;
System.out.println(nnn);
for(int xxx=-1; xxx<po; xxx++)
{
sum=sum+(Integer.parseInt(nnn.nextToken()));
if(sum>0)
{
System.out.println("Switch sw"+(x+56)+"is \"on");
}
else if(sum==0)
{
System.out.println("Switch sw"+(x+56)+"is \"off");
}
}
}
}
}
I'm not sure what's wrong with the code. Any advice would be greatly appreciated. Thanks, and sorry for the lengthy post!