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-1;i++){
if(isNumber(array[i])){
for(int j=i+1;j<array.length;j++){
if(isNumber(array[j])){
int a,b;
a=Integer.parseInt(array[i]);
b=Integer.parseInt(array[j]);
if(a<b){
String temp=array[i];
array[i]=array[j];
array[j]=temp;
}
else{
}
}
}
}
else{
for(int j = i + 1; j < array.length; j++){
if(isNumber(array[j])==false){
if(isGreaterThan(array[i],array[j])==false){
String flag=array[i];
array[i]=array[j];
array[j]=flag;
}
}
else{
}
}
}
}
}
// 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;
}
}
My code is throwing null pointer exception error on the 18th line. not able to find a way to resolve it.Can anyone help
Resolved
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Anthony Chalk
12 December 2019, 09:40
You're adding an empty String to the list
0
shaan mohd khan QA Automation Engineer at mphasis Ltd
12 December 2019, 10:14
Thanks anthony.. checking on it.
0
oli blaustrom
12 December 2019, 18:27
No that's not it, the s.isEmpty() throws the nullpointer exception. break actually prevents list.add(s) to be executed. Hoare.
0
oli blaustrom
12 December 2019, 18:27
fix by changing s.isemtpy to s == null
0
shaan mohd khan QA Automation Engineer at mphasis Ltd
13 December 2019, 04:18
yupp.. Its working now.. thanx for help
0