A. Gisbert A. Gisbert - 1 year ago 136
Java Question

Java-Error trying to sort an int

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("");
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();

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

C:\Users\agn12\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

Answer Source

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("");
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();
String str1 = new String(max);

The rest of your code can stay the same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download