Hi Pals,
Here said that "java.lang.NullPointerException: Solution.java, method main, line: 18"
An attempt was made to access an uninitialized object (Null).
But in the IDEA return :
Apple
22
Bob
3
Cherry
1
0
Watermelon
Process finished with exit code 0
Please help me.
package com.codegym.task.task09.task0930;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
Task about algorithms
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> list = new ArrayList<String>();
while (true) {
String s = reader.readLine();
if (s.isEmpty()) break;
list.add(s);
}
String[] array = list.toArray(new String[list.size()]);
sort(array);
for (String x : array) {
System.out.println(x);
}
}
public static void sort(String[] array) {
// write your code here
for (int i = 0; i < array.length; i++) {
String minWord = array[i];
int positionMinWord = i;
String maxNumber = array[i];
int positionMaxNumber = i;
//System.out.println("************" + i + array[i] + " ******************");
for (int j = i + 1; j < array.length; j++) {
String sActual = array[i];
String sNext = array[j];
//Print
//System.out.println( j + " next: " + sNext);
//Order 9 - > 0
if (isNumber(sActual)) {
if (isNumber(sNext)) {
int actual= Integer.parseInt(sActual);
int next = Integer.parseInt(sNext);
if(next > actual) {
maxNumber = sNext;
positionMaxNumber = j;
//print
//System.out.println("MaxNumber: " + maxNumber);
}
}
}
// Order a -> z
else if (!(isNumber(sActual)) && !(isNumber(sNext))) {
if (isGreaterThan(sActual, sNext)) {
minWord = sNext;
positionMinWord = j;
//print
//System.out.println("MinWord: : " + minWord);
}
}
if (j == array.length - 1) {
if (isNumber(sActual)) {
array[positionMaxNumber] = array[i];
array[i] = maxNumber;
} else {
array[positionMinWord] = array[i];
array[i] = minWord;
}
//System.out.println("Nuevo en posicion array[i]: " + array[i]);
}
}
}
}
// String comparison method: 'a' is greater than 'b'
public static boolean isGreaterThan(String a, String b) {
return a.compareTo(b) > 0;
}
// Is the passed string a number?
public static boolean isNumber(String s) {
if (s.length() == 0) return false;
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((i != 0 && c == '-') // The string contains a hyphen
|| (!Character.isDigit(c) && c != '-') // or is not a number and doesn't start with a hyphen
|| (i == 0 && c == '-' && chars.length == 1)) // or is a single hyphen
{
return false;
}
}
return true;
}
}