Runtime error while handling large numbers - java

I am trying to write code for a problem that involves a function, that takes input numbers as Strings, and returns the remainder of that input when divided by 7 as an int.
Although the code works for smaller numbers, it prompts a runtime error when handling large numbers as input, shown as follows ..
Runtime error time: 0.04 memory: 711168 signal:-1
Exception in thread "main" java.lang.NumberFormatException: For input string: "5‌​449495"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.math.BigInteger.<init>(BigInteger.java:470)
at java.math.BigInteger.<init>(BigInteger.java:597)
at Ideone.remainderWith7(Main.java:13)
at Ideone.main(Main.java:22)
My code is as follows ..
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
int remainderWith7(String num) {
// Your code here
java.math.BigInteger bg = new java.math.BigInteger(num);
//System.out.println(num);
Integer n = bg.intValue();
return (int) n % 7;
}
public static void main(String[] args) throws java.lang.Exception {
// your code goes here
Ideone id = new Ideone();
System.out.println(id.remainderWith7("56495654565052555054535456545355495650575755555757575350505‌​44949525452505653565‌​54949515453545151525‌​15050575749545453535‌​54954555157565253514‌​94949495155515455545‌​65555575452555157505‌​55557495050564952514‌​95051505752545155495‌​65156515750555450545‌​35549535551525149535‌​25654525554535154515‌​05251575251494956515‌​35255515450515553515‌​15657545054505357535‌​55654575549575349565‌​351575054"));
}
}

How'd you paste that string in? It looks like it contains a lot of zero-width spaces and zero-width non-joiners.
I say "looks like"; in actuality, you'd only ever be able to see those if you printed out the contents of the string's array, either with Arrays.toString and encapsulating that long string in a variable, or if you inspected it with a debugger.
Ultimately, that's what's leading you astray; Java is attempting to convert those Unicode characters to numbers, and since they're not numbers, they convert to -1. This is why your code breaks, and this is also why it's not immediately apparent as to why it breaks. There are more characters in that string than you're immediately led to believe.
The fix is to remove these characters from the string.
String num = ""; // enter your long number here; not repeating it for brevity's sake
num = num.replace("\u200C", "").replace("\u200B", "");
Now you can get back to other issues with the code, such as not using BigInteger.mod when you want to do a modulo (because trust me, using % ain't gonna give you the right answer with an integer as large as that).

Related

In what format is data sent on, getInputStream on a URLconnection Object?

Im trying to connect to a php script on a server and retrieve the text the script echoes.Do accomplish I used the following code.
CODE:=
import java.net.*;
import java.io.*;
class con{
public static void main(String[] args){
try{
int c;
URL tj = new URL("http://www.thejoint.cf/test.php");
URLConnection tjcon = tj.openConnection();
InputStream input = tjcon.getInputStream();
while(((c = input.read()) != -1)){
System.out.print((char) c);
}
input.close();
}catch(Exception e){
System.out.println("Caught this Exception:"+e);
}
}
}
I do get the desired output that is the text "You will be Very successful".But when I remove the (char) type casting it yields a 76 digit long.
8911111732119105108108329810132118101114121321151179999101115115102117108108
number which I'm not able to make sense of.I read that the getInputStream is a byte stream, then should there be number of digits times 8 number long output?
Any insight would be very helpful, Thank you
It does not print one number 76 digits long. You have a loop there, it prints a lot of numbers, each up to three digits long (one byte).
In ASCII, 89 = "Y", 111 = "o" ....
What the cast to char that you removed did was that it interpreted that number as a Unicode code point and printed the corresponding characters instead (also one at a time).
This way of reading text byte by byte is very fragile. It basically only works with ASCII. You should be using a Reader to wrap the InputStream. Then you can read char and String directly (and it will take care of character sets such as Unicode).
Oh I thought it would give out the byte representation of the individual letter.
But that's exactly what it does.
You can see it more clearly if you use println instead of print (then it will print each number on its own line).

error while parsing an int from a char in String

import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(s, s.charAt(0)); // ERROR!
}
}
I want to parse the input string based on char position to get the positional integer.
Error message:
Exception in thread "main" java.lang.NumberFormatException: radix 49 greater than Character.MAX_RADIX
at java.lang.Integer.parseInt(Unknown Source)
at test.main(test.java:11)
That method you are calling parseInt(String, int) expects a radix; something that denotes the "number system" you want to work in, like
parseInt("10", 10)
(10 for decimal)! Instead, use
Integer.parseInt(i)
or
Integer.parseInt(i, 10)
assuming you want to work in the decimal system. And to explain your error message - lets have a look at what your code is actually doing. In essence, it calls:
Integer.parseInt("123", '1')
and that boils down to a call
Integer.parseInt("123", 49) // '1' --> int --> 49!
And there we go - as it nicely lines up with your error message; as 49 isn't a valid radix for parsing numbers.
But the real answer here: don't just blindly use some library method. Study its documentation, so you understand what it is doing; and what the parameters you are passing to it actually mean.
Thus, turn here and read what parseInt(String, int) is about!
Integer.parseInt(parameter) expects the parameter to be a String.
You could try Integer.parseInt(s.charAt(0) + ""). The +"" is to append the character to an empty String thereby casting the char to String and this is exactly what the method expects.
Another method to parse Characters to Integers (and in my opinion much better!) is to use Character.getNumericValue(s.charAt(0));
Check this post for further details on converting char to int
Need to convert String.valueOf(s.charAt(0)) to String.valueOf(s.charAt(0)) i.e. Char to String.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(String.valueOf(s.charAt(0)));
}
}
Let use what we have here.
To parse one digit from a String into an integer. Use getNumericValue(char)
In your case, to get the first character into a number :
int n = Character.getNumericValue(s.charAt(0));
Be aware that you should take the absolute value if you integer can be negative.

How do I properly use the java.lang.Math?

I am in a COMP 110 class which is intro to Java. This specific program is irrelevant to the class but to help my own understanding with Java.
I believe I have imported the tool to allow the program to calculate basic math operations by using "java.lang.Math;"
I understand * is multiplication, / is division, + is addition, - is subtraction, and % finds the remainder.
The final line of the program gives me the error message:
squared.java:14: operator * cannot be applied to java.lang.String,java.lang.String
and I am at a loss for why because I have imported the language Math, which should enable me to use the * to multiply the value variable when I enter "value * value"
import java.util.Scanner;
import java.lang.Math;
public class squared {
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
System.out.println("What number do you want to find the square of?");
String value = number.nextLine();
System.out.println("The square of the number" + value + "is" + value * value);
}
}
Yes you must first convert it into an Integer, Double, Float, etc in order to do a multiplication on such. So just do
int v = Integer.parseInt(value.trim());
Then
System.out.println("The square of the number"+v+"is"+ (v * v));
Also using operators has nothing to do with Math library. Math library is used like so:
double d = Double.parseDouble(value.trim());
Math.pow(d,2.0); //which does the same thing above
There are two approaches to go about this program -
1) Read the input as String and then convert it to int or
2) Read the input as int(or double?) itself.
Following code shows how you can read the input as int and perform the operation.
Note the code change (value*value) in your sysout statement. When you concatenate any value to a string, it get treated as string, and hence you are getting the error. Put it in parenthesis such that before concatenating, actual value*value operation is performed.
public class squared {
public static void main(String[] args){
Scanner number = new Scanner(System.in);
System.out.println("What number do you want to find the square of?");
int value = number.nextInt();
System.out.println("The square of the number"+value+"is"+ (value * value));
}
}
Talking about Math.pow(), it doesn't serve any different purpose here. Using it is same as the way you have done here.
First of all, you don't need to import java.lang.Math. All of the java.lang libraries are already there. Also, you don't need to use the Math library for operations. You use it for things like Math.sin() to find the sine of an angle, or Math.pow() to get the power of one number to another. If you want a full list of the uses for java.lang.Math, here is a link: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
You probably want to store the input in a double, so rather than using number.nextLine(), you may want to use number.nextDouble(), and store it in a double, as below.
double value = number.nextDouble();
You were storing the value as a String, so the computer was reading the input as a quotation, like "cat," rather than the numbers. It doesn't work because what you were trying to do was akin to saying
"cat" * "dog."
Good luck in the class!

Compare first two decimal points

Suppose if I have 3.13 and 4.13, I want to be able to check whether .13 from 3.13 and .13 from 4.13.
I tried many things:
1) converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
2) a = 3.14;
a = a - Math.floor(a); to try to get the decimal alone but i end up getting 0.1400000001
converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
split uses a regex, so you have to escape the dot.
string.split(".")
should become
string.split("\\.")
With this you should be able to split the string properly and do your comparisons
By the way, i would use Reimenus solution, when you have numbers it's always better to use math if you can. Use strings only if you really need them.
You could separate the fractional part for comparison instead
double value1 = 3.13;
double value2 = 4.13;
double fractional1 = value1 - (long)value1;
double fractional2 = value2 - (long)value2;
System.out.println(Double.compare(fractional1, fractional2));
Read What Every Computer Scientist Should Know About Floating-Point Arithmetic too see
why you're seeing additional digits after your own numerical operation
your second method is actually correct. when comparing double values, you have to include a range.. Java: Double Value Comparison (refer this)
Try this out
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float v1 = 3.13f,v2 = 4.13f;
//Converting float value into String array
String split1[]=Float.toString(v1).split("\\.");
String split2[]=Float.toString(v2).split("\\.");
//Comparing two strings
if(split1[1].equals(split2[1]))
{
System.out.println("Yes");
}
}
}

java convert to int

I am trying to convert to int like this, but I am getting an exception.
String strHexNumber = "0x1";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
It would be a great help if someone can fix it.
Thanks.
That's because the 0x prefix is not allowed. It's only a Java language thing.
String strHexNumber = "F777";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println(decimalNumber);
If you want to parse strings with leading 0x then use the .decode methods available on Integer, Long etc.
int value = Integer.decode("0x12AF");
System.out.println(value);
Sure - you need to get rid of the "0x" part if you want to use parseInt:
int parsed = Integer.parseInt("100", 16);
System.out.println(parsed); // 256
If you know your value will start with "0x" you can just use:
String prefixStripped = hexNumber.substring(2);
Otherwise, just test for it:
number = number.startsWith("0x") ? number.substring(2) : number;
Note that you should think about how negative numbers will be represented too.
EDIT: Adam's solution using decode will certainly work, but if you already know the radix then IMO it's clearer to state it explicitly than to have it inferred - particularly if it would surprise people for "035" to be treated as octal, for example. Each method is appropriate at different times, of course, so it's worth knowing about both. Pick whichever one handles your particular situation most cleanly and clearly.
Integer.parseInt can only parse strings that are formatted to look just like an int. So you can parse "0" or "12343" or "-56" but not "0x1".
You need to strip off the 0x from the front of the string before you ask the Integer class to parse it. The parseInt method expects the string passed in to be only numbers/letters of the specified radix.
try using this code here:-
import java.io.*;
import java.lang.*;
public class HexaToInteger{
public static void main(String[] args) throws IOException{
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexadecimal value:!");
String s = read.readLine();
int i = Integer.valueOf(s, 16).intValue();
System.out.println("Integer:=" + i);
}
}
Yeah, Integer is still expecting some kind of String of numbers. that x is really going to mess things up.
Depending on the size of the hex, you may need to use a BigInteger (you can probably skip the "L" check and trim in yours ;-) ):
// Convert HEX to decimal
if (category.startsWith("0X") && category.endsWith("L")) {
category = new BigInteger(category.substring(2, category.length() - 1), 16).toString();
} else if (category.startsWith("0X")) {
category = new BigInteger(category.substring(2, category.length()), 16).toString();
}

Categories