Why my binary to decimal conversion is not working in java? - java

I have this method where it converts a binary input from a user to decimal value.
Main Method:
public static void main(String args[])
{
String inputByUserString=""; //number input by the player
int inputByUserInteger;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number"); //getting the input
inputByUserString=sc.nextLine();
inputByUserInteger=Integer.parseInt(inputByUserString);
and then I create a switch case where there is more options for conversion like Decimal number to Binary number etc...
Then in that switch I call a method:
int binaryToDecimalNumberVariable=obj1.binaryToDecimalConversion(inputByUserInteger);
System.out.println("Binary Number:"+inputByUserInteger);
System.out.println("Decimal Number:"+binaryToDecimalNumberVariable);
Method for binary to decimal conversion:
public int binaryToDecimalConversion(int inp) //to convert binary number into decimal number
{
int a1;int a2=0;int a3 = 0;
while(inp>0)
{
a1=inp%10;
a1=inp/10;
a3=(int)(a3+(a1*(Math.pow(2,a2)))); //result
a2++;
}
return a3;
}
The whole switch case:
System.out.println("What type of conversion do you want?");
System.out.println("1)Decimal number to Binary number");
System.out.println("2)Binary number to Decimal number");
System.out.println("3)Decimal number to Octal number");
System.out.println("4)Octal number to Decimal number");
System.out.println("5)Decimal number to Hexadecimal number");
System.out.println("6)Hexadecimal number to Decimal number");
System.out.println("7)Octal number to Hexadecimal number");
System.out.println("8)Hexadecimal number to Octal number");
int choice=sc.nextInt();
switch(choice)
{
case 1: //Decimal number to Binary number
break;
case 2: //Binary number to Decimal number
int binaryToDeci=obj1.binaryToDecimalConversion(inputByUserInteger);
System.out.println("Binary Number:"+inputByUserInteger);
System.out.println("Decimal Number:"+binaryToDeci);
break;
case 3: //Decimal number to Octal number
break;
case 4: //Octal number to Decimal number
break;
case 5: //Decimal number to Hexadecimal number
break;
case 6: //Hexadecimal number to Decimal number
break;
case 7: //Octal number to Hexadecimal number
break;
case 8: //Hexadecimal number to Octal number
break;
default:
System.out.println("Invalid Input");
} //switch close
It shows no error while compiling but when I execute it,it just stucks.
Error that is showing when I execute it:
So, help me.

To expand on my comment, the correct way to handle your requirements:
String myBinaryNr = sc.next();
int myNr = Integer.parseInt(myBinaryNr, 2);
String myDecimalNr = Integer.toString(myNr, 10);
The last 10 is optional, since it is the default.

If it's getting stuck, it probably hasn't detected an input and it's awaiting for it. To confirm this, I would add a
System.out.println("Test" + choice);
just under the choice input, so it would be like this:
int choice = sc.nextInt();
System.out.println("Test" + choice);
switch(choice){...}
If it doesn't print correctly, then you have found your issue. It may have something to do with the System.in

Never mind,I just have to do this and it solves the problem.
public int binaryToDecimalConversion(int inp) //to convert binary number into decimal
{
int a1;int a2=0;int a3 = 0;
while(inp>0)
{
a1=inp%10;
a3=(int)(a3+(a1*(Math.pow(2,a2)))); //result
a2++;
inp=inp/10;
}
return a3;
}

Related

Only Accepting 2 as a number and giving wrong output of odd or even

Good morning,
I'm trying to learn somethings on my own. As I'm overloaded for assignments as it is. This is just a small practice program I was working on. I get it to this point however, I'm unsure of what is happening.
When given a number other than 2 it says "Please input a valid number, Thank you"
When given 2 it says "The Number is not even so there are Remainders"
I'm unsure why I'm getting this. Why is it not accepting other numbers and why is it saying 2 isn't even?
Any help on what I'm interpreting wrong would be appreciated. Thank you.
import java.util.Scanner;
public class Assignment1
{
//Scanner keyboard = new Scanner(System.in);
//int num = keyboard.nextInt();
public static int isEven()
{
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
switch (num)
{
case 1:
if (num % 2 == 0)
System.out.println("The Number is Even no Remainders");
break;
case 2:
if (num % 2 != 0);
System.out.println("The Number is not even so there are Remainders");
break;
default:
System.out.println("Please input a valid number, Thank you.");
}//switch
/*pull number from user
//store in num
//if even print message num is even
//else print message not an even number
* This is the remainder of my psuedcode notes to remind me how my
* mind was flowing
*/
return num;
} //isEven
public static void main (String args[])
{
Assignment1.isEven();
}//main
}//public class assignment one
The documentation for switch-case is here .
And now try this, I added some comment to lines. Read those carefully.
public class Assignment1 {
public static int isEven() {
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
num = num % 2; // divide by 2 and get a remainder.
switch (num) {
case 0: //case 0 means if number equal to zero
System.out.println("The Number is Even no Remainders");
break;
case 1: // case 1 means if number equal to one
System.out.println("The Number is not even so there are Remainders");
break;
default: // if no one match if not a valid.
System.out.println("Please input a valid number, Thank you.");
}//switch
/*pull number from user
//store in num
//if even print message num is even
//else print message not an even number
* This is the remainder of my psuedcode notes to remind me how my
* mind was flowing
*/
return num;
} //isEven
public static void main(String args[]) {
Assignment1.isEven();
}//
}

adding a control structure

the code below convert a decimal number to octal number. what i need is to have it to be able to display these message when the input is invalid and repeat the input process until a valid input in entered
"Enter a decimal number: -1
Input should not have any negative sign!
Enter a decimal number: -a
Input should not have any negative sign!
Input should not contain letters!
Enter a decimal number: -1.1
Input should not have any decimal point!
Input should not have any negative sign!
Enter a decimal number: -1.a
Input should not have any decimal point!
Input should not have any negative sign!
Input should not contain letters!
Enter a decimal number: 15 decimal 15 = octal 17"
import java.util.Scanner;
public class apple
{
public static void main(String args[])
{
Scanner sc = new Scanner( System.in );
System.out.print("Enter a decimal number: ");
int num =sc.nextInt();
int rem;
String str="";
int num1 = num;
while(num>0)
{
rem=num%8;
num=num/8;
str =rem+str;
}
System.out.println("decimal " + num1 + " = octal " + str);
}
}
thanks in advance.
boolean continueEntering = true;
while(continueEntering)
{
int num =sc.nextInt();
if(your condition failed){
//print whatever you want
continueEntering = true; //didnt got the out put so asking again
}else{
//input is valid no need to ask data again
continueEntering = false;
}
}
you need to pass a boolean value at the while loop. If the user has entered a invalid input you can make the boolean value true so that you can ask the input one more time. However i have stopped the program when user has entered a valid input. You can change that by reversing the value of the boolean.

Java validation error from user input

I have the following code, where the idea is that the user will input two numbers and the sum of the two will be calculated.
If an invalid value, e.g. a character is entered, an error message should be outputted but I keep getting errors
Java
package calculator;
import java.util.Scanner;
public class calculator {
/**
* #param args
*/
public static void main(String[] args) {
double n1, n2;
String operation;
Scanner scannerObject = new Scanner(System.in);
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
System.out.println("Enter second number");
n2 = scannerObject. nextDouble();
Scanner op = new Scanner(System.in);
System.out.println("Enter your operation");
operation = op.next();
switch (operation) {
case "+":
System.out.println("Your answer is " + (n1 + n2));
break;
case "-":
System.out.println("Your answer is " + (n1 - n2));
break;
case "/":
System.out.println("Your answer is " + (n1 / n2));
break;
case "*":
System.out.println("Your asnwer is " + (n1 * n2));
break;
default:
System.out.println("I do not know!");}
}
int function(){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
int range;
while(true){
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine(); //Comsume the garbage value
System.out.println("Enter an integer between 1-100:");
}
return range;
}
}
and these are the error messages I get:
Errors
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at calculator.calculator.main(calculator.java:14)
I've tried so many different things but can't get it to work as I want it.
Can anyone be of any assistance here?
Thanks for reading
This exception is thrown by an instance of the Scanner class to indicate that a retrieved token does not match the pattern for the expected type, or that the retrieved token is out of range.
You can see the documentation for the exception here: https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html
Taken from documention on Scanner
double nextDouble()
Returns the next token as a long. If the next token is not a float or
is out of range, InputMismatchException is thrown.
I suspect that your not inputting your number correctly. Ensure that your input is of the correct format.
You should also set the locale of your scanner as some locales expect a comma , instead of a dot ., such as:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
Your first two inputs should be numbers. If this is true, then it's probably the decimal mark for your numbers. You need a dot(.) not a comma (,)
It seems that you are not entering any integer as input.
You can solve this by handling the exception this way :
try {
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine();
}
catch (InputMismatchException e) {
input.nextLine();
}
Your issue is at,
scannerObject. nextDouble();
You are trying to get a double but entering a string. You will need to do some sort of a input validation like below to stop program from crashing incase of invalid inputs.
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input");
}
Then you may want to create a loop to get the input again and agin until valid input is detected.
Edit
You'll need to,
import java.util.InputMismatchException;
Also create a loop to get a valid input from a user. Something like below. This is just an example, you'll need to do something like this to work with your code. Also need to make sure n1 and n2 are initiated before you actually use their values.
boolean notValidInput = true;
while(notValidInput) {
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
notValidInput = false;
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input. Please try again!");
}
}

How to multiply Roman Number string with a double in Java?

i am new to a java program and i have a homework where when i get input from a user as an string, i have to convert it to a double and multiple it with a .11111 using a switch decision structure.
A string input from user has to be a number in roman numeral which is I, II, III, IV, and so on....
//This is my program
package practiceNum;
import java.util.Scanner;
public class practiceNum{
class stastic void main(String[] args){
String num_In_Roman; //declare a string
Scanner keyboard = new Scanner(System.in); //read input words
System.out.println("Enter a roman numerals from I to X: "); //asking user input
num_In_Roman = keyboard.nextLine();
switch(num_In_Roman){
case "I":
break;
case "II":
break;
//and so on until 10 (X) in roman numerals.
default:
System.out.println("Invalid Number!");
}
//end of body program here
}
}
Here's what i did to calculate my math but still giving me an error.
Double value = Double.parseDouble(num_In_Roman); //convert string into double
case "I":
value *= .111111;
System.out.println(value);
break;
someone help please.
This is the bad way, but this is what you can do:
case "I":
value = 1 * .111111;
System.out.println(value);
break;
case "II":
value = 2 * .111111;
System.out.println(value);
break;

Trouble trying to restart my Java program

After looking up numerous ways to restart a Java program within itself, a while loop seemed like the easiest option. Here's an example of a basic calculator program I'm trying this with:
import java.util.Scanner;
class a {
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done)
{
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
add addObject = new add();
addObject.getSum();
break;
case 2:
sub subObject = new sub();
subObject.getDifference();
break;
case 3:
times multObject = new times();
multObject.getProduct();
break;
case 4:
divide divObject = new divide();
divObject.getQuotient();
break;
case 5:
remain remObject = new remain();
remObject.getRemainder();
break;
case 6:
avg avgObject = new avg();
avgObject.getAvg();
break;
case 7:
interest intObject = new interest();
intObject.getInterest();
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
}
However, this seems to throw out a NoSuchElementException at the end of the first time through the loop, and crashes the program. The function of this class is to take the initial input from the user to determine which class to use, which will determine which mathematical operation to perform. Everything works fine without the while (!done) loop.
Example usage:
McMackins Calc v2.0 (Now with fewer crashes!)
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
1
How many addends?
1
Enter your numbers now.
1
You have entered 1 addend.
The sum is: 1.0
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
Enter a valid integer.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at a.main(a.java:13)
I've also tried just having the other classes refer back to this one, but since main is a static method, I cannot access it the way I intended.
Note that I'm a bit of a beginner at Java, which is why my program is pretty simple, so try to keep it simple if it can be, or post code and then in DETAIL explain what it means so I can not only fix this problem, but future ones as well.
Thank you!
EDIT:
The code is formatted better within my editor. The braces came out in odd positions when I posted it here.
Since apparently a is written correctly, this is my add class. Hopefully this will clear something up.
import java.util.Scanner;
public class add {
public void getSum(){
Scanner input = new Scanner(System.in);
double total, addend;
int entries, count;
total = 0;
count = 0;
System.out.println("How many addends?");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
entries = input.nextInt();
System.out.println("Enter your numbers now.");
while (count < entries){
while (!input.hasNextDouble()){
System.out.println("Enter a valid number.");
input.next();
}
addend = input.nextDouble();
total = total + addend;
count++;
if (count == 1){
System.out.println("You have entered " + count + " addend.");
}else if (count > entries){
System.out.println("You have entered too many addends! Contact program developer.");
}else{
System.out.println("You have entered " + count + " addends.");
}
}
System.out.println("The sum is: " + total);
input.close();
}
}
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done) {
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
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:
System.out.println("5");
break;
case 6:
System.out.println("6");
break;
case 7:
System.out.println("7");
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
This seemed to work for me so perhaps the error is something to do with your own classes (add, divide) etc.
Also, it's best to keep with convention when creating your own classes by capitalizing the first letter e.g. "add" should be "Add".
You could probably make this a little bit easier to read by building a general "Operations" class which holds an add method, a subtract method etc.
EDIT:
try this for your add method:
public static int add() {
Scanner s = new Scanner(System.in);
int counter = 0;
System.out.println("How many numbers to add?");
int numCount = s.nextInt();
for(int i = 0; i < numCount; i++) {
System.out.println("enter number");
counter += s.nextInt();
}
return counter;
}
Use bufferedreader and inputstream instead of Scanner class. This class creates a lot of bugs and errors, since sometimes it takes more arguments, that you expect it to take.
Also:
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
Your using hasNextInt method wrong, instead of it try to make simple while loop with Boolean and input.next() should be replaced with input.nextLine().
Another thing, you should check,if user typed integer instead of string or something in the while loop and it range. If everything is okay, you should change Boolean value to true and make him go out of the while loop.
For future users who are wondering how to fix this issue, through some reprogramming, I discovered that my problem was closing the input variable BEFORE the end of the loop. By having the program restart indefinitely and only close input when done, this program works fine.
Thanks to Benjamin's response, I am currently in the process of cleaning up and shortening my code by way of for loops.

Categories