How does one add extremely large values in Java? - java

I've tried the code below, but I'm getting an error. How would I go about adding two large values represented as strings together?
public class LargeAddition {
static String testcase1 = "987659876598765";
static String testcase2 = "9999999999999999999999999988888888888";//can we add this kind of large num
public static void main(String args[]){
LargeAddition testInstance = new LargeAddition();
String result = testInstance.add(testcase1,testcase2);
System.out.println("Result : "+result);
}
//write your code here
public String add(String str1, String str2){
Long num=000000000000000L;
//String str="";
num=Long.parseLong(str1)+Long.parseLong(str2);
//String str=num.toString();
return num.toString();
}
}

Use BigInteger, Long is short for these values.
public static String add(String str1, String str2) {
BigInteger big1 = new BigInteger(str1);
BigInteger big2 = new BigInteger(str2);
final BigInteger num = big1.add(big2);
return num.toString();
}

Since this is an a homework assignment and you don't/can't use classes such as BigInteger, I'll go through a more tedious and manual way to do it (although a good introduction assignment).
You can loop through the two String-integers from size-1 to 0.
String integer1 = "1230"
String integer2 = "9999999"
for(int i = integer1.size; i >= 0; i--){
//addition
}
However, this is may be an issue since the two String-integers have different sizes. I would create a method that will add additional zeroes to the front of the smaller String-integer so both String-integers match in size. Ex. "1230" -> "0001230"
Before looping, create an output String-inter which equals to an empty-String.
String outputInt = "";
Convert each char to an int, then do the addition.
int tempResult = Integer.parseInteger(integer1.indexOf(i)) + Integer.parseInteger(integer2.indexOf(i))
If you get a single digit, convert it to a String and append to output String-integer. If you get a double digit, then only put append the second digit and carry over the first digit to the next calculation.
String tempResultStr = //convert tempResult into a String
if(tempResultStr .size == 1){
//handle single digit case
}else{
//handle double digit case
//use a variable to declare carry over
}
Remember to handle the case if you have to carry over and there is nothing to carry over to.
NOTE: This is pseudo code for most part

If you run
System.out.println(Long.MAX_VALUE);
you'll get
9223372036854775807
your values are far greater
9999999999999999999999999988888888888
so the way is to use BigDecimal
BigDecimal bd = new BigDecimal("9999999999999999999999999988888888888");
System.out.println(bd.multiply(bd));
gives you
99999999999999999999999999777777777760000000000000000123456790143209876544

Related

Check if any part of a string input is not a number

I couldnt find an answer for this in Java, so I'll ask here. I need to check if 3 parts of a string input contains a number (int).
The input will be HOURS:MINUTES:SECONDS (E.g. 10:40:50, which will be 10 hours, 40 minutes and 50 seconds). So far I am getting the values in String[] into an array by splitting it on :. I have parsed the strings into ints and I am using an if statement to check if all 3 parts is equal or larger than 0. The problem is that if I now use letters I will only just get an error, but I want to check if any of the 3 parts contains a character that is not 0-9, but dont know how.
First I thought something like this could work, but really dont.
String[] inputString = input.split(":");
if(inputString.length == 3) {
String[] alphabet = {"a","b","c"};
if(ArrayUtils.contains(alphabet,input)){
gives error message
}
int hoursInt = Integer.parseInt(inputString[0]);
int minutesInt = Integer.parseInt(inputString[1]);
int secondsInt = Integer.parseInt(inputString[2]);
else if(hoursInt >= 0 || minutesInt >= 0 || secondsInt >= 0) {
successfull
}
else {
gives error message
}
else {
gives error message
}
In the end I just want to check if any of the three parts contains a character, and if it doesnt, run something.
If you are sure you always have to parse a String of the form/pattern HH:mm:ss
(describing a time of day),
you can try to parse it to a LocalTime, which will only work if the parts HH, mm and ss are actually valid integers and valid time values.
Do it like this and maybe catch an Exception for a wrong input String:
public static void main(String[] arguments) {
String input = "10:40:50";
String wrongInput = "ab:cd:ef";
LocalTime time = LocalTime.parse(input);
System.out.println(time.format(DateTimeFormatter.ISO_LOCAL_TIME));
try {
LocalTime t = LocalTime.parse(wrongInput);
} catch (DateTimeParseException dtpE) {
System.err.println("Input not parseable...");
dtpE.printStackTrace();
}
}
The output of this minimal example is
10:40:50
Input not parseable...
java.time.format.DateTimeParseException: Text 'ab:cd:ef' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalTime.parse(LocalTime.java:441)
at java.time.LocalTime.parse(LocalTime.java:426)
at de.os.prodefacto.StackoverflowDemo.main(StackoverflowDemo.java:120)
I would personally create my own helper methods for this, instead of using an external library such as Apache (unless you already plan on using the library elsewhere in the project).
Here is an example of what it could look like:
public static void main(String[] arguments) {
String time = "10:50:45";
String [] arr = time.split(":");
if (containsNumbers(arr)) {
System.out.println("Time contained a number!");
}
//You can put an else if you want something to happen when it is not a number
}
private static boolean containsNumbers(String[] arr) {
for (String s : arr) {
if (!isNumeric(s)) {
return false;
}
}
return true;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
containsNumbers will take a String array as an input and use an enhanced for loop to iterate through all the String values, using the other helper method isNumeric that checks if the String is a number or not using regex.
This code has the benefit of not being dependent on Exceptions to handle any of the logic.
You can also modify this code to use a String as a parameter instead of an array, and let it handle the split inside of the method instead of outside.
Note that typically there are better ways to work with date and time, but I thought I would answer your literal question.
Example Runs:
String time = "sd:fe:gbdf";
returns false
String time = "as:12:sda";
returns false
String time = "10:50:45";
returns true
You can check the stream of characters.
If the filter does not detect a non-digit, return "Numeric"
Otherwise, return "Not Numeric"
String str = "922029202s9202920290220";
String result = str.chars()
.filter(c -> !Character.isDigit(c))
.findFirst().isEmpty() ? "Numeric"
: "Not Numeric";
System.out.println(result);
If you want to check with nested loop you can see this proposal:
Scanner scanner = new Scanner(System.in);
String [] inputString = scanner.nextLine().split(":");
for (int i = 0; i < inputString.length; i++) {
String current = inputString[i];
for (int k = 0; k < current.length(); k++) {
if (!Character.isDigit(current.charAt(k))) {
System.out.println("Error");
break;
}
}
}
you could use String.matches method :
String notANum= "ok";
String aNum= "7";
if(notANum.matches("^[0-9]+$") sop("no way!");
if(aNum.matches("^[0-9]+$") sop("yes of course!");
The code above would print :
yes of course
The method accepts a regex, the one in the above exemple is for integers.
EDIT
I would use this instead :
if(input.matches("^\d+:\d+:\d+$")) success;
else error
You don't have to split the string.
I tried to make your code better, take a look. You can use Java regex to validate numbers. also defined range for time so no 24:61:61 values is allowed.
public class Regex {
static boolean range(int timeval,int min,int max)
{
boolean status=false;
if(timeval>=min && timeval<max)
{status=true;}
return status;
}
public static void main(String[] args) {
String regex = "[0-9]{1,2}";
String input ="23:59:59";
String msg="please enter valid time ";
String[] inputString = input.split(":");
if(inputString[0].matches(regex) && inputString[1].matches(regex) && inputString[2].matches(regex) )
{
if(Regex.range(Integer.parseInt(inputString[0]), 00, 24) &&Regex.range(Integer.parseInt(inputString[1]), 00, 60) && Regex.range(Integer.parseInt(inputString[2]), 00, 60))
{msg="converted time = " + Integer.parseInt(inputString[0]) + " : " +Integer.parseInt(inputString[1])+ " : " +Integer.parseInt(inputString[2]) ;}
}
System.out.println(msg);
}
}

Why to add a Empty String while adding an string with int?

In the below when I wasn't adding the ""(Empty String), the output was in int, which is pretty abnormal because adding a String with an int always gives a string. But as soon as I added the Empty String thing, the code seemed to work fine. In both the cases,I was adding a string from the string array that I created earlier in the code.
import java.io.*;
public class TooLong{
public static void main(String[] args) throws IOException{
InputStreamReader n = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(n);
byte i ;
i=Byte.parseByte(input.readLine());
String origWords[] = new String[i];
for (int j=0;j<i;j++) origWords[j]= input.readLine();
for (int j=0;j<i;j++){
int charLength = origWords[j].length();
if (charLength < 11) System.out.println(origWords[j]);
else System.out.println(origWords[j].charAt(0) +""+ (charLength-2) + origWords[j].charAt(charLength-1) );
}
}
}
I assume, you are trying to achieve “internationalization ⇒ i18n”
That is because String.charAt(int) returns char. Which will be treated as numerical when using +.
By using + with the empty String you force the compiler to convert everything to String
You can use String.substring(0,1) instead of the first charAt to force type String conversion
The charAt() method of String returns the char. char is one of the primitive data types. char is a textual primitive, however, it also can do arithmetic operations like numerical primitives. The codes below are examples for it:
`public static void main(String args[]){
String st = "i am a string";
char c = st.charAt(0);
System.out.println(c);
System.out.println(c+ st.charAt(2));
System.out.println(c+ "" + st.charAt(2));
}
`
The result of the above code will be:
i
202
ia
Hope this example makes it clear.

Round up to two places of decimal of java without reassigning to new variable

I have the following code where I need to print value up to two decimal places removing the dot(.) from the number.
How ever sometimes it print up to two and sometimes up to three places off decimal.
public class CheckSubString3 {
public static void main(String[] args) {
Double[] d={134344.00d,234434.08d,234434.02d};
for(int i=0; i<d.length; i++){
System.out.println((d[i])*(25)/100);
System.out.println(parseLonggetFormattedAmount((d[i])*(25)/100));
System.out.println();
}
}
private static String parseLonggetFormattedAmount(double d) {
DecimalFormat format = (DecimalFormat) NumberFormat
.getInstance(new Locale("en", "gb"));
format.setMinimumFractionDigits(2);
FieldPosition f = new FieldPosition(0);
StringBuffer s = new StringBuffer();
String value = format.format(d, s, f).toString().replace(',', ' ')
.replace('.', ' ');
return value.replaceAll(" ","");
}
}
Below is the output:
original value 33586.0
required value 3358600
original value 58608.52
required value 5860852
original value 58608.505
required value 58608505// This line is giving upto 3 places of decimal
According to the NumberFormat documentation, you could use setMaximumFractionDigits(int newValue)
Sets the maximum number of digits allowed in the fraction portion of a number.
just put it in your function parseLonggetFormattedAmount(double d):
format.setMaximumFractionDigits(2);
It seems you simply want to multiply the doubles by 100 and round to the nearest integer. So your method could be written:
private static String parseLonggetFormattedAmount(double d) {
return String.valueOf(Math.round(d * 100));
}
Which outputs:
3358600
5860852
5860851

Making a loop that returns the characters before it hits a colon character

Whenever I run my code it returns this error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at codes.Main.main(Main.java:10)
Here is my code:
package codes;
public class Main {
public static void main(String[] args) {
String cord1 = "Name: x=23 y=60 z= 600";
String cord2 = "Name: x=200 y=20 z= 300";
int c1 = cord1.length();
String mychar = String.valueOf("cord1".charAt(0));
for (int a = 0; a < c1; a++){
mychar = String.valueOf("cord1".charAt(a));
if (mychar == ":"){
break;
}else{
cord1.substring(a);
}
}
}
}
There are multiple things wrong in your code..
mychar == ":" should be mychar.equals(":") instead. Since Strings are immutable, we need to use the .equals to compare them instead of == (<- this checks if the references are equal instead of the String-values).
"cord1".charAt should be your variable cord1.charAt.. By using "cord1" you basically create a new String with the value cord1.
cord1.substring(a); doesn't change the cord1 value, but returns a new String. So you'll have to save this String result, or print it, and then stop the loop with a break.
Using cord1 = cord1.substring(a) would shorten the String itself. Since you still loop in the range [0, c1) where c1 was the original String, we would still get a StringIndexOutOfBoundsException. Instead, you don't need the else-case and need both the cord1 = cord1.substring(a) and break inside the if-case. (Also, I assume you want to remove the : itself as well, so you'll have to use .substring(a+1) instead.)
Also, why use String.valueOf( char ) instead of just using the char themselves? Not really a requirement, but the String.valueOf is kinda redundant here, and makes the code less readable.
Putting it all together:
public class Main {
public static void main(String[] args) {
String cord1 = "Name: x=23 y=60 z= 600";
System.out.println("cord1 before:\t" + cord1);
int c1 = cord1.length();
char mychar = cord1.charAt(0);
for (int a = 0; a < c1; a++){
mychar = cord1.charAt(a);
if (mychar == ':'){
cord1 = cord1.substring(a+1);
break;
}
}
System.out.println("cord1 after:\t" + cord1);
}
}
Which will result in cord1 having the value " x=23 y=60 z= 600" (note the leading space) in the end.
Try it online.
Here is a much simpler alternative with the same result:
String cord1 = "Name: x=23 y=60 z= 600";
String cord1ExcludingName = cord1.replaceFirst("^.*:","");
Try it online.
^ : Only look at the start of the String for:
.* : Zero or more of any character,
: : followed by a `:`
Which will be replaced with "" (an empty String), so they're basically removed.
Use equals instead of "=="
Like this
if (mychar.equals(":")){
break;
You need to use equals method because you are working with a string. Whenever you work with string u must compare them with the method equals.
If you used
char myChar = .....
Your code would work. You can compare chars with "=="
String.valueOf("cord1".charAt(0)) means you are looking into the 0th character of string "cord1" which has a highest index of 4, that is why it is giving out of bound exception at 5.
What you have to do is String.valueof(cord1.charAt(0)). This will consider the string in the variable cord1.

Is there such thing as math.substring in java?

Okay, I'm just getting curious. But I was wondering if there was such thing as a substring for numbers (math.substring ?), and then it would get the character(s) in the position specified.
Example (really poorly thought out one)
int number = 5839;
int example = number.substring(0,1)
println = example;
and then it displays 5?
Why don't you just convert it to a string, and then call substring(0,1)?...
int number = 5839;
int example = Integer.parseInt((number+"").substring(0,1));
Where calling number+"" causes the JVM to convert it into a String, and then it calls substring() on it. You then finally parse it back into an int
int number = 5839;
String numString = Integer.toString(number);
String example = numString.substring(0,1)
int subNum = Integer.parseInt(example);
System.out.println(subNum);
Change it to a String first.
Here's a little function I wrote:
public static int intSubstring(int number, int beginIndex, int endIndex) {
String numString = Integer.toString(number);
String example = numString.substring(beginIndex,endIndex)
int subNum = Integer.parseInt(example);
return subNum;
}
Or compressed:
public static int intSubstring(int number, int beginIndex, int endIndex) {
return Integer.parseInt((number+"").substring(beginIndex,endIndex));
}
No there is not. But you could possibly convert the integer to string and get the substring and again parse back to integer
No there no such thing, but you can do the following:
String s = ""+number; //You can now use the Substring method on s;
Or if you just want to remove the last y digits:
number = (int)(number/y);
of if you want to keep only the last z digits:
number = number%(Math.pow(10,z)); // % means modulo
No, there is none. int is a primitive data type. You can however, accomplish your need with one statement.
Integer.parseInt(String.valueOf(12345).substring(1, 2))

Categories

Resources