Java-Error trying to sort an int - java

package programame;
import java.util.Scanner;
import java.util.Arrays;
public class E100 {
public static int ascendente(int a)
{
String str = Integer.toString(a);
String max[] = str.split("");
Arrays.sort(max);
String str1 = Arrays.toString(max);
int ascendente = Integer.parseInt(str1);
return ascendente;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int intentos = sc.nextInt();
int x = sc.nextInt();
System.out.println(ascendente(x));
}
}
Hi, I am trying to sort an int read from a scanner, but everytime I run it it gives me the error =
Exception in thread "main" java.lang.NumberFormatException: For input string: "[3, 4, 6, 7]" at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at
java.lang.Integer.parseInt(Integer.java:615) at
programame.E100.ascendente(E100.java:18) at
programame.E100.main(E100.java:25)
C:\Users\agn12\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

The exception
java.lang.NumberFormatException: For input string: "[3, 4, 6, 7]"
says that Java cannot convert such string to an Int as you are requesting.
It can be of use to be able to read the compiler error:
programame.E100.ascendente(E100.java:18) at
programame.E100.main(E100.java:25)
It tells you that the problem arises at line 25 in method main of E100.java, that in turn calls the method ascendente and the problem is at line 18 where you try to convert to an int an array of strings.

You are trying to split the number 3467 into its constituent decimal digits, sort them, and re-construct the digits into a single string:
String max[] = str.split("");
Arrays.sort(max);
String str1 = Arrays.toString(max);
The problem is that Arrays.toString returns a human-readable representation of the array, which is in the form "[3, 4, 6, 7]". This, obviously, cannot be parsed as an int. You are expecting to get the string "3467".
A better way of doing it (in terms of runtime efficiency and ease of coding) is to split the string into individual characters, instead of one-character strings. Then you can sort them, and easily turn them back into a string using one of String's constructors:
char[] max = str.toCharArray();
Arrays.sort(max);
String str1 = new String(max);
The rest of your code can stay the same.

The fault is with this line
String str1 = Arrays.toString(max);
You are trying to convert an array of numbers to string so
max = [2]
So str1 = "[2]"
and then converting this to a number
int ascendente = Integer.parseInt(str1);
Gives an error :: java.lang.NumberFormatException

Related

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.

Why is parseInt in java unable to identify integers in my input string?

After inputting a string and separating it into different parts, I have used parseInt to separate integers from an input string. But while running the program, a NumberFormatException generated on the string " 4", which clearly has the integer '4' in it. input is a file reading scanner type variable already declared in the program prior to this operation.
String line = input.nextLine();
String[] part = line.split(", ");
int tempParticleNumber;
tempParticleNumber = Integer.parseInt(part[0]);
The terminal output is
Exception in thread "main" java.lang.NumberFormatException: For input string: " 4"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:638)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
Expected process is that the input string " 4" is converted to an integer 4, but this doesn't happen.
You haven't taken into account the space that is coming with part[0], your part[0] is not '4', its ' 4' which is not an integer.
Try doing this :
line = line.substring(1);
String[] part = line.split(", ");
int tempParticleNumber;
tempParticleNumber = Integer.parseInt(part[0]);
This will make the string get rid of the initial space.
Simply trim() the whitespaces:
tempParticleNumber = Integer.parseInt(part[0].trim());

NumberFormatException while converting large textual numbers to BigInteger

I have a .dat file that contains lots of huge numbers such as 568e24 1.20536e8 1.3526e12 1.5145e11. And I already input these numbers as String, and stored in ArrayList. I need to use these number to calculate and represent gravitational body in Solar System. But in java it already exceeds the upper limit of Double and Int. What am I suppose to do to use these numbers in Java.
Here is my code that input these data and store these data as String in ArrayList.
public static void main(String[] args) throws Exception{
Scanner input = new Scanner(new File("solarsystem.dat"));
ArrayList<String[]> BodyData = new ArrayList<String[]>();
input.nextLine();
while(input.hasNextLine()){
String x = input.nextLine();
String[] x1 = x.split("[^a-zA-Z0-9().]+");
BodyData.add(x1);
}
System.out.println(BodyData.get(0)[0]);
I am trying to use BigInteger to change String to BigIntiger by following code:
BigInteger reallyBig = new BigInteger("1898e24");
System.out.print(reallyBig);
But the output is wrong:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1898e24"
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:606)
at tryScanner.main(tryScanner.java:18)
So ...now.. what should I do to use this large number such as 1898e24. Do I need to change the format of this number (1898e24), such as 1898000000000...?
You could use something like BigInteger, which should be larger then you need.

How to print ASCII value of an int in JAVA

I've searched for this on the internet but was unable to find a precise solution, one possible solution I found was to read the integer as a String, and use charAt method and then cast the character to int to print the ascii value.
But is there any other possible way to do it other than the above stated method?
int a=sc.nextInt();
//code to convert it into its equivalent ASCII value.
For example, consider the read integer as 1, and now I want the ASCII value of 1 to be printed on the screen,which is 49
I assume you're looking for this:
System.out.print((char)a);
The easy way to do that is:
For the Whole String
public class ConvertToAscii{
public static void main(String args[]){
String number = "1234";
int []arr = new int[number.length()];
System.out.println("THe asscii value of each character is: ");
for(int i=0;i<arr.length;i++){
arr[i] = number.charAt(i); // assign the integer value of character i.e ascii
System.out.print(" "+arr[i]);
}
}
}
For the single Character:
String number="123";
asciiValue = (int) number.charAt(0)//it coverts the character at 0 position to ascii value

To check if a given string is SuperAscii or Not - java.lang.StringIndexOutOfBoundsException

The problem goes like this:
If a is assigned the value 1, b=2,c=3,...z=26, check if a given string is a Super Ascii String or not. A string is said to be a Super Ascii String, if the number of times a character is repeated matches its value. The string must be only in lowercase letters
Eg. abbccc is super ascii because a=1,b=2,c=3. Similarly, bab, "bb a ccc"
This is my attempt in solving the problem
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
public class SuperAsciiNew
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a string : ");
String input = in.nextLine();
char[] inputArray = input.replaceAll("\\s+","").toCharArray();
Arrays.sort(inputArray);
String customInput = new String(inputArray);
char currentChar = customInput.charAt(0);
int increment=0;
Map<Character, Integer> characterMap = new HashMap<Character, Integer>();
char a='a';
boolean superascii = true;
for(int i=1;a<='z';i++,a++)
characterMap.put(new Character(a), new Integer(i));
while(increment<=customInput.length())
{
int nooftimes = customInput.lastIndexOf(currentChar) - customInput.indexOf(currentChar) + 1;
if(characterMap.get(currentChar) == nooftimes)
{
System.out.println("The character "+currentChar+" is repeated "+nooftimes);
increment += nooftimes;
currentChar = customInput.charAt(increment);
}
else
{
superascii = false;
break;
}
}
if(superascii == true)
System.out.println("The given string "+input+" is a Super Ascii string");
else
System.out.println("The given string "+input+" is not a Super Ascii string");
}
}
Here, first I am removing spaces (if any), sorting the string. Then, I find the first character in the string, what is its value and how many times is it repeated. If these two values are not equal then the loop is broken else, the number of times the character is repeated is incremented in increment variable and the next character is found.
The output I get for various test cases:
java SuperAsciiNew
Enter a string : abb ccc
The character a is repeated 1
The character b is repeated 2
The character c is repeated 3
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(String.java:658)
at SuperAsciiNew.main(SuperAsciiNew.java:30)
java SuperAsciiNew
Enter a string : bab
The character a is repeated 1
The character b is repeated 2
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:658)
at SuperAsciiNew.main(SuperAsciiNew.java:30)
java SuperAsciiNew
Enter a string : hello world
The given string hello world is not a Super Ascii string
When the string "hello world" is given, the output is generated without any exceptions. What is the issue here?
I have one more doubt in Java:
What is the difference between importing individual classes like java.util.Scanner and importing the package as whole java.util.*? Are there any performance issues? What I feel is, the second one might consume more memory while the first, the system has to search the appropriate class and include it. Am I right in my thinking?
You are checking for a character one too many times.
Use the following condition:
while(increment<=customInput.length()-1)
instead of:
while(increment<=customInput.length())
Edit: the reason you are not getting the error on "hello world" is because it fails before reaching that extra char, thus not throwing an exception.

Categories

Resources