Binary to decimal conversion - java

I am a novice programmer trying to write a program that converts an entered Binary number into a decimal number. As far as I can tell, the math and code are right, and no compilation errors are returned, however the number that is output is NOT the correct decimal number. My code is as follows:
String num;
double result = 0;
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number or enter 'quit' to quit: ");
num = in.nextLine();
int l = num.length();
if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}
for (int i = 0; i < l; i++)
{
result = result + (num.charAt(i) * Math.pow(2, (l - i)));
}
System.out.println("The resulting decimal number is: " +result);
} while (!num.equals("quit"));
if (num.equals("quit")){
System.out.println("You chose to exit the program.");
return;
}
Any Help you could give would be much appreciated. I tried making my question as clear as possible but if you have any questions I will try to answer the best I can. I have not been doing this long. All I need is for someone to look it over and hopefully find the error I made somewhere, thanks.

Change
result = result + (num.charAt(i) * Math.pow(2, (l - i)));
to
result = result + ((num.charAt(i) - '0') * Math.pow(2, i));
or more compactly,
result += (num.charAt(i) - '0') * Math.pow(2, i);
Remember that the character '0' is not the same thing as the number 0 (same for '1' and 1); num.charAt(i) returns the character not the integer.
int a = '0';
int b = 0;
System.out.println(Math.pow(2, a));
System.out.println(Math.pow(2, b));
Output:
2.81474976710656E14
1.0
Big difference isn't there?

The function String.charAt(); does not return the number 0 or 1 which you can multiply with the bit but the character "id". You need to convert the String / char to a number.
String num;
double result = 0;
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number or enter 'quit' to quit: ");
num = in.nextLine();
int l = num.length();
if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}
for (int i = 0; i < l; i++)
{
result = result + (Integer.parseInt(num.substring(i,i+1)) * Math.pow(2, (l - i)));
}
System.out.println("The resulting decimal number is: " +result);
} while (!num.equals("quit"));
if (num.equals("quit")){
System.out.println("You chose to exit the program.");
return;
}
By the way: Why is a string that does not contain either a 0 or a 1 not a binary numer? Think of 1111 for example. I think you should better check for "neither 0 nor 1"
if (num.indexOf("0")==-1 && num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}

Note that num.charAt(i) gives the ASCII code for the character at position i. This is not the value you want. You need to convert each character digit to an int before you do any math with the value.

Integer.parseInt(string, base) parse string into an integer using "base" radix, if it cannot be converted, it raises an exception.
import java.util.Scanner;
public class Convertion {
public static void main(String[] args) {
String num;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number");
num = in.nextLine();
try{
//this does the conversion
System.out.println(Integer.parseInt(num, 2));
} catch (NumberFormatException e){
System.out.println("Number entered is not binary");
}
}
}

Related

How do you make it so that when you enter a number it puts a space between each integer

import java.util.Scanner;
public class Digits {
public static void main(String[] args) {
/*
*
count = 1
temp = n
while (temp > 10)
Increment count.
Divide temp by 10.0.
*/
//Assignment: fix this code to print: 1 2 3 (for 123)
//temp = 3426 -> 3 4 2 6
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int count = 1;
int temp = input.nextInt();
while(temp >= 10){
count++;
temp = temp / 10;
System.out.print(temp + " ");
}
}
}
Need help fixing code.
Example: when you type 123 it becomes 1 2 3.
Your code is dividing by ten each time, that could be used to print the value in reverse. To print it forward you need a bit more math involving logarithms. Sometime like,
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int temp = input.nextInt();
while (temp > 0) {
int p = (int) (Math.log(temp) / Math.log(10));
int v = (int) (temp / Math.pow(10, p));
System.out.print(v + " ");
temp -= v * Math.pow(10, p);
}
Alternatively, read a line of input. Strip out all non digits and then print every character separated by a space. Like,
String temp = input.nextLine().replaceAll("\\D", "");
System.out.println(temp.replaceAll("(.)", "$1 "));
Most of your code is correct, and what you are trying to do is divide by 10 and then print out the value - this probably should have been a modulus operation % to get the remainder of the operation and print that out - but a nice way of thinking about it.
Nevertheless.
You can just use a string and then split the string on each character
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
// we know that we are going to get some input - so we will just grab it as a String
// whilst we are expecting an int - we will test this later.
// we are doing this as it makes it easier to split the contents of a string
String temp = input.next();
// is this an int? - we will test this first
try {
// if this parsing fails - then it will throw a java.lang.NumberFormat exception
// see the catch block below
int test = Integer.parseInt(temp);
// at this point it is an int no exception was thrown- so let's go
// through and start printing out each character with a space after it
// the temp(which is a string).toCharArray returns a char[] which we
// can just iterate through and set the variable of each iteration to 'c'
for (char c : temp.toCharArray()) {
// now we are going to print out the character with a space after it
System.out.print(c + " ");
}
} catch (NumberFormatException ex){
// this is not an int as we got a number format exception...
System.out.println("You did not enter an integer. :(");
}
// be nice and close the resource
input.close();
}
Answering solely your question, you can use this one-line code.
int test = 123;
System.out.println(String.join(" ", Integer.toString(test).split("")));
Output is: 1 2 3

How to recognize doubles and negative vaules

// The program compiles and runs as it should to compute averages I am just struggling to add negative, and double values to it.
import java.util.*;
public class DoWhileLoops {
public static void main (String [] args) {
Scanner kb = new Scanner(System.in);
int sum = 0,
ct = 0;
String input = "";
do {
System.out.println
("Enter a positive whole number, or q to quit.");
int n=0, sct=0;
char c;
input = kb.nextLine();
do {
c = input.charAt(sct);
if (c >= '0' && c <= '9')
{
n = n * 10;
n += (int)(c - '0');
}
sct++;
} while (sct < input.length());
if (n > 0) {
sum += n;
ct++;
}
} while (!input.equalsIgnoreCase("q"));
System.out.printf("The sum of the %d numbers you entered is: %d\n", ct, sum);
if(ct > 0)
System.out.printf("The average is: %.2f", (double)sum/ct);
else
System.out.printf("No numbers entered - can't compute average");
}
}
//Need help having the program so it will recognize positive and negative values as well as doubles.
You use a Regular Expression (regex) within a String#matches() method to determine if the User has entered a string representation of a valid number of either a signed (negative) or unsigned (positive) integer or double data type value, for example:
if (!input.matches("-?\\d+(\\.\\d+)?")) {
System.err.println("Invalid numerical value supplied! Try again..." + ls);
continue;
}
The regular expression used in the matches() method above is: "-?\\d+(\\.\\d+)?" and here is an explanation of what it means:
When summing, you want to use a double data type variable which means then that when the User supplies a value we want to parse it to a double data type. To do this you can use the Double.parseDouble() method to convert the string numerical value to a double data type and add that value to our summation (the sum variable which we've already declared as double).
Here is what the code might look like:
Scanner kb = new Scanner(System.in);
String ls = System.lineSeparator();
double sum = 0;
int counter = 0;
String input;
do {
System.out.print((counter + 1) + ") Enter a numerical value (or q to finish): ");
input = kb.nextLine();
// If the first character supplied by User is a Q then exit loop
if (Character.toString(input.charAt(0)).equalsIgnoreCase("q")) {
break;
}
// If the value supplied is not a numerical value
// then inform User and let him/her/it try again.
if (!input.matches("-?\\d+(\\.\\d+)?")) {
System.err.println("Invalid numerical value supplied! Try again..." + ls);
continue;
}
counter++;
double num = Double.parseDouble(input);
sum += num;
} while (true); // q must be given to exit loop.
System.out.printf(ls + "The sum of the %d numbers you entered is: %f\n", counter, sum);
if (counter > 0) {
System.out.printf("The average is: %.2f", (double) sum / counter);
}
else {
System.out.printf("No numerical values entered! - Can not compute average!");
}

Parsing a String to an Integer

So my biggest problem is that I cannot seem to remember how to parse a string into an int so that I can idiot proof my code. My goal here is to find out if the user enters in a word instead of an int and then I can explain to them what an integer is. Can someone please help? I just need a simple list of parsing commands so that I can study them for use in the future, once there is a simple list I think I'll be able to figure all the others out from there.
import java.util.Scanner;
import java.util.*;
public class SelfTestNumberNine
{
public static void main(String[] args)
{
boolean test = false;
int num = 0;
int sum = 0;
int count = 0;
int pos = 0;
int neg = 0;
Scanner in = new Scanner(System.in);
while(!test)
{
num = 0;
System.out.print("Enter in an Integer Value: ");
String letta = in.next();
if(??parsing stuff goes here!!)
{
num = in.nextInt();
count++;
if(num > 0)
{
pos++;
sum = sum + num;
}
else if(num < 0)
{
neg++;
sum = num + sum;
}
else
{
test = true;
}
}
else
{
System.out.println("An Integer is a number that is positive or
negative,\nand does not include a decimal point.");
}
}//end while
System.out.println("Total: " + sum);
double avg = sum / count;
System.out.println("Average: " + avg);
}//end main
}//end class
Basically, the program asks the user to input integers, counts the number of positive and negatives, and prints out the total and average (Ignoring 0). The program ends when the user inputs a 0.
P.S. Thanks for your time!! ]:-)
If you want to ensure that the user has entered an int without throwing an exception if they don't you can use the hasNextInt() method:
System.out.println("Enter an int (0) to quit");
//While the user has not entered a valid int
while (!input.hasNextInt()) {
System.out.println("Please enter an integer: ");
//Consume the bad input
input.nextLine();
}
Which will loop until they enter a valid int. A sample run (- denotes user input):
Enter an int (0 to quit)
-No
Please enter an integer:
-Never!!
Please enter an integer:
-Ok ok fine
Please enter an integer:
-3
You can do this in two ways.
- Integer.parseInt()
- Integer.valueOf()
String myStr = "1";
int parsedInt = Integer.parseInt(myStr);
int valueOf = Integer.valueOf(myStr);
System.out.println("Parse Int: " + parsedInt);
System.out.println("Value Of: " + valueOf);
Note: You might get exception if the input is not parseable. NumberFormatException.
You can use a Boolean method and a try-catch to check if you can parse the string to an Integer.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}

How to handle invalid input when using Scanner.nextInt()

I am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.
import java.util.Scanner;
public class Average{
public static void main(String[]args){
System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");
System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}
To get integer inputs in a loop, respond to an "exit" value, and guard against invalid inputs, I would use something like the template below.
Note that something critical that none of the answers so far has mentioned is that it is not good enough to simply catch InputMismatchException. You must also call your scanner object's nextLine() method to clear the bad input out of its buffer. Otherwise, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter integers or -5 to quit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == -5) {
done = true;
}
else {
// The input was definitely an integer and was definitely
// not the "quit" value. Do what you need to do with it.
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Enter integers or -5 to quit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: -5
Exiting...
You would probably want
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
inside the while loop because right now you are only checking the last read value(also, there's no need to up the counter outisde the loop(after you have read -5, btw, why -5?o.O).
Also, you would probably want the min/max values initialised this way, because if your min value is bigger than 0, your code outputs 0. Same goes if your max value is below 0:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
For the non-integer part: read up on exceptions and use a try-catch block to catch the InputMismatchException.
try {
//while(scan.nextInt) here
} catch (InputMismatchException e) {
//Do something here, like print something in the console
}
As someone else pointed out, if you want the average to not be truncated, cast sum to double: ((double) sum) / count.
Finally, but most important: try debugging it yourself before asking someone else.
Try this:
import java.util.Scanner;
public class Average {
static Scanner scan;
public static void main(String[] args) {
System.out.println("Enter any integer numbers or -5 to quit:");
scan = new Scanner(System.in);
int number = -1, sum = 0, count = 0;
int max = 0;
int min = 0;
while((number = scanNextInt()) != -5) {
count++;
sum = sum + number;
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
}
if(number == -5) {
try {
System.out.println("Average : " + (sum / count));
System.out.println("Maximum : " + max);
System.out.println("Minimum : " + min);
}catch(Exception e) {
//Error printing, so quit the program. Look below.
}
//Quit
System.exit(0);
}
scan.close();
}
static int scanNextInt() {
try {
return scan.nextInt();
}catch(Exception e) {
//Stop the program if the user inputs letters / symbols
System.out.println("Invalid Number.");
return -5;
}
}
}
Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages
Note: This HAS been tested
Firstly - you need to move the closing bracket of the while loop after the min number check to allow the checks to be performed for every number you read. And remove one count++ to avoid double counting.
To ignore illegal input you could use one of the other Scanner methods and read a String instead of int, then try to Integer.parseInt the String and wrap the parsing into a try catch.
//count++;
double avg = 0.0;
if (count != 0) {
avg = ((double) sum) / count;
}
System.out.println("Average : " + avg);
When both sides of the division are int then it is an integer division (result int, remainder of division thrown away).
Hence we cast one side, here sum to floating point:
(double) sum
And then it works.

binary to decimal program isn't giving correct answer java

So i have to write a program for homework where it takes a binary number and prints out its the decimal form. I've tried and and i just can't really get it. Like im printing out what it's doing every time in the loop and it looks like im getting the wrong value when i multiply the inputed data by the 2^i. If someone could help, that would be amazing
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
int value = 0;
int square_value = 0;
for (int i = 0; i < binary_number.length(); i++) {
char binary_place_holder = binary_number.charAt(i);
square_value = (int) Math.pow(2, i);
if (binary_place_holder == '1') {
value = (square_value*binary_place_holder+value);
}
System.out.println(binary_place_holder+ " " + square_value + " " + value);
}
System.out.print(binary_number + " == " + value);
}
}
The way you determine the exponent is wrong: The exponent is not i.
You need to realize that you are looking at the string from left to right side so from the highest bit.
This means the first character's exponent is 2^string_length-1.
Second character's exponent is 2^string_length-2 and so on.
Therefore as the index i becomes larger, i.e. as we are scanning the input left to right, the exponent value becomes smaller.
So the exponent is:
int exponent = binary_number.length() - 1 - i;
Note: You can of course do things in reverse and start from the end of the input string and determine the exponent that way, I just wanted to do less changes to your code.
Also, you should add a check to make sure the input is a valid binary number. You can write your own function to do it but a simpler solution is to use regex matching:
binary_number.matches("[01]+")
This will return true if the string binary_number contains only '0' and '1' characters, and false otherwise.
Applying all these changes to your code:
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
if(!binary_number.matches("[01]+")) {
System.err.println("\nPlease enter a valid binary number");
} else {
int value = 0;
for (int i = 0; i < binary_number.length(); i++) {
if (binary_number.charAt(i) == '1') {
int exponent = binary_number.length() - 1 - i;
value += (int) Math.pow(2, exponent);
}
}
System.out.print(binary_number + " == " + value);
}
}
This might be considered cheating but you could go all like
System.out.println(Integer.parseInt(binary_number, 2));

Categories

Resources