Multiplication of two 64 digit number_Gettin Input Mismatch Exception - java

public class Karatsubamultiplication {
public static void multiply(long ac , long ad, long bc, long bd, long digits)
{
double mul=0;
mul = Math.pow(10, digits) *ac + Math.pow(10, digits/2)*(ad+bc)+bd;
System.out.println("The multiplication answer is "+mul);
}
public static long[] splitnum(long n1) {
long[] split= new long[3];
long divider=1;
long num =0;
long counter=0;
num=n1;
while(num>0) {
num=num/10;
counter=counter+1;
}
split[2]=counter;
for(long i=0;i<counter/2;i++) {
divider*=10;
}
split[0]=n1/divider;
split[1]=n1%divider;
return split;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter value of n1 and n2 ");
long n1 = sc.nextLong();
long n2 = sc.nextLong();
long ac=0,ad=0,bc=0,bd=0,digits=0;
if(n1/10==0 && n2/10==0)
{
System.out.println("The multiplication answer is "+n1*n2);
}
else
{
long[] a= splitnum(n1);
long[] c =splitnum(n2);
ac = a[0]*c[0];
ad = a[0]*c[1];
bc= a[1]*c[0];
bd= a[1]*c[1];
digits=a[2];
multiply(ac,ad,bc,bd,digits);
}
}
}
Multiplication of two 64 digit number_Gettin Input Mismatch Exception
Query : when i give 2 64 bit number result will be in 128 bits. Getting Input Mismatch exception:(
Need help to enhance this code in order to handle this exception .>

InputMismatchException is thrown by the nextLong() method, when the input entered by the user is not, in fact, a long.
The way you've used scanner means that nextLong is looking for a space, enter (newline), end of the stream, or other whitespace, and will then parse all the character that precede it as a long. Note that this means the input must consist of an optional + or -, and then a bunch of digits, and that is all, and that the number must fit between -2^63 and +2^63-1 (so, between -9223372036854775808 and +9223372036854775807). Any number below/above that isn't a long and therefore causes that exception.
Fix: Well, you tell me. What do you want this program to do? Any numbers outside of that range do not fit into the long datatype in the first place.
If you don't need your program to deal with numbers that extreme, then.. don't enter them.
If you do, then this code needs to be replaced entirely; don't call .nextLong() at all. Presumably, just call .next() and use java.math.BigInteger instead of longs, which can take numbers of any size.

Related

Removing all but the first two numbers in a decimal

I'm trying to make a program that converts a number the user inputs into a percentage. Once converted, I want to keep the first two numbers after the decimal, but without rounding off the number. For example, inputting 1.23456 would result in 123.45.
My line of thinking was that I could take the input, separate the string into before and after the decimal place, and from there create a loop that removes the last digits until it has at most 2 decimal places. My issue is that whenever I create something that would have an output greater than 9 for the decimal, I get the error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 0, so I can only get decimals to the tenths place at the moment.
My code:
import java.util.Scanner;
public class percentage {
public static void main(String[] args) {
try (// TODO Auto-generated method stub
Scanner x = new Scanner(System.in)) {
System.out.println("Please input a number with a decimal to be converted into a percentage: ");
String numberAsString = x.next();
double number = Double.parseDouble(numberAsString);
double percentage = (number * 100);
String toString = Double.toString(percentage);
String[] parts = toString.split("[.]");
String integer = parts[0];
String decimal = parts[1];
int length = decimal.length();
while(length>2) {
decimal = decimal.substring(0,decimal.length()-1);
}
System.out.println("decimal is " + decimal);
System.out.println("integer is " + integer);
}
//System.out.println(decimal);
}
}
Multiply by 10,000 (100 for percentage, 100 for the two decimal places), truncate to integer, divide by 100 (to get back to percentage).
Writing it out one step at a time, for clarity of exposition:
Double n = input.nextDouble();
int i = (int)(n * 10_000);
Double pc = i / 100.0;
System.out.printf("%.2f\n", pc);
You have the number as a String in the variable toString. Use regex to trim all characters after the 2nd decimal (if any exist).
It’s a one-liner:
toString = toString.replaceAll("(?<=\\...).*", "");
Or just print it directly:
System.out.println(toString.replaceAll("(?<=\\...).*", ""));

The while and do-while loops The smallest value

I need to write a program that a user inputs a long positive number m. I need to find out what is the smallest int number n such that n! > m.
So far I have written such a code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
int fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println(count);
}
}
Test input:
6188989133
Correct output:
13
Your code output:
My code output is empty. What I am missing here?
You have to use long for the fact variable. When you use int the possible values are between -2,147,483,648 and 2,147,483,647.
However, you will never exceed the input number 6,188,989,133, so your while(fact <= number) loop will never exits. Every integer value possible will be smaller than 6,188,989,133. This explains why your code output is "empty", as it doesn't reach that System.out.println(count); line at all.
Keep in mind that the long type has such a limit as well, values can only be between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. When the input number is that big, you will not find the correct fact value which will be greater than the input because you are limited by the long type value range. As an example, for the input number 9,000,000,000,000,000,000 (which is inside the long type value range) the next factorial number is 51,090,942,171,709,440,000 (the value of 21!), which is outside the long type value range.
You can use the java.math.BigInteger class which has an "unlimited" range of possible values and do your math operations on BigInteger objects.
fact should be declared as long. Check the code below:
public class TestJava {
public static void main(String[] args) {
try{
System.out.println("Input number: ");
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
if(number >= 2432902008176640000L) {
// log an appropriate message like can not handle
// long value greater than 2432902008176640000L
return 21;
}
long fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println("output: "+ count);
}catch(Exception e){
e.printStackTrace();
}
}
}
Update (Warning):
As #Pshemo mentioned, with out the if condition, the above code is fine till 20!, but after that it will cause the infinite loop problem. Hence this condition has to be taken care of. Code has been updated accordingly.
You need to change fact type to long

I'm new to Java. I coded a Java program that adds two numbers. Can't get to display the sum as int.

Hi I'm totally new to the Java language and my professor gave us an assignment that's not too complicated. I've done most of it correctly. Here's what we're supposed to do. If you enter two integers the sum should be an int. If you enter two doubles the sum should be a double. And if either of the two is a double then also the sum should be a double. And if either of the two can be interepreted as a Binary number, it should be treated as such. Lastly, if both numbers are Binary then the sum should be displayed in binary. The code I have so far, does everything except when I enter two ints it gives me the sum as a double, can somebody please suggest where I should make a change to fix that?
This is my code so far:
import java.util.Scanner;
public class ProjectZero
{
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
cin.useRadix(2);
System.out.print("Enter two numbers separated by a space: ");
if (cin.hasNextInt())
{
int first = cin.nextInt();
if (cin.hasNextInt())
{
int second = cin.nextInt();
bigFunction(first, second);
}
else if (cin.hasNextDouble())
{
double second = cin.nextDouble();
bigFunction(first,second);
}
else
System.out.println("Please try again and enter numbers.");
}
else if (cin.hasNextDouble())
{
double first = cin.nextDouble();
if (cin.hasNextDouble())
{
double second = cin.nextDouble();
bigFunction(first,second);
}
else
System.out.println("Please try again and enter numbers.");
}
else
System.out.println("Please try again and enter numbers.");
cin.close();
}
public static void bigFunction(int a, int b)
{
int sum = a + b;
System.out.print("The sum of " + Integer.toBinaryString(a) + " (Decimal value: " + a + ")");
System.out.println(" and " + Integer.toBinaryString(b) + " (Decimal value: " + b + ")" + " is " + Integer.toBinaryString(sum));
}
public static void bigFunction(double a, double b)
{
double sum = a + b;
System.out.println("The sum of " + a + " and " + b + " is " + sum);
}
}
even easier answer do
instead of if .hasNextDouble
if (first % 1 ==0)
{
//you have an integer
}
else
{
//it is not an integer
}
the % means modulus which basically divides something and check if there is a remainder if there is a remainder after deviding a number by 1 it is not an int
The easiest way is to read the two inputs as Strings. Then check the strings to see whether they contain only the digits 0 and 1 (if so, binary number). If not binary, check whether it can be interpreted as a double. If so, cast to int and see if it is the same value (then it is an int). If it can't be read as a double, it is bad format. Note that you might have to consider if the number is too big to fit an int, or long, etc.
The reason why you are getting the sum as double when both the input's are int is because you are changing the default radix of scanner, hence it fails to recognize the input as int and instead reads it as a double.
If you don't change the radix of scanner, it will use the default radix (10) and scan input at base 10. Now this will work for input: int & double; but will not work for binary input's. All this boils down to your choice of implementation and I don't think you can accomodate all the required inputs with your current approach. I'd suggest following #FredK approach and take the input as string (even that approach has it's own flaws).
There is no way for you to check if the two numbers entered are in fact two separate ints. And also, you are asking for two double parameters and your sum is also a double so when you put the ints into the bigFunction, you are always casting them to doubles and the sum is a double so you will always get a double.
You need to have a check inside the bigFunction function to check if they are in fact two doubles or two ints, etc.
Or in fact make separate functions, but always strive for laziness!
Hope that gets the gears churning!
In java an integer is a form of double if you run the code
int a =4
int b =5
double b = a +c
System.out.print(b);
this would work as an integer is a form of double.
the easiest way would be to rename your double method to something else
best solution
userinput (the double) = variable
if ((variable == Math.floor(variable))
this rounds the number do so 5.9 would be 5 and if the that is equal to variable you have an int.

Could anyone tell me why my program doesn't work?

The program reads values from scanner until the value 0 is given, which finishes the process. The program will compile the sum only if all the numbers given are integers. In all the other situations (where not all of the values are integers) the program won't give anything out.
So i noticed my program gives out the sum of the integers even if there are other non integer values given and sometimes when they are all integers given it doesn't show the real sum just one of the numbers or something.
import java.util.Scanner;
public class Testing3{
public static void main(String[] args) {
int sum1 = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number");
String number = input.nextLine();
int value =Integer.parseInt(number);
while(true) {
if (value!=0) {
number = input.nextLine();
if (Math.round(value)==value)//condition to integer{
sum1 = sum1 + value;
} else {
System.out.println(sum1);
break;
}
}
}
}
First of all, use while(true) or for(;;) to make in infinite loop
Second use nextInt() to read integers instead of doubles because you have no use for doubles. Alternatively, read strings with readLine and check their validity with Integer.parseInt.
Thirdly, you have a syntax error (so it shouldn't compile). You have an unmatched close brace near the else.
Lastly, remove the if (number != 0) because that will cause your program to continuously repeat in the loop without doing anything forever. Change the inside of the loop to:
number = input.nextInt();
if (number != 0){
sum1 = sum1 + number; //or use sum1 += number
} else {
System.out.println(sum1);
break;
}
I think your problem is at the place where you test for an integer. I don't think x mod 1 == 0 is correct suitable here. What I'll do when I am asked to check whether a number is an integer, I round the number and check if it equals to the original number.
Let's say we have a double variable called x and this evaluates to true if x is an integer:
Math.round(x) == x
I don't know whether there is a better way to do it but that's how I would do it and I like it.

Why wont this program allow me to divide

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);}
}

Categories

Resources