Why wont this program allow me to divide - java

I noticed I could not find the digits in really large numbers. I decided to use biginteger to solve this problem however it will not let me divide them. I also turned one of the divisions into the big int dividion method but still it gives me a red flag. can anyone help me figure out why this is happening? the divide method is not working also. I changed one division to the divide method and left the rest as regular divisions.
//This class test the recursive method to see how many digits are in a number
public class TestDigits {
public static void main(String[] args) {// main method to test the nmbDigits method
Scanner c = new Scanner(System.in);
try{
System.out.println("Input an integer number:");
BigInteger number = c.nextBigInteger() ;
System.out.println(nmbDigits(number));}
catch (InputMismatchException ex){
System.out.println("incorrect input, integer values only.");
System.exit(1);}}
static BigInteger nmbDigits(BigInteger c) {//nmbDigits method takes input from user and returns the number of digits
int digits = 0;
if (c.divide(10) == 0){
digits++;}
else if (c / 10 != 0){
digits++;
BigInteger count = c/10;
do {
count = count/10;
digits++;}
while (count != 0);}
return digits;}
}

You can't use the division operator / on instances of BigInteger. This operator only works for primitive numerical types. That's why the BigInteger class has a divide method.
BigInteger result = c.divide(new BigInteger("10")); would work.

public class TestDigits {
public static void main(String[] args) {// main method to test the nmbDigits method
Scanner c = new Scanner(System.in);
try{
System.out.println("Input an integer number:");
BigInteger number = c.nextBigInteger() ;
System.out.println(nmbDigits(number));}
catch (InputMismatchException ex){
System.out.println("incorrect input, integer values only.");
System.exit(1);}}
static BigInteger nmbDigits(BigInteger c) {//nmbDigits method takes input from user and returns the number of digits
long digits = 0;
if (c.divide(BigInteger.valueOf(10L)) == BigInteger.valueOf(0L)){
digits++;}
else if (c.divide(BigInteger.valueOf(10L)) != BigInteger.valueOf(0L)){
digits++;
long count = (c.divide(BigInteger.valueOf(10L))).longValue();
do {
count = count/10;
digits++;}
while (count != 0);}
return BigInteger.valueOf(digits);}
}

Related

Binary to Decimal calculator InputMismatchException

My goal is to create a simple binary to decimal calculator. I try to go about this by first having the user input a string of the binary value they are trying to calculate and later use the length of this string to run a for loop (as seen in the code below). The calculator appears to work fine but fails when the user enters a binary number (of all 1's) longer than 20 digits. I receive a java.util.InputMismatchException error and I don't know how to fix it.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
long binaryNum = scan.nextLong();
System.out.println(binaryConverter(binaryNum));
scan.close();
}
public static long binaryConverter(long binaryNum) {
String binaryString = Long.toString(binaryNum);
long decimalValue = 0;
for(int i = 0; i < binaryString.length(); i++) {
if((binaryNum%10) == 0) {
binaryNum = binaryNum/10;
} else if((binaryNum%10) == 1) {
decimalValue += Math.pow(2, i);
binaryNum = binaryNum/10;
} else {
System.out.println("This isn't a binary number. Please try again.");
break;
}
}
return decimalValue;
}
}
The way you want to do this to use scanner.nextLong(2) where 2 is the radix. Then you will be reading in an actual binary number.
long number = scanner.nextLong(2);
System.out.println(number);
produces
144115188075855871
for input of
111111111111111111111111111111111111111111111111111111111
If I understood you correctly you always want to convert the binary input to a decimal value. A very simple solution would look like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
final String input = scan.next();
System.out.println(Integer.parseInt(input, 2));
scan.close();
}
If you are interested how it works under the hood, take a look at the java source for Integer.parseInt.

converting to decimal but without using integer.parseInt() method

So this is my first programming course and I have an assignment to convert a binary number entered by the user to a decimal. And my binary number should be stored in a a string.
And to check that all my digits are 1s and 0s I need to use a method to make sure it's valid and return true if the the number is correct and false otherwise.
So I did a search and saw that everyone was using the integer.parseInt(String , int radix) method to convert a binary string to int which worked completely fine, however, the only problem is we didn't take this with my professor so I'm not sure if it's OK and that maybe he wants another way to convert it?
So my question is: how can I write this code in another way that doesn't use this method?.
Here's my code:
import java.util.*;
import java.lang.*;
public class Assignment2
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int converttodecimal;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
converttodecimal = Integer.parseInt(st,2);// integer.parseInt(String , int radix);
System.out.println("the equivalent decimal value is: " +converttodecimal );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
}//end of class
This is the output:
enter a binary number to convert to decimal:
110101
the equivalent decimal value is: 53
Thank you in advance I already asked this question else where but I didn't get the answer I wanted.
UPDATE:
I wrote the program again based on your suggestions #akhil_mittal #fabian but if i want to write the converting method in the program itself (not calling the method) how can i do that ?
here's the code:
import java.util.*;
import java.lang.*;
public class Assignment2test
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int result;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
result = convertBinaryToDecimal(st);
System.out.println("the equivalent decimal value is: " + result );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
public static int convertBinaryToDecimal(String st){
double decimal =0;
for(int i=0;i<st.length();i++){
if(st.charAt(i)== '1'){
decimal = decimal + Math.pow(2,st.length()-1-i);
}
}
return (int) decimal;
}
}
//end of class
Do it manually, you can just multiply each digit for the corresponding power of two and sum the results.
Regarding the last part of your question, you can simply use java.lang.Math.pow(2,exponent), there is no specific operator for that if that was what you were wondering.
You can use the bit-shift operator to get powers of 2:
int pow2(int exponent) {
return 1 << exponent;
}
which should be more efficient than Math.pow.
But you could also calculate a binary number like this (example for 0b110101):
((((((1)*2+1)*2+0)*2+1)*2+0)*2+1)
i.e. by repeatedly multiplying by 2 and adding the next digit.
I have written two methods which use basic computation to convert binary to decimal, one takes long and other takes String. You can also use them to check the differences in implementation. The method is very simple and easy to understand.
public static int convertBinaryToDecimal(String binary){
double decimal =0;
for(int i=0;i<binary.length();i++){
if(binary.charAt(i)== '1'){
decimal = decimal + Math.pow(2,binary.length()-1-i);
}
}
return (int) decimal;
}
public static int convertBinaryToDecimal(long numberInBinary){
int decimal = 0;
int power = 0;
while(true){
if(numberInBinary == 0){
break;
} else {
long temp = numberInBinary%10;
decimal += temp*Math.pow(2, power);
numberInBinary = numberInBinary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
int binaryNumber = 110011;
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumber));
String binaryNumberInString = "110011";
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumberInString));
}
If you want to ensure that String only contains 0 and 1 then you can try yourself and let me know if you need any help.
Binary to decimal Conversion without using Integer.parseInt method
public class BinaryDecimal
{
public static int binaryToDecimal(int binary) {
int decimal = 0;
for (int power = 1; binary > 0; power *= 2, binary /= 10)
decimal += power * (binary % 10);
return decimal;
}
public static void main(String a[]) {
System.out.println("11 ===> " + binaryToDecimal(11));
//System.out.println("11 ===> " + binaryToDecimal(Integer.parseInt(a[0]))); //Input from command line
}
}

Checking text length is divisible by 2

I want to check whether a length of an input text is divisible by 2.
so it will be like
if my text length is 3, the result will be 1.5 and it will display not divisible by 2 and
if my text length is 6, the result will be 3.0 and it will display divisible by 2
but my codes will display the output "not divisible by 2" regardless what is the text length.
what have I done wrong?
import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
result = (double)l/2.0;
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}
}
}
The mod operation is your friend but only with integers...
if (integer % divisibleBy == 0) { do stuff; }
Edit: I also found this page that does a really good job outlining the various uses mod the mod operator and explains why your double mod doesn't work like you expect.
Edit: Also more review of your code; it looks like you divide by 2 and then do mod by 2. So 6/2 = 3 and 3 is not even. Wonder if your code would work if you used 8 -> 8/2 = 4 and 4%2 = 0.
Check the length of the text, then do a modulo to it.
Modulo , an operation which checks if a number will have a remainder if its divided by another number
yourNumber%5 == 0
where yourNumber is the lenght of your String. Take it from here.
First, length() returns an int, and it's simpler to work with integers, so why are you casting the length to double? The % (modulo) operator is meant to work with integers, not doubles; remember, double numbers are floating-point numbers, so there's always room for numerical error if you use them.
Second, you don't need to use so many variables; keep it simple:
a = scan.nextLine();
if(a.length() % 2 == 0)
System.out.println("Length of string is divisible by 2");
else
System.out.println("Length of string is not divisible by 2");
Easier to read (and write), don't you think?
import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
String str = scan.nextLine();
int length = str.length();
if(length % 2 !=0) {
System.out.println("not divisible by 2");
}
else {
System.out.println("divisible by 2");
}
}
}
There were a lot of problems with your code:
You are using a double to store the result for some reason, when it should've been an int
Your variable names are not descriptive of what they are for.
There is no need to initialize variables to a default value only to overwrite them with new values.
haha i hate these little mistakes. i do them all the time. Just switch both to %
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
//this is your problem
result = (double)l%2.0;
//this is your problem
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}

Making a main method repeat after catching an exception

This program takes in an integer and returns the number of digits within that integer. I noticed that I was unable to take very big numbers, so I decided to use the BigInteger class. All was good until I realized I needed the user to input a valid integer if they use incompatible input (like a string). How do I make the main method repeat after the catch statement, so no matter how many times you use bad input it request another input? I know that I shouldn't exit the program.
//This class test the recursive method to see how many digits are in a number
public class TestDigits {
public static void main(String[] args) {// main method to test the nmbDigits method
Scanner intInput = new Scanner(System.in);
try{
System.out.println("Input an integer number:");
BigInteger number = intInput.nextBigInteger() ;
System.out.println(nmbDigits(number));}
catch (InputMismatchException ex){
System.out.println("incorrect input, integer values only.");
System.exit(1);}}
static BigInteger nmbDigits(BigInteger c) {//nmbDigits method takes input from user and returns the number of digits
long digits = 0;
if (c.divide(BigInteger.valueOf(10l)) == BigInteger.valueOf(0l)){
digits++;
}
else if (c.divide(BigInteger.valueOf(10l)) != BigInteger.valueOf(0l)){
digits++;
BigInteger remainingValue = c.divide(BigInteger.valueOf(10l));
BigInteger g = nmbDigits(remainingValue);
digits += g.longValue();}
return BigInteger.valueOf(digits);}}
You can loop :
public static void main(String[] args) {// main method to test the nmbDigits method
boolean exit=false;
Scanner intInput = new Scanner(System.in);
while (!exit) {
try{
System.out.println("Input an integer number:");
BigInteger number = intInput.nextBigInteger() ;
System.out.println(nmbDigits(number));
exit=true;
}
catch (InputMismatchException ex){
System.out.println("incorrect input, integer values only.");
}
}
}
Somewhat like this pseudocode would do:
main(args) {
input = null;
do {
input = getInput();
} while(!valid(input);
solveAlgorithm(input);
}

Scan integers resources warning

In line 4 of this code, there is a resource leak warning. input=scan();
I want a method that takes an integer from the user. It will ask the user to re-enter an integer value if the value he previously entered is unacceptable, i.e. chars, spec. chars, etc. Also, I want to close the scanner before returning the int taken.
How do I fix this problem?
public static int readInt() {
Scanner input = scan();
while(!input.hasNextInt()) {
input = scan();
int n = input.nextInt();
while(n<0) {
System.out.println("Input should be a positive interger!");
n = readInt();
}
input.close();
return n;
}
return -1;
}
public static Scanner scan() {
System.out.print("Enter number: ");
Scanner input = new Scanner(System.in);
return input;
}
Use it with try catch block and close it in finally
finally {
input.close();
}
You should always close your Scanner when you're done with it:
You shouldn't create a new instance of Scanner every time you want to read something, you should create one instance and keep calling nextInt().
Also, I don't think your loop quite makes sense. I've rewritten the code slightly - if you want to keep asking the user for a number until n is positive, it makes sense to have n < 0 as your loop condition.
For example:
public static int readInt() {
Scanner input = new Scanner(System.in);
int n = -1;
while (n < 0) {
System.out.print("Enter number: ");
n = input.nextInt();
if (n < 0) {
System.out.println("Input should be a positive interger!");
}
}
input.close();
return n;
}
(also, the Scanner constructor throws a FileNotFoundException so you'd need to handle that in the code above - how did your example even compile?)

Categories

Resources