How to catch odd numbers using switch - java

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

Related

How to create a program that converts binary to decimal

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.

Switch Statement and Case

I am making code for my CPSC class and I have to print up to a case number that is set for the int. When I enter "2", the code prints "two potato" eight times instead of "One potato, two potato".
Here is my code I have:
public class Potato {
public Potato() {
}
public void count(int c) {
for (int i = 0; i < 8; i++) {
switch (c % 8) {
case 1: System.out.println("One potato"); break;
case 2: System.out.println("two potato"); break;
case 3: System.out.println("three potato"); break;
case 4: System.out.println("four..."); break;
case 5: System.out.println("five potato"); break;
case 6: System.out.println("six potato"); break;
case 7: System.out.println("seven potato"); break;
case 8: System.out.println("more!"); break;
default: break;
}
}
}
}
I think my problem is my for-loop, not too sure though, since I am here asking for help. Thanks in advance!
It is because c % 8 (2 % 8 = 2), so in every loop it will execute case 2 and prints two potato. You could use i % 8 instead.
This should do the trick. As others have said, you should use i%8. However, for this to work you should also start with i=1 since 0%8 = 0. And your case 8 should be changed to case 0.
for (int i = 1; i <= c; i++) {
switch (i % 8) {
case 1: System.out.println("One potato"); break;
case 2: System.out.println("two potato"); break;
case 3: System.out.println("three potato"); break;
case 4: System.out.println("four..."); break;
case 5: System.out.println("five potato"); break;
case 6: System.out.println("six potato"); break;
case 7: System.out.println("seven potato"); break;
case 0: System.out.println("more!"); break;
default: break;
}
}
This code is... peculiar:
The main problem is that you are not using the i variable that is incremented at the for loop. Instead, you are using c variable:
switch (c % 8)
Should be:
switch (i % 8)
You don't need the case 8 since there is no way that i % 8 result in 8. And, looks like you don't need c variable at all.

How to put characters beyond 9 in superscript in java?

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.

why is the wrong "case" being executed after "default" in a switch statement

How is it possible that the output is 1002,why is the last case being executed despite having a mismatch?
public class Main {
public static void main(String[] args) {
int i=0,j=0;
switch (i) {
case 2 : j++;
default: j+=2;
case 15 : j+=1000;
}
System.out.println("j="+j);
}
}
FALLTHROUGH:
Another point of interest is the break statement. Each break statement
terminates the enclosing switch statement. Control flow continues with
the first statement following the switch block. The break statements
are necessary because without them, statements in switch blocks fall
through: All statements after the matching case label are executed in
sequence, regardless of the expression of subsequent case labels,
until a break statement is encountered.
Your code should be:
case 2 : j++; break;
case 4: j+=10; break;
default: j+=2; break;
case 15: j+=1000;
}
FROM DOCS
public class Example{
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
This is the output from the code:
August
September
October
November
December
You have to break at the end of the case blocks. Otherwise all subsequent cases will be also executed.
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
int i=0,j=0;
switch (i){
case 2 : j++; break;
case 4: j+=10; break;
case 15 : j+=1000; break;
default: j+=2;
}
System.out.println("j="+j);
}
}
Because you are missing break;
and if I understand your confusion, The order of default doesn't matter. In below case,
int i=15,j=0;
switch (i){
case 2 :
j++;
break;
case 4:
j+=10;
break;
default:
j+=2;
break;
case 15 :
j+=1000;
break;
}
j will be having value 1000 even if default was before case 15
you don't have the 'break' keyword specified in each of your cases.
Should be like this:
switch (i){
case 2 :
j++;
break;
case 4:
j+=10;
break;
case 15 :
j+=1000;
break;
default:
j+=2;
break;
}
In this case case 2 and case 4 are not execute but default and case 15 are so the answer is 1002. Please put break statement for desired result.
Hope this helps.

how to add while loop in switch statement when using dialog boxes?

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

Categories

Resources