Ordering Strings in java [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have an assignment where i am supposed to create an object that initializes an array of strings to have "size" elements and the amount of used elements equal to 0.
my issue is when im trying to compare strings to put them in alphabetical order.
int compare = storage[index].compareTo(value);
if (compare < 0)
thats where i am getting the runtime error of a nullpointerexception
here is my full code.
class main
package assignment2;
public class Main {
public static void main(String[] args) {
OrderedStringList myList = new OrderedStringList(5);
System.out.println("adding 10, 5, & 7");
myList.Insert("10");
myList.Insert("5");
myList.Insert("7");
myList.Display();
System.out.println("Value 4 find = "+ myList.Find("4"));
System.out.println("Value 7 find = "+ myList.Find("7"));
System.out.println("Adding 24 & 3");
myList.Insert("24");
myList.Insert("3");
myList.Display();
System.out.println("myList size: "+ myList.Size());
if (!myList.Insert("12"))
System.out.println("Could not add 12, full");
System.out.println("Removing 10, adding 12.");
myList.Delete("10");
myList.Insert("12");
myList.Display();
}
}
class OrderedStringList
package assignment2;
public class OrderedStringList {
int length;
int numUsed;
String[] storage;
boolean ordered;
public OrderedStringList(int size){
length = size;
storage = new String[length];
numUsed = 0;
}
public boolean Insert(String value){
boolean result = false;
int index = 0;
if (numUsed < length) {
while (index <= numUsed) {
int compare = storage[index].compareTo(value);
if (compare < 0)
index++;
}
moveItemsDown(index);
storage[index] = value;
numUsed++;
result = true;
}
return result;
}
private void moveItemsDown(int start){
int index;
for (index = numUsed-1; index >=start; index--){
storage[index+1] = storage[index];
}
}
private void moveItemsUp(int start){
int index;
for (index = start; index < numUsed-1; index++){
storage[index] = storage[index+1];
}
}
public boolean Find(String value){
return (FindIndex(value) >= 0);
}
private int FindIndex(String value) {
int result = -1;
int index = 0;
boolean found = false;
while ((index < numUsed) && (!found)) {
found = (value.equals(storage[index]));
if (!found)
index++;
}
if (found)
result = index;
return result;
}
public boolean Delete(String value){
boolean result = false;
int location;
location = FindIndex(value);
if (location >= 0) {
moveItemsUp(location);
numUsed--;
result = true;
}
return result;
}
public void Display() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.println(index+" "+storage[index]);
}
System.out.println("-------------");
System.out.println();
}
public void DisplayNoLF() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.print(storage[index]+" ");
}
System.out.println("-------------");
System.out.println();
}
public int Size(){
return numUsed;
}
}
thanks guys

It should be
while(index < numUsed)
If you use <=, you'll always access index 0 in an empty list, which will be null. Then when you try to call compareTo on it it will throw an NPE.
ALso, if null is a legal value to add to your list, you'll need to put a null check around the compareTo call and decide if null is alphabetically first or last.

You can use Arrays#sort to maintain order, its already available in library.
public boolean Insert(String value){
boolean result = false;
if (numUsed < length) {
storage[index] = value;
numUsed++;
result = true;
Arrays.sort(storage);
}
return result;
}

Here's why:
public boolean Insert(String value){
boolean result = false;
int index = 0;
if (numUsed < length) {
while (index <= numUsed) { // Here the first time numUsed = 0, index = 0, index <= numUsed;
int compare = storage[index].compareTo(value); // The first time, storage[0] == null; NullPointException is thrown
if (compare < 0)
index++;
}
moveItemsDown(index);
storage[index] = value;
numUsed++;
result = true;
}
return result;
}
Maybe change <= to < will do?

At the first run this line
int compare = storage[index].compareTo(value);
your are comparing storage[index] which value is null with value which is not null or empty
to enable a smooth running
replace
while(index =< numUsed) {
int compare = storage[index].compareTo(value);
if(compare < 0)
index++;
}
with
while(index < numUsed) {
int compare = storage[index].compareTo(value);
if(compare < 0)
index++;
}

Related

I am new with working with priority queues and have formatted this code wrong.What is the error in my Priority Queue code?

Error in the output box is :
Exception in thread "main" java.lang.NullPointerException: Cannot assign field "value" because "this.priorityqueue[this.count]" is null
at PriorityQueue.enQueue(PriorityQueue.java:16)
at Main.main(Main.java:4)
It is having operations like enqueue,dequeue,peek of Priority Queue.
Mostly showing the error in Enqueue part.
public class PQ {
public int value;
public int priority;
}
public class PriorityQueue {
public PQ[] priorityqueue;
public int count;
public PriorityQueue(int size){
this.count = 0;
this.priorityqueue = new PQ[size];
System.out.println("The Priority Queue is create with the size of :" + size);
}
public void enQueue(int element,int priority){
if (count == priorityqueue.length){
System.out.println("Priority Queue Overflow!");
}
else {
priorityqueue[count].value = element;
priorityqueue[count].priority = priority;
count++;
}
}
public int peekprio(){
int max = Integer.MIN_VALUE;
int index = -1;
for (int i = 0;i < count;i++){
if (priorityqueue[i].priority > max){
max = priorityqueue[i].priority;
index = i;
} else if (priorityqueue[i].priority == max && index > -1 && priorityqueue[index].value < priorityqueue[i].value){
index = i;
}
}
return index;
}
public int peek(){
if (count == 0){
System.out.println("Priority Queue Underflow!");
return -1;
}
else {
int index = -1;
int max = Integer.MIN_VALUE;
for (int i = 0; i < count; i++) {
if (priorityqueue[i].priority > max) {
max = priorityqueue[i].priority;
index = i;
}
else if (priorityqueue[i].priority == max && index > -1 && priorityqueue[index].value < priorityqueue[i].value){
index = i;
}
}
return priorityqueue[index].value;
}
}
public void deQueue(){
if (count == 0){
System.out.println("Priority Queue Underflow!");
}
else {
int element = priorityqueue[peekprio()].value;
int index = peekprio();
for (int i = index;i < count;i++){
priorityqueue[i] = priorityqueue[i + 1];
}
count--;
System.out.println("Value deQueued :" + element);
}
}
}
public class Main {
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue(5);
pq.enQueue(1,0);
pq.enQueue(3,3);
pq.enQueue(5,5);
pq.enQueue(2,2);
}
}
You are modeling your priority queue internally with an array of PQ objects, but you are missing the creation of the PQ object itself, so when you try to assign a value and priority to the queue it tries to set it to an object that does not exist yet.
When you do this: this.priorityqueue = new PQ[size]; on the constructor you are only creating the array, you still need to create the individual objects when you want to add them to the array.
To do that change this part on the enQueue method to add the new PQ():
else {
priorityqueue[count] = new PQ();
priorityqueue[count].value = element;
priorityqueue[count].priority = priority;
count++;
}
Ideally you'd want to create a constructor for that on the PQ class instead of setting the properties directly from outside.
Hope that helps.

BubbleDown function(min heap) not working

I have generated a minheap to this file but I think something I have missed but I can't identify what are the things I have missed. I have missed something on --private void bubbleDown() { }-- section but I can't find what are the things missed by me.
private int default_size = 100; // how big the heap should be
private T[] array;
private int size;
public Heap() {
#SuppressWarnings("unchecked")
T[] tmp = (T[]) (new Comparable[default_size]);
array = tmp;
size = 0;
}
boolean isRoot(int index) { return (index == 0); }
int leftChild(int index) { return 2 * index + 1; }
int parent(int index) { return (index - 1) / 2; }
int rightChild(int index) { return 2 * index + 2; }
T myParent(int index) { return array[parent(index)]; }
T myLeftChild(int index) { return array[leftChild(index)]; }
T myRightChild(int index) { return array[rightChild(index)]; }
boolean hasLeftChild(int i) { return leftChild(i) < size-1; }
boolean hasRightChild(int i){ return rightChild(i) < size-1; }
private void swap(int a, int b) {
T tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
public boolean isEmpty() { return (size == 0); }
/* adding heap */
public void add(T value) {
if(size == default_size) throw new IllegalStateException("Full array");
array[size++] = value;
bubbleUp();
}
public void bubbleUp() {
if(size == 0) throw new IllegalStateException("Shape error");
int index = size - 1;
while(!isRoot(index)) {
if(myParent(index).compareTo(array[index]) <= 0) break;
/* else part */
swap(parent(index), index);
index = parent(index);
}
}
/* removing */
public T remove() {
if(isEmpty()) return null;
T res = array[0]; /* root */
array[0] = array[size-1];
size --;
bubbleDown();
return res;
}
// i think this section having wrong something
private void bubbleDown() {
int parent = 0;
int leftChild = 2*parent + 1;
int rightChild = 2*parent + 2;
int choice = compareAndPick(leftChild, rightChild);
while (choice != -1)
{
swap(choice, parent);
parent = choice;
choice = compareAndPick(2*choice+1, 2*choice+2);
}
}
private int compareAndPick(int leftChild, int rightChild)
{
if (leftChild >= default_size || array[leftChild] == null) return -1;
if (array[leftChild].compareTo(array[rightChild]) <= 0 || (array[rightChild] == null))
return leftChild;
return rightChild;
}
public void show() {
for(int i=0; i<size; i++)
System.out.print(array[i] + " ");
System.out.println("=======");
}
public static void main(String [] args) {
Heap<Integer> heap = new Heap<Integer>();
for(int i=0; i<10; i++) {
heap.add((Integer)(int)(Math.random() * 100));
heap.show();
}
System.out.println("You should see sorted numbers");
while(!heap.isEmpty()) {
System.out.print(heap.remove());
System.out.print(" ");
heap.show();
}
System.out.println();
}
}
this code used generics and min heap functions.. i need to identify what is the wrong thing did by me on bubbleDown() section
Explanation
The bubbleDown() method is not a different way to insert a node and move it to it's correct position in the Heap. When bubbleDown() is called it's job is to Heapify the Binary Tree from any state. So your attempt to write the method just by changing the condition from the bubbleUp() method isn't gonna help you.
Extra
Here is a video that can give you the idea of how bubbleDown is supposed to work.

Building a Java Vector from Scratch [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Long story short, I am in a university Comp Sci class, and the Professor wants us to build a Vector but from scratch. Are their any good tutorials on the web for something like this? I did a Google search but nothing really came up.
EDIT
According to the document the teacher gave out the vector needs to be able to do the following:
append(Object element) – appending the element at the end of the vector
clear() – make the vector collection empty
contains(Object element) – check whether the vector contains the element
elementAt(int index) – access the element at the given index
indexOf(Object element) – find the index of the element
insertAt(int index, Object element) – insert the element at the given index
isEmpty() – check whether the vector is empty
removeAt(int index) – remove the element at the given index
remove(Object element) – remove the element from the vector
replace(int index, Object element) – replace the element at the given index with the given element
size() – get the number of elements in the current vector
ensureCapacity(int minCapacity) – make sure the vector gets at least the given capacity
clone() – returns a cloned copy of this vector
removeRange(int fromIndex, int toIndex) – removes from this vector all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive
toString() – returns a string representation of this vector, containing the String representation of each element
reverse() – reverse the elements in this vector
merge(MyVector vector2) – add all the elements in vector2 to the end of this vector
Additionally the class needs to implment Cloneable and be self expanding.
This is what I have come up with so far:
package collection;
public class MyVector implements Cloneable {
protected Object[] items;
protected int arraySize;
protected int maxCap;
public MyVector (int initialCapacity) {
super();
if (initialCapacity < 0) {
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
}
this.items = new Object[initialCapacity];
this.arraySize = 0;
this.maxCap = initialCapacity;
}
public MyVector() {
this(10);
}
public void append(Object element) {
int newArraySize = this.arraySize + 1;
if(this.maxCap == newArraySize) {
this.items = this.increaseCap(newArraySize);
this.items[this.arraySize] = element;
this.arraySize += 1;
//System.out.println(this.items[this.arraySize);
} else {
this.items[this.arraySize] = element;
this.arraySize +=1;
}
}
#Override
public String toString() {
String output = "[";
//output = this.items[0].toString();
for(int i = 0; i < this.arraySize; i++) {
output += this.items[i] + ", ";
}
output += "]";
return output;
}
public void clear() {
for(int i = 0; i < this.arraySize; i++) {
this.items[i] = null;
this.arraySize = 0;
}
}
public boolean contains(Object element) {
boolean doesContain = false;
for(int i = 0; i < this.arraySize; i++) {
if(element == this.items[i]) {
doesContain = true;
i = this.arraySize;
}
}
return doesContain;
}
public Object elementAt(int index) {
if(this.arraySize >= index) {
return this.items[index];
} else {
Object temp = null;
System.out.println("No index of " + index);
return temp;
}
}
public Object indexOf(Object element) {
Object index = "No value found";
for(int i = 0; i < this.arraySize; i++) {
if(element == this.items[i]) {
index = i;
break;
}
}
return index;
}
public boolean isEmpty() {
if(this.arraySize == 0) {
return true;
}
return false;
}
public void replace(int index, Object element) {
if(this.arraySize > index) {
this.items[index] = element;
} else {
System.out.println("No element at " + index);
}
}
public int size() {
return this.arraySize;
}
public void reverse() {
Object[] temp = new Object[this.items.length];
int j = this.arraySize;
for(int i = 0; i < this.arraySize; i++) {
temp[j] = this.items[i];
j--;
}
this.items = temp;
}
public void ensureCapacity(int minCapacity) {
if(minCapacity > this.items.length) {
this.items = this.increaseCap(minCapacity);
}
}
public Object[] increaseCap(int minCap) {
Object[] arr1 = new Object[minCap * 2];
for(int i = 0; i < minCap; i++) {
arr1[i] = this.items[i];
}
this.maxCap = this.maxCap * 2;
return arr1;
}
#Override
public Object clone() {
return this.items;
}
public boolean checkIndex(int index) {
boolean check = false;
if(index < this.arraySize) {
check = true;
}
return check;
}
public void removeAt(int index) {
if(true == this.checkIndex(index)) {
Object[] temp = new Object[this.arraySize - 1];
for(int j = 0; j < index; j++) {
temp[j] = this.items[j];
}
for(int j = index + 1; j < this.arraySize; j++) {
temp[j-1] = this.items[j];
}
this.items = temp;
this.arraySize = this.arraySize - 1;
}
}
public void insertAt(int index, Object element) {
if (this.checkIndex(index) == true) {
Object[] temp = new Object[this.arraySize];
for(int i = index; i < this.arraySize; i++) {
temp[i+1] = this.items[i];
}
this.items[index] = element;
for (int i = index + 1; i < this.arraySize; i++) {
this.items[i] = temp[i - 1];
}
this.arraySize = this.arraySize - 1;
}
}
public void remove(Object element) {
for(int i = 0; i < this.items.length; i++) {
if(this.items[i] == element) {
this.removeAt(i);
}
}
}
public void removeRange(int fromIndex, int toIndex) {
for(int i = fromIndex; i < toIndex; i++) {
this.removeAt(i);
}
}
public void merge(MyVector vector2) {
this.ensureCapacity(vector2.size() + this.arraySize);
for(int i = 0; i < vector2.size(); i++) {
this.append(vector2);
}
}
}
Assuming your assignment is replicating java.util.Vector, I would look at what a Vector is in order to replicate it:
Vector implements a dynamic array. It is similar to ArrayList, but
with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
You could attempt to use an ArrayList in a synchronous manner in order to replicate a Vector, but I'm sure there are much better solutions.

Java project - override toString() method and return a string

My class has begun working with queues and our instructions are to override the toString() method and return a string. Without using the default method, I do not know how to convert the array into the string form [element, element, element] for return. Here is my code so far. My queue works fine and I do not need any input on that...just the toString() method return.
package edu.ben.cis205;
public class MyQueue {
//Create array
public int[] array = new int[10];
//Create variables to track number of elements and pointer positions
private int first = 0;
private int last = 0;
private int numberOfElements = 0;
public int peek() {
//Returns first element in array
if (numberOfElements > 0)
return array[first];
else {
System.out.println("No integers in array.");
return 0;
}
}
public boolean add(int inputNumber) {
//Adds input to array
//Checks for room at back of array
if (numberOfElements < array.length && last < array.length) {
array[last] = inputNumber;
last++;
numberOfElements++;
return true;
//Checks for room at front of array
} else if (numberOfElements < array.length && last == array.length) {
last = 0;
array[last] = inputNumber;
last++;
numberOfElements++;
return true;
} else {
return false;
}
}
public int getSize() {
//Returns number of elements in array
return numberOfElements;
}
public boolean isFull() {
//Returns true if full
if (numberOfElements == array.length)
return true;
else
return false;
}
public boolean isEmpty() {
//Returns true if array is empty
if (numberOfElements == 0)
return true;
else
return false;
}
public int remove() {
//Removes element at front of array
//Checks for elements and moves pointer to next array position
if (numberOfElements > 0 && first < array.length) {
int returnValue = array[first];
first++;
numberOfElements--;
return returnValue;
//Checks for elements and moves pointer to front if at final position
} else if (numberOfElements > 0 && first == array.length) {
first = 0;
int returnValue = array[first];
first++;
numberOfElements--;
return returnValue;
//Returns an int value of 0 if array is empty
} else {
return 0;
}
}
public int getCapacity() {
//Returns array size
return array.length;
}
public int getRemainingCapacity() {
//Returns remaining spaces in array
return array.length - numberOfElements;
}
//ERROR IN METHOD
public String toString() {
//Int establishes where to start in the array.
int arrayPointer = first;
//New array established to put queue in order.
int stringArray[] = new int[numberOfElements];
//This code reconstructs the queue in the correct order
if (numberOfElements != 0) {
for (int i = 0; i < numberOfElements; i++) {
stringArray[i] = array[arrayPointer];
if (arrayPointer < (array.length - 1))
arrayPointer++;
else
arrayPointer = 0;
}
} else
return null;
// ??? Do not know how to change the new array (stored now in the correct order) into a String return...
}
}
Use
Arrays.toString(array[])
to get your array in [item1, item2, item3] representation

Convert a string like 2,4,5,6,7,8,10,12,14,15,16 to 2,4-8,10,12,14-16

I want to convert a string input like 2,3,6,7,8,10,12,14,15,16 to 2-3,6-8,10,12,14-16 using java
I tried using the below code
Vector ar=new Vector();
int lastadded=0;
String ht="";
String [] strarray=str.split(",");
strarray=sortArray(strarray);
Vector intarray=new Vector();
for(int i=0;i<strarray.length;i++)
{
int temp=1;
for(int j=1;j<=intarray.size();j++)
{
if(Integer.parseInt(strarray[i])==Integer.parseInt(intarray.get(j-1).toString()))
{
temp=0;
}
}
if(temp==1)
{
intarray.add(Integer.parseInt(strarray[i]));
ar.add(Integer.parseInt(strarray[i]));
}
}
ht="";
String strdemo="";
for(int i=0;i<intarray.size();i++)
{
if(ht=="")
{
ht=ar.get(i)+"";
lastadded=i;
}
else
{
strdemo=(String)ht;
if(strdemo.length()==ar.get(0).toString().length())
{
if(Integer.parseInt(strdemo.substring(0))==Integer.parseInt(ar.get(i).toString())-1)
{
strdemo=strdemo+"-"+ar.get(i);
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
else
{
strdemo=strdemo+","+ar.get(i);
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
}
else if(strdemo.length()==3)
{
strdemo=(String)ht;
if(Integer.parseInt(strdemo.substring(strdemo.length()-1,strdemo.length()))==Integer.parseInt(ar.get(i).toString())-1)
{
strdemo=strdemo.substring(0,strdemo.length()-2)+"-"+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
else
{
strdemo=strdemo+","+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
}//Else IF
else{
strdemo=(String)ht;
int de=1;
int ddd=lastadded;
if(ddd==Integer.parseInt(ar.get(i).toString())-1)
{
int lastaddedlen=(lastadded+"").length();
String symbol=strdemo.substring(strdemo.length()-lastaddedlen-1,strdemo.length()-lastaddedlen);
if(symbol.equalsIgnoreCase("-"))
strdemo=strdemo.substring(0,strdemo.length()-lastaddedlen-1)+"-"+Integer.parseInt(ar.get(i).toString());
else
strdemo=strdemo+"-"+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
else
{
strdemo=strdemo+","+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
}
}
}
Here sortArray function sorts the array descending and returns
protected static String[] sortArray(String ss[])
{
String temp;
for(int i=0;i<ss.length;i++)
{
for(int j=0;j<ss.length;j++)
{
if(Integer.parseInt(ss[i])<Integer.parseInt(ss[j]))
{
temp=ss[i];
ss[i]=ss[j];
ss[j]=temp;
}
}
}
return ss;
}
I am not getting consistant results for some inputs for example for the below case
2,3,6,7,8,10,12,14,15,16 it gives 2-3,6-8,10,12,14-16 (which is correct)
while for 2,4,5,6,7,8,10,12,14,15,16 it gives 2-8,10,12,14-16 (which actually should have been 2,4-8,10,12,14-16)
Where does the code go inconsistent is what I need to find out..
This is pretty ugly and verbose in Java, but here is a version. Note, it uses StringUtils from Spring at the very end for the trivial but also ugly process of converting a String collection to a comma delimited string.
The key is to use a separate class to model the numeric ranges. Let this class know how to turn itself into a String. Then you won't have so much logic around appending to a StringBuilder.
Also, try to think in terms of collections. This always makes things clearer. The pseudo-code is something like: String becomes List<Integer> becomes List<Range> and finally becomes String.
public class Ranges {
// A class that models a range of integers
public static class Range {
private int low;
private int high;
public Range(int low, int high) {
this.low = low;
this.high = high;
}
public int getHigh() {
return high;
}
public void setHigh(int high) {
this.high = high;
}
#Override
public String toString() {
return (low == high) ? String.valueOf(low) : String.format("%d-%d", low, high);
}
}
public static void main(String[] args) {
String input = "2,3,6,7,8,10,12,14,15,16";
// Turn input string into a sorted list of integers
List<Integer> inputNumbers = new ArrayList<Integer>();
for (String num : input.split(",")) {
inputNumbers.add(Integer.parseInt(num));
}
Collections.sort(inputNumbers);
// Flatten list of integers into a (shorter) list of Ranges
Range thisRange = null; // the current range being built
List<Range> ranges = new ArrayList<Range>();
for (Integer number : inputNumbers) {
if (thisRange != null && number <= thisRange.getHigh() + 1) {
// if we are already building a range (not null) && this new number is
// the old high end of the range + 1, change the high number.
thisRange.setHigh(number);
} else {
// create a new range and add it to the list being built
thisRange = new Range(number, number);
ranges.add(thisRange);
}
}
// Join List<String> into a single String
String result = StringUtils.collectionToCommaDelimitedString(ranges);
System.out.println("result = " + result);
}
}
Here is my implementation. Hope this help.
You have to pass these values
e.g int[] a = {2,3,4,5,6,7,8,10,12, 14,15,16,18,19,21,22,26};
to the following method.
public List<String> listIntRange(int[] values)
{
List<String> intRangeList = new ArrayList<String>();
int first = 0;
int current = 0;
int prev = 0;
int count = 0;
if (values == null || values.length < 1)
return intRangeList;
first = prev = values[0];
int index = 1;
boolean range = false;
for(index = 1; index < values.length; index++)
{
current = values[index];
if(current - prev == 1)
{
range = true;
prev = current;
continue;
}
if(range == true)
{
intRangeList.add(first + "-" + prev);
}
else
{
intRangeList.add("" + first);
}
first = current;
prev = current;
range = false;
}
if(range == true)
{
intRangeList.add(first + "-" + current);
}
else
{
intRangeList.add("" + current);
}
return intRangeList;
}
Output is as follows, when print out the values from intRangeList:
2-8,10,12,14-16,18-19,21-22,26,
Please ignore last comma ','.

Categories

Resources