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.
Related
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.
This question is regarding switch statement. These are a few similar posts on this (below) but I am still having trouble understanding.
Using user-inputted characters in If/Switch statements
How do I used a char as the case in a switch-case?
Multiple characters in a switch statement?
Please consider the following:
public class main
{
public int selection;
public main()
{
System.out.println("MENU");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
doSomething();
break;
case 2:
case 3:
default:
System.out.println("Instruction is invalid");
}
}
while (selection !=7);
{ System.exit(0); }
}
public static void showMenu()
{
System.out.print('\u000c');
System.out.println("option 1 \n");
System.out.println("option 2 \n");
System.out.println("7 - exit.\n");
System.out.println("Select Option:\n");
}
}
So this is a switch statement is for the user to choose options within the do while loop. The user enters an integer from the printed list to choose an option, after completion of the case, it loops back to menu.
My teacher informs me that its better practice to use char instead of int to get user input for the switch. I expect it to look something like this, but it doesn't work and I'm not sure why.
public class main
{
public int selection;
public main()
{
System.out.println("MENU");
Scanner in = new Scanner(System.in);
do {
showMenu();
String menu = "";
char selection = menu.charAt();
switch (selection)
{
case 'A':
doSomething();
break;
case 2, 3, 4, 5, 6
default:
System.out.println("Instruction is invalid");
}
}
while (selection != 'QQ');
{ System.exit(0); }
}
In the second link posted there was an answer which i think suggested using
hello.charAt(0)
as the switch condition?
switch (hello.charAt(0))
{
case 'a': ... break;
}
I have three specific questions on this code:
1) My code doesn't work. Should my condition be hello.charAt(0) ?
2) I would like to use QQ as the quit option on the switch. Is possible with the code above? From the second link, I think it should be fine.
3) It is also shown here (switch statement using char in the case condition?) that the case statement should have double quotations. Could someone please clarify this as well?
Something like this should work better:
do {
showMenu();
String menu = in.nextLine(); // read a line of input
char selection;
if (menu.length>0) selection = menu.charAt(0); // extract the first char of the line read
else selection = '\0'; // special char when input is empty...
switch (selection) {
case 'A': case 'a':
doSomething();
break;
case 'Q': case 'q':
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 'Q' && selection != 'q');
menu stores the full input line. selection would be the first char (if it exists) of the line.
To use .charAt() you need to supply the index - so if you want to use the first character then use 0, etc.
In general one read an entire line instead of a single keystroke:
The first char of a String is gotten by charAt(0). However the string
could have length 0. There is the if-expression CONDITION ? TRUEVALUE : FALSEVALUE.
String menu = in.readLine();
char selection = menu.isEmpty() ? ' ' : menu.charAt(0);
switch (selection) {
case 'A':
doSomething();
break;
case '2':
case '3':
case '4':
...
break;
default:
System.out.println("Instruction is invalid");
}
There is an even more succint solution:
String menuSelection = in.readLine();
switch (menuSelection) {
case "A":
doSomething();
break;
case "2":
case "3":
case "4":
...
break;
default:
System.out.println("Instruction is invalid");
}
The following code should print whether intenger value is odd or even with fall through switch statement and for statements
for(int i=2; i<=10; i+=2)
{
switch(i)
{
case 1:
{System.out.printf("\nNot printing odd numbers");}
case 2:
System.out.printf("\n %d is an even number.", i);
//case 3:
//case 4:
}//end switch
}//end for
Change i+=2 to i++ and i+=2 will give you value of i as 2,4,6,8,10 which means only even numbers.
switch(i%2)
{
case 0:
//even number
break;
case 1:
//Odd Number
break;
}
There is no need given your for loop,
for(int i=2; i<=10; i+=2)
i will not be odd. Based on your switch and problem statement I think you wanted,
for(int i=1; i<=10; i++) {
switch(i) {
case 2: case 4: case 6: case 8: case 10:
System.out.printf("\n %d is an even number.", i);
break;
default:
System.out.printf("\nNot printing odd numbers");
}
}
I believe a fall-through switch should look like this. I have ommitted your outer for loop for simplicity.
switch (i)
{
case 1:
case 3:
case 5:
case 7:
case 9:
System.out.printf("\nNot printing odd numbers");
break;
case 2:
case 4:
case 6:
case 8:
System.out.printf("\n %d is an even number.", i);
break;
}
You essentially Fallthrough some cases (all odd numbers and all even numbers). Hence the term. You can read more about fallthrough here.
for (int i = 2; i <= 10; i++) {
switch (i % 2) {
case 0: // even number
System.out.printf("\n %d is an even number.", i);
break;
case 1: // odd number
System.out.printf("\nNot printing odd numbers");
break;
}// end switch
}// end for
Try this
for (int i = 2; i <= 10; i++) {
switch (i % 2) {
case 0:
System.out.printf("\n%d is an even number.", i);
break;
case 1:
System.out.printf("\nNot printing odd numbers");
break;
}// end switch
}// end for
}
nt num=10;//any number you want
nt last=num%10;
switch(last)
{
case 0:
case 2:
case 4:
case 6:
case 8:
System.out.println("numbet is even" +num) ;
break ;
default :
System.out.println("number is odd" +num)
}
//end of switch block
//odd or even using fall through language java
//GAGAN GANJWAR
I only need help with the input part. If the user inputs a number I need the program to read and output a case that equals the number that was input.
//This program will display the months of the year
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
int month;
System.out.println("Please enter a Month Number: ");
month = (int) System.in.read(); //Get an integer
switch (month) {
case 1: System.out.println("January");
break;
case 2: System.out.println("February");
break;
case 3: System.out.println("March");
break;
case 4: System.out.println("April");
break;
case 5: System.out.println("May");
break;
case 6: System.out.println("June");
break;
case 7: System.out.println("July");
break;
case 8: System.out.println("August");
break;
case 9: System.out.println("September");
break;
case 10: System.out.println("October");
break;
case 11: System.out.println("November");
break;
case 12: System.out.println("December");
break;
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}
Try using the Console class instead: http://docs.oracle.com/javase/6/docs/api/java/io/Console.html to obtain user input, then convert the String to a number with Integer.parseInt(String)
Also, be aware that the next version of Java (8) will support Strings in case blocks.
class vehicle
{
int passengers;
int fuelcap;
int mpg;
}
import java.io.*;
class Vehicle_Demo
{
public static void main (String args[]) throws java.io.IOException
{
vehicle obj1 = new vehicle();
obj1.passengers=12;
obj1.fuelcap=9;
obj1.mpg=78;
System.out.println(obj1.passengers, obj1.fuelcap, obj1.mpg);
}
}
You can use Scanner to read your System.in
Scanner input = new Scanner(System.in);
month = input.nextInt();
Output:
Please enter a Month Number:
1
January
See related
Edit:
as noahz pointed out there is a Console class that covers the same functionality. For an idea of the difference between the two, read this.
Try to use TextIO Input Functions
This is better than scanner input
You need to compile TextIO.java fist as a prerequisite so that TextIO.class must be found in the same folder.
use this input function instead:
month = TextIO.getChar();
Please let me know if you have problems on this method.
Thanks!
Correct me if I'm wrong, but I'm pretty sure it will still work with "system.in.read". You're switch cases do not have single quotes around the input you want to be processed. If you want case one to be run when you type '1' your case should be case '1', not case 1.
There problem here was Java have cast a character to an integer, therefore you get an ASCII value.
For instance, when you type 5 you've got 53 in ASCII. Check it taking the variable value in System.out.println();
I've tried to solve that changing month to a char type and then passing a char value to the switch control. But the problem is, getting System.in.read(); method you just can get a single character. At last you just can select between 1 to 9.
I suspect the solution is using a buffer reader. Until then, I leave you here my code:
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
char month;
System.out.println("Please enter a Month Number: ");
month = (char) System.in.read(); //Get an integer
//System.out.println("Actual value of :" + month);
switch (month) {
case '1': System.out.println("January");
break;
case '2': System.out.println("February");
break;
case '3': System.out.println("March");
break;
case '4': System.out.println("April");
break;
case '5': System.out.println("May");
break;
case '6': System.out.println("June");
break;
case '7': System.out.println("July");
break;
case '8': System.out.println("August");
break;
case '9': System.out.println("September");
break;
/*case '10': System.out.println("October");
break;
case '11': System.out.println("November");
break;
case '12': System.out.println("December");
break;*/
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}
Here I have some problem when I use while loop in switch statement using dialog boxes. Some statements are unreachable and dialog boxes not appeared. Please help me! And also can do some correction on my code.
This the simple code that I made:
public static void main(String[] args)
{
// prompt and read first number from user
String no = JOptionPane.showInputDialog(null, "Enter the number");
int num = Integer.parseInt(no); //convert string to number
switch (num)
{
//display result
default: JOptionPane.showMessageDialog(null,"fail"); break;
case 1: JOptionPane.showMessageDialog(null,"c=a+b"); break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
}
}
The cases in a switch/case are evaluated in the order you put them. default matches all cases. Since you have that first and that case does something before breaking out of it, the other cases will never be reached. Try this instead:
case 1: JOptionPane.showMessageDialog(null,"c=a+b"); break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
default: JOptionPane.showMessageDialog(null,"fail"); break;
Your code does not show a while loop anywhere. Perhaps you can update with the code you attempted.
switch (num)
{
case 1:
while(!your condition)
{
JOptionPane.showMessageDialog(null,"c=a+b");
}
break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
default: JOptionPane.showMessageDialog(null,"fail"); break;
}
Retype the code:
// prompt and read first number from user
String no = JOptionPane.showInputDialog(null, "Enter the number");
int num = Integer.parseInt(no); //convert string to number
while (num<=4)
{
if
switch (num)
{
//display result
case 1: JOptionPane.showMessageDialog(null,"c=a+b"); break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
default: JOptionPane.showMessageDialog(null,"fail"); continue;
}
}// end method main
}// end class abc