I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?
i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.
package Calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("(2) Convert binary to decimal");
System.out.println("\n\n Please enter your choice: ");
int choice = scan.nextInt();
if(choice == 2){
scan.nextLine();
//prompt for user input
System.out.println("Please enter a binary number: ");
String binary = scan.nextLine();
char[] binaryArray = binary.toCharArray();
int i=1;
int integer=0;
//potential problem somewhere around here?
while(i<8){
if(binaryArray[i]==0) {
++i;
}else if(binaryArray[i]==1) {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
}
System.out.println("The decimal value of the binary number is: "+ integer);
scan.close();
}
}
}
The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.
This is happening because you are reading the input, and converting into an array of char.
Anywhere where you are making your comparisons to an int, you should instead be doing a comparison to a char, by wrapping your values in single quotations.
while(i<8){
if(binaryArray[i]=='0') {
++i;
}else if(binaryArray[i]=='1') {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
Others have already pointed out that you have got confused between 0 and 1, and '0' and'1'`.
Other problems:
Your i starts at 1, so you miss the most significant bit;
You will never actually hit case 8: in the switch because of the while (i < 8) loop guard.
This doesn't work unless you enter exactly 8 bits.
You can write the entire while loop in a much more concise way:
for (int i = 0; i < binaryArray.length; i++) {
integer *= 2; // shift the digits along by 1 place
if (binaryArray[i] == '1') {
integer += 1; // set the least significant bit.
}
}
You should get away from all those switch statements.
Say you have "10101101" as input.
set val = 0;
Then either multiply by val by 2 or shift left 1 bit. They're the same. It is important
you do this before adding the next bit.
Start from the left and if it's a '1', add a 1 to val. Otherwise, add 0.
Then repeat starting at multiply until you've gone thru the string.
val should then have the decimal version when you print it.
Related
So, I made a burger class with a method for extra stuff, my question is how can I use case 0,1,2 only 1 time, like if I use case 0, I can't use it anymore, I can use only 1 and 2, If I use case 1 after 0 , then I can use only case 2 since I used case 0 and 1 before , It's possible to do something like that ? If yes how ?
The code:
boolean flag=true;
while(flag){
System.out.println("Enter your choice for extra toppings ");
int choice=scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 0:
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
case 1:
double bacon=1.05;
setAdditional(getAdditional()+bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries=0.79;
setAdditional(getAdditional()+fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag=false;
}
}
} ```
boolean flag = true;
Set<Integer> set = new HashSet<>();
while (flag) {
System.out.println("Enter your choice for extra toppings ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 0:
if (!set.contains(choice)) {
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
}
else {
System.out.println("Added already");
}
continue;
case 1:
double bacon = 1.05;
setAdditional(getAdditional() + bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries = 0.79;
setAdditional(getAdditional() + fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag = false;
}
set.add(choice);
}
}
so I did it with Set in the end, only for salad, but it's the same for the rest, if someone else needs it.
your cases go by integer numbers, so an array of boolean with 1 element for every option.
boolean[] allowed = new boolean[options]; (faster than hasMap of string to boolean).
add a check just before the "switch" statement:
if(allowed[choice] && choice != 3) {...}
you should also create an integer constant STOP_OPTION or something like that and use it in the above if-statement and in the final "case" of your switch statement. in your example, set it to 3. then later you can change it without replacing all instances of "3" in your code. but that's more of a styling suggestion.
the "flag" boolean is also redundant, the while loop can just check if choice != 3. be careful of NumberFormatExceptions!
good luck!
My teacher asked me a question and I was really confused how to write it out as a code. I understood what I had to do, but just couldn't write in Java. So the question was that: Design and implement an application that determines and prints the number of odd even and zero digits. Input could be anything from the user/keyboard. I just don't know how to start. So can someone help me here with an answer and an explanation with that?(without using string)
Thank you so much for your time.
Application? It's three lines:
int odds = str.replaceAll("[^13579]", "").length();
int evens = str.replaceAll("[^2468]", "").length();
int zeroes = str.replaceAll("[^0]", "").length();
If the input is not a string, make it one:
long number;
String str = number + "";
I would use a for loop to traverse the input string. Within the for loop would be a switch statement that increments either the 'odd' variable, the 'even' variable,' the 'zero' variable, or does nothing.
This way the string is only traversed once instead of three times.
The code would look something like:
int numOdds = 0;
int numEvens = 0;
int numZeroes = 0;
for(int i = 0; i < inputString.length(); i++) {
switch(inputString.charAt(i)) {
case '1':
case '3':
case '5':
case '7':
case '9': numOdds++;
break;
case '2':
case '4':
case '6':
case '8': numEvens++;
break;
case '0': numZeroes++;
default: break;
}
}
Looks like you have a couple answers. Here is another you may like more because you probably can understand it:
int odds, evens, zeroes;
public void setOddsEvensZereos(String str) {
for(char c:str) {
try {
int i = Integer.parseInt(c + "");
if(i == 0)
zereos++;
else if(i % 2 == 0)
evens++;
else
odds++;
} catch (Exception e){/*the character isn't a number*/}
}
}
So I am making a program in Java on a BlueJ environment that computes Binary expansion. However, I can't seem to figure out how to add powers more than 9 in the output.
If I have an input power of anything more than 9 the program goes haywire, presumably because there are no cases after 9.
Also, I personally feel my program in general is extremely inefficient but I just did it this morning and this was the first approach I saw, so if you see a way to make it more efficient than using switch case, that'd be great too.
This is my code so far. It's not all mine, but I'm not sure if intellectual property and stuff applies on here, so just putting it out there.
import java.util.*;
class Binomial_Theorem_Expansion
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the value of x in (x+a)^n");
int x=s.nextInt();
System.out.println("Enter the value of a in (x+a)^n");
int a=s.nextInt();
System.out.println("Enter the value of n in (x+a)^n");
int n=s.nextInt();
System.out.println ("The expanded answer is");
int r=0;
int powx=n;
while (r<=n)
{
long nCr=calculatenCr(n,r);
if(nCr!=-1)
{
double y=Math.pow((double)x,(double)n-r);
double z=Math.pow((double)a,(double)r);
switch (powx)
{
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
case 2: System.out.print ("("+nCr*y*z+"x\u00B2");
break;
case 3: System.out.print ("("+nCr*y*z+"x\u00B3");
break;
case 4: System.out.print ("("+nCr*y*z+"x\u2074");
break;
case 5: System.out.print ("("+nCr*y*z+"x\u2075");
break;
case 6: System.out.print ("("+nCr*y*z+"x\u2076");
break;
case 7: System.out.print ("("+nCr*y*z+"x\u2077");
break;
case 8: System.out.print ("("+nCr*y*z+"x\u2078");
break;
case 9: System.out.print ("("+nCr*y*z+"x\u2079");
break;
case 10: System.out.print ("("+nCr*y*z+"x\u2071\u00B2");
break;
}
switch (r) {
case 0: System.out.print (")");
break;
case 1: System.out.print ("y"+")");
break;
case 2: System.out.print ("y\u00B2"+")");
break;
case 3: System.out.print ("y\u00B3"+")");
break;
case 4: System.out.print ("y\u2074"+")");
break;
case 5: System.out.print ("y\u2075"+")");
break;
case 6: System.out.print ("y\u2076"+")");
break;
case 7: System.out.print ("y\u2077"+")");
break;
case 8: System.out.print ("y\u2078"+")");
break;
case 9: System.out.print ("y\u2079"+")");
break;
}
r++;
if (r<=n)
{
System.out.print ("+");
}
powx--;
}
}
}
public static long calculatenCr(int n,int r)
{
long res=1;
if(n>=r)
{
res=getFact(n)/(getFact(n-r)*getFact(r));
return res;
}
else return -1;
}
public static long getFact(int n)
{
long f=1;
for(int i=n;i>=1;i--)
{
f*=i;
}
return f;
}
}
Thanks for any constructive input. :)
presumably because there are no cases after 9.
Your code is using UNICODE superscript characters, and the cases that you have cover only numbers zero through ten for x and zero through nine for y.
You can fix this by defining a method that produces a superscript UNICODE conversion of a multidigit number, and calling it from both places where you need to produce such representation:
switch (powx) {
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
default: System.out.print ("("+nCr*y*z+"x"+toSuperscript(powx));
break;
}
The other switch (i.e. switch (r)) should be converted in a similar way.
You can implement String toSuperscript(int n) by producing a decimal representation of n, and then replacing '0' with '\u2070', '1' with '\u00B9', and so on.
Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}
Here is the code:
public static void main(String args[])
{
int i=0;
int m=0;
double scale;
boolean exit;
Shape[] s = new Shape[10];
while(exit !=true)
{
System.out.print("\nChoose an option:\n"+
"1-Add a new circle\n"+
"2-Add a new rectangle\n"+
"3-Delete all shapes\n"+
"4-Scale all shapes\n"+
"5-Display perimeter of all shapes\n"+
"6-Display the area of all shapes\n"+
"7-Enter scale factor\n"+
"8-Exit program\n");
Scanner input = new Scanner(System.in);
m=input.nextInt();
if(i<=9)
{
switch (m)
{
case 1: Circle c = new Circle(0);
s[i]=c;
i++;
break;
case 2: Rectangle r = new Rectangle(1,1);
s[i]=r;
i++;
break;
case 3: s=null;
i=0;
break;
case 4: for(i=0; i<s.length; i++)
{
s[i].scaleShape();
}
break;
case 5: for(i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getPerimeter());
}
}
break;
case 6: for(i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getArea());
}
}
break;
case 7: do
{
System.out.println("\nEnter scale factor");
scale=input.nextDouble();
}
while(scale<0);
Shape.setScaleFactor(scale);
}
break;
case 8: System.out.println("Do you want to quit?");
break; //Nothing here since loop should terminate it.
//default: System.out.println("Number must be 1-8");
// break;
}
}
}
}
Oddly the compiler is giving me an error on case 8 saying:
Type mismatch can't convert from int to boolean.
But Im not converting anything to boolean
-syntax error on token "case" assert expected
-syntax error on token :, ; expected
But all the commands there have semi-colons
expression must return a value
Why is the compiler acting so funny? Normally errors like that are easy to find. What is going on?
Your problem is in the case for 7:
case 7: do
{
System.out.println("\nEnter scale factor");
scale=input.nextDouble();
}
while(scale<0);
Shape.setScaleFactor(scale);
}
Notice the extra close brace: that's closing your switch statement, orphaning your case 8.
} // <-- Why is this here?
break;
case 8: System.out.println("Do you want to quit?");
You're ending the switch statement with an extra }. Remove it and things may work.
Every one has pointed out that you have an extra parenthesis in your code, what we've failed to point out is where it's coming from...
while(scale<0); // <-- This isn't going to work....
Shape.setScaleFactor(scale);
}
It should be...
while(scale<0) {
Shape.setScaleFactor(scale);
}
The next question is, how is scale decremented? Cause this could cause an infinite loop if you're not careful.
while(scale<0);
Shape.setScaleFactor(scale);
} // Remove this parenthesis.
break;