Chutes and Ladder determine if cell is empty [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i am making a Chutes Ladder program and needed another way to determine if the Cell is a empty space beside the 3 spaces i am using. Is there any other way to determine the Cell is empty beside if the cell have 3 spaces.
Cell.java:
public class Cell {
String text;
int number;
public Cell() {}
public Cell( String r ) {
text = r;
}
public Cell( int m, String r ) {
text = r;
number = m;
}
public String getText() {
return text;
}
public void setText( String x ) {
text = x;
}
public int getNumber() {
return number;
}
public void setText( int x ) {
number = x;
}
public boolean isLadder() {
return (text.equals( "L" ));
}
public boolean isChute() {
return (text.equals( "C" ));
}
public boolean isEmpty() {
return text.equals( " " );
}
public String toString() {
String s = "";
if ( isChute() )
s = s + text + Math.abs( number );
else if ( isLadder() )
s = s + text + number;
else if ( isEmpty() )
s = s + " ";
return s;
}
}
ChutesAndLadders.java
public class ChutesAndLadders {
Cell[] board;
Random ran = new Random();
public ChutesAndLadders() {}
public ChutesAndLadders( int numChutes, int numLadders ) {
board = new Cell[100];
for ( int i = 0; i < board.length; i++ ) {
board[i] = new Cell( " " );
}
chutes( numChutes );
ladders( numLadders );
}
public void setBoard( Cell[] board ) {
this.board = board;
}
public Cell[] getBoard() {
return board;
}
public void makeChutes( int x ) {
for ( int i = 0; i < x; i++ ) {
int temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( -10, "C" );
else
i--;
}
}
public void makeLadders( int y ) {
for ( int i = 0; i < y; i++ ) {
int temp = ran.nextInt( board.length );
if ( temp < 10 )
temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( 10, "L" );
else
i--;
}
}
public void chutes( int x ) {
for ( int i = 0; i < x; i++ ) {
int temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( -10, "C" );
else
i--;
}
}
public void ladders( int y ) {
for ( int i = 0; i < y; i++ ) {
int temp = ran.nextInt( board.length );
if ( temp < 10 )
temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( 10, "L" );
else
i--;
}
}
public int addToMove( String a ) {
if ( a.equals( "C10" ) ) {
int n = Integer.parseInt( a.substring( 1 ) );
return n;
}
if ( a.equals( "L10" ) ) {
int n = Integer.parseInt( a.substring( 1 ) );
return n * -1;
}
else
return 0;
}
public void printBoard() {
int counter = 0;
for ( int i = 0; i < board.length; i++ ) {
counter++;
System.out.print( "|" + board[i] );
if ( counter == 10 ) {
System.out.print( "|" + "\n" );
counter = 0;
}
}
}
}
test.java:
public class test {
public static void main( String[] args ) {
ChutesAndLadders cl = new ChutesAndLadders( 10, 10 );
cl.makeChutes( 5 );
cl.makeLadders( 5 );
int chutes = 0, ladders = 0;
for ( Cell cell : cl.getBoard() ) {
if ( cell.isLadder() )
ladders++;
else if ( cell.isChute() )
chutes++;
}
System.out.println( "Board has " + chutes + " chutes and " + ladders + " ladders" );
cl.printBoard();
}
}

public boolean isEmpty() {
return !(isLadder() && isChute());
}

Related

Java - Compressed String

Given a string, I want to compress the string based on each character's number of consecutive occurrences next to it. For example, let's say we have a string like "abaasass". 'a' occurs one time, 'b' occurs one time, 'a' occurs two times consecutively, 's' occurs one time, 'a' occurs one time, and 's' occurs two times consecutively. The method should then return a string like "aba2sas2".
This is what I have so far:
public static String compressedString(String message) {
StringBuilder compressedString = new StringBuilder();
int total = 0;
for (int i = 0; i < message.length() - 1; i++){
if (message.charAt(i) == message.charAt(i+1)){
total += 2;
compressedString.append(message.charAt(i)).append(total);
}
else {
compressedString.append(message.charAt(i));
}
total = 0;
}
return compressedString.toString();
}
It instead returns: "aba2asas2" which is somewhat close, anyone sees the issue?
public static String compressedString(String message) {
StringBuilder compressedString = new StringBuilder();
int total = 1;
for (int i = 0; i < message.length() - 1; i++){
if (message.charAt(i) == message.charAt(i+1)){
total++;
}
else if(total==1){
compressedString.append(message.charAt(i));
}
else
{
compressedString.append(message.charAt(i)).append(total);
total = 1;
}
}
if(message.charAt(message.length()-2) != message.charAt(message.length()-1)
compressedString.append(message.charAt(message.length()-1));
else
compressedString.append(message.charAt(message.length()-1)).append(total);
return compressedString.toString();
}
public static String compressedString(String message)
{
String result = "" ;
for ( int i = 0, t = message.length() - 1 ; i < t ; )
{
String letter = String.valueOf( message.charAt(i) ) ;
int currentChain = consec( i, message ) ;
result += ( currentChain > 1 ? ( letter + currentChain ) : letter ) ;
i += currentChain ;
}
return result ;
}
private static int consec( int startIndex, String text )
{
int chain = 1 ;
for( int i = startIndex ; i < text.length() - 1 ; ++i )
{
if( text.charAt(i) == text.charAt(i+1) )
chain++ ;
else
break ;
}
return chain ;
}
This is your solution for your question
static void compressedString(String str) {
int n = str.length();
for (int i = 0; i < n; i++) {
// Count occurrences of current character
int count = 1;
while (i < n - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
if (count == 1) {
System.out.print(str.charAt(i));
} else {
System.out.print(str.charAt(i));
System.out.print(count);
}
}
}
public static void main(String[] args) {
String str = "abaasass";
compressedString(str);
}

How to run this portion of code?

i found this snippet of code on stack and i wanted to try it out on my machine but it keeps giving me an error of
Main method not found in class Main, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
can anyone help me figure out what to do?
This is the portion of the code i wanted to try on my machine
public static void main(String[] args) {
}
public int parse(String input) {
Scanner scanner = new Scanner(input);
return consumeLine(scanner);
}
public int consumeLine(Scanner scanner) {
if( scanner.hasNext("(") ) {
return consumeExpression(scanner);
} else if( scanner.hasNext("IF") ) {
return consumeIf(scanner);
}
return 0;
}
public int consumeExpression(Scanner scanner) {
scanner.next("(");
int a = scanner.nextInt();
int b = scanner.nextInt();
String op = scanner.next("[+-/*]");
scanner.next(")");
if( "+".equals(op) ) {
return a + b;
} else if( "-".equals(op) ) {
return a - b;
}
throw new RuntimeException("parsing error");
}
public int consumeIf(Scanner scanner) {
scanner.next("IF");
int exp1 = consumeExpression(scanner);
int exp2 = consumeExpression(scanner);
int exp3 = consumeExpression(scanner);
int exp4 = consumeExpression(scanner);
if( exp1 < 0 ) {
return exp2;
} else if( exp1 == 0 ) {
return exp3;
}
throw new RuntimeException("should not be here (TM)");
}
Try this.
public int parse(String input) {
Scanner scanner = new Scanner(input);
return consumeLine(scanner);
}
public int consumeLine(Scanner scanner) {
if( scanner.hasNext("\\(") ) {
return consumeExpression(scanner);
} else if( scanner.hasNext("IF") ) {
return consumeIf(scanner);
}
return 0;
}
public int consumeExpression(Scanner scanner) {
scanner.next("\\(");
int a = scanner.nextInt();
int b = scanner.nextInt();
String op = scanner.next("[+-/*]");
scanner.next("\\)");
if( "+".equals(op) ) {
return a + b;
} else if( "-".equals(op) ) {
return a - b;
}
throw new RuntimeException("parsing error");
}
public int consumeIf(Scanner scanner) {
scanner.next("IF");
int exp1 = consumeExpression(scanner);
int exp2 = consumeExpression(scanner);
int exp3 = consumeExpression(scanner);
int exp4 = consumeExpression(scanner);
if( exp1 < 0 ) {
return exp2;
} else if( exp1 == 0 ) {
return exp3;
}
throw new RuntimeException("should not be here (TM)");
}
sample output
System.out.println(parse(" IF ( 0 0 - ) ( 1 1 + ) ( 2 2 + ) ( 3 3 + )"));
// -> 4

need quick help in Java Program Lab

i have a lab for my java class. I have everything except cannot get the average method to work properly. Whenever i run the program, the average is calculated from the random values and not the one updated.
package ArrayKeyAccess;
/**
* Class Definition for Data Element
* Minimal Definition -- No Error Checking
* Instructional Model -- Conceptual Emphasis
*/
public class Data
{
private int studentID;
private int test1;
private int test2;
private int test3;
private int average;
private String letterGrade;
private static int nextSID = 99; //cheap sequence number approach
private static int getNextSID()
{
return ++nextSID;
}//getNextKey
public Data(int n) //no error checking
{
this.setStudentID(getNextSID());
this.setTest1(n);
this.setTest2(n);
this.setTest3(n);
}//Data constructor
public Data(int k, int n) //no uniqueness checking
{
this.setStudentID(k);
this.setTest1(n);
this.setTest2(n);
this.setTest3(n);
}//Data constructor
public Data( Data d ) //Copy Constructor
{ //required for Composition
this.setStudentID(d.getStudentID());
this.setTest1(d.getTest1());
this.setTest2(d.getTest2());
this.setTest3(d.getTest3());
this.calculateAverage(getTest1(), getTest2(), getTest3());
this.determineLetterGrade(letterGrade);
}//copy constructor
public Data copy() //Copy Object
{ //required for Compostion
return new Data(this);
}//copy object
public String toString()
{
return "Student ID: " + this.getStudentID() + '\n' +
"Test 1: " + this.getTest1() + '\n' +
"Test 2: " + this.getTest2() + '\n' +
"Test 3: " + this.getTest3() + '\n' +
"Average: " + this.getAverage() + '\n' +
"Letter Grade: " + this.getLetterGrade() + '\n';
}//toString
public void setStudentID (int n) //no error checking
{
studentID = n;
}
public int getStudentID()
{
return studentID;
}
//----------------------Test1---------------------------------------
public void setTest1(int n) //no validity checking
{
test1 = n;
}
public int getTest1()
{
return test1;
}
//----------------------Test2---------------------------------------
public void setTest2(int n) //no validity checking
{
test2 = n;
}
public int getTest2()
{
return test2;
}
//----------------------Test3---------------------------------------
public void setTest3(int n) //no validity checking
{
test3 = n;
}
public int getTest3()
{
return test3;
}
//---------------calculate average score-----------------------------
public void calculateAverage(int test1, int test2, int test3) //set
{
this.test1 = getTest1();
average = (getTest1() + getTest1() + getTest3()) / 3;
}
//----------------determine letter grade------------------------------
public void determineLetterGrade(String letterGrade)
{
if(average >= 90)
letterGrade = "A";
else if(average >= 80)
letterGrade = "B";
else if(average >= 70)
letterGrade = "C";
else if(average >= 60)
letterGrade = "D";
else
letterGrade = "F";
this.letterGrade = letterGrade;
}
//getAverageScore
public int getAverage() //get
{
return average;
}
//getLetterGrade
public String getLetterGrade()
{
return letterGrade;
}
}//class Data
ProgramTest
UnsortedArray s = new UnsortedArray(10);
int score;
//add 10 data elements
for( int i=1; i<=10; i++ )
{
score = 50 + (int)(Math.random()*50)+1;
s.insert( new Data(score) );
}
System.out.println("------------------TEST 1----------------------");
//update test 1
s.updateTest1(100,44);
s.updateTest1(101,89);
s.updateTest1(102,80);
s.updateTest1(103,95);
s.updateTest1(104,65);
s.updateTest1(105,74);
s.updateTest1(106,69);
s.updateTest1(107,56);
s.updateTest1(108,88);
s.updateTest1(109,99);
s.showList();
The Unsorted Array Class ( i forgot to attach before)
package ArrayKeyAccess;
/**
* Class Definition for Unsorted Array
* Minimal Basic Methods
* Implements Insert, Fetch, Update, Delete
* Conceptual Instructional Model
*/
public class UnsortedArray
{
private int next; //next insert position
private int size; //array capacity
private Data[] a; //reference for container of
//data elements
public UnsortedArray(int n) //no error checking
{
next = 0;
size = n;
a = new Data[size];
}//constructor
public boolean insert( Data newNode )
{
if( next >= size ) //array is full
return false;
//insert copy in next position
a[next] = new Data( newNode );
++next;
return true;
}//insert
public Data fetch( int targetKey )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return null;
else //node was found
return a[i].copy(); //return a copy
}//fetch
//Update data element field in the container
public boolean updateTest1( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest1( val );
return true;
}
}//updateTest1
public boolean updateTest2( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest2( val );
return true;
}
}//updateTest2
public boolean updateTest3( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest3( val );
return true;
}
}//updateTest1
//overload update method
//assumes record was fetched and
//value was modified and now is
//to be "reinserted".
public boolean update( int targetKey, Data updNode )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i] = updNode.copy(); //assign copy
return true; //preserve Composition
}
}//update
public boolean delete( int targetKey )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i] = a[next-1]; //move last node to deleted position
//"deleted" node has no reference
a[next-1] = null; //new next available position
--next; //reset insert position
return true;
}
}//delete
public void showList() //List the nodes
{
for(int i=0; i<next; i++)
System.out.println( a[i] );
}//showList
}//class UnsortedArray
Well, there's two problems.
First, you're adding getTest1() twice. That's worth fixing in its own right.
The second problem is that you're going to run into integer division - simply because all four of your values are going to be ints, you won't get any floating-point values (or a "true" average).
What you want to do is change the type of average to double, then change your divdend into a floating point number, as such:
average = (getTest1() + getTest2() + getTest3()) / 3.0;
It may be because you add test1 twice.
average = (getTest1() + getTest1() + getTest3()) / 3;
i figured it out, these are my changes, no getters for calculateAverage or letterGrade
public int calculateAverage() //set
{
average = (this.getTest1() + this.getTest2() + this.getTest3()) / 3;
return average;
}
public String letterGrade()
{
if(this.average >= 90)
letterGrade = "A";
else if(this.average >= 80)
letterGrade = "B";
else if(this.average >= 70)
letterGrade = "C";
else if(this.average >= 60)
letterGrade = "D";
else
letterGrade = "F";
return letterGrade;
}
public String toString()
{
return "Student ID: " + this.getStudentID() + '\n' +
"Test 1: " + this.getTest1() + '\n' +
"Test 2: " + this.getTest2() + '\n' +
"Test 3: " + this.getTest3() + '\n' +
"Average: " + calculateAverage() + '\n' +
"Letter Grade: " + this.letterGrade() + '\n';
}//toString

Very Basic Java: For-Loop in Java method won't run

I've never asked a question on this before but I'd appreciate any help anyone can provide. I'm currently learning the fundamentals of Java so this is more than likely a very basic problem. When I call this method, nothing seems to happen and I can't figure out why. I could just change it to type void and use system.print but I'd rather not, anyhow here's the code:
public double calcTotal()
{
double total = 0.00;
for (int i = 0; i < jSongs.size(); i++)
{
total += jSongs.get(i).getPrice();
}
return total;
}
I think it would be easier if I just showed you guys the whole lot, this is the app that's calling the methods to test them:
public class JukeboxApp {
public static void main(String[] args) {
Song s1 = new Song("Metallica", "The Unforgiven", 1.25, 6.23);
Song s2 = new Song("Test Artist 2", "Test Title 2", 4.00, 3.40);
Song s3 = new Song("Test Artist 3", "Test Title 3", 6.00, 2.50);
Jukebox jb = new Jukebox();
jb.addSong(s1);
jb.addSong(s2);
jb.addSong(s3);
jb.displaySongs();
jb.removeSong("The Unforgiven");
jb.searchSong("Test Title 2");
jb.calcTotal();
}
}
Here is the jukebox class, which I'm sure is full of mistakes:
import java.util.ArrayList;
public class Jukebox {
private String name;
private ArrayList<Song> jSongs;
public Jukebox()
{
name = "Primary Jukebox";
jSongs = new ArrayList<Song>();
}
public String getName()
{
return name;
}
public double calcTotal()
{
double total = 0.00;
for (int i = 0; i < jSongs.size(); i++)
{
total += jSongs.get(i).getPrice();
}
return total;
}
public void searchSong(String sTitle)
{
boolean check = false;
if ( jSongs.size() == 0 ) {
System.out.println("The are no songs in the list.");
check = true;
} else if ( jSongs.size() != 0 ) {
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getTitle().equals(sTitle) == true ) {
check = true;
System.out.println(jSongs.get(i));
}
}
}
if ( check == false ) {
System.out.println("The searched song could not be found.");
}
}
public String searchArtist(String sArtist)
{
int countMatch = 0;
for (int i = 0; i < jSongs.size(); i++) {
if ( jSongs.get(i).getArtist().equals(sArtist) ) {
countMatch++;
return jSongs.get(i).getTitle();
} else if ( countMatch == 0 ) {
return "The requested artist could not be found.";
}
}
return "If you would like to search for another artist, please enter the corresponding number.";
}
public void addSong(Song s1)
{
boolean check = false;
if ( jSongs.size() == 0 ) {
System.out.println("Your song will be added to the list.");
jSongs.add(s1);
return;
} else if ( jSongs.size() != 0 ) {
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i) == s1 ) {
check = true;
}
}
}
if ( check == false ) {
System.out.println("Your song will be added to the list.");
jSongs.add(s1);
} else if ( check == true ) {
System.out.println("Your song is already in the list.");
}
}
public void removeSong(String title)
{
boolean check = false;
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getTitle().equals(title) ) {
jSongs.remove(i);
check = true;
}
}
System.out.println(check);
}
public void displaySongs()
{
for ( int i = 0; i < jSongs.size(); i++ ) {
System.out.println(jSongs.get(i));
}
}
public Song showMostExpensive()
{
double price = 0.00;
Song mostESong = new Song();
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getPrice() > price ) {
price = jSongs.get(i).getPrice();
mostESong = jSongs.get(i);
}
}
return mostESong;
}
public Song showShortest()
{
double length = 500.00;
Song shortest = new Song();
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getLength() < length ) {
length = jSongs.get(i).getLength();
shortest = jSongs.get(i);
}
}
return shortest;
}
public Song mostPlayed()
{
int count = 0;
Song mostPSong = new Song();
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getCount() > count ) {
count = jSongs.get(i).getCount();
mostPSong = jSongs.get(i);
}
}
return mostPSong;
}
}
And here is the class that creates the song objects:
public class Song {
private String artist;
private String title;
private double price;
private int playCount;
private double length;
public Song()
{
artist = "unknown";
title = "unknown";
price = 0.00;
length = 0.00;
playCount = 0;
}
public Song(String artist, String title, double price, double length)
{
this.artist = artist;
this.title = title;
this.price = price;
this.length = length;
playCount = 0;
}
public String getArtist()
{
return artist;
}
public String getTitle()
{
return title;
}
public double getPrice()
{
return price;
}
public int getCount()
{
return playCount;
}
public double getLength()
{
return length;
}
public void changePrice(double newPrice)
{
price = newPrice;
}
public void playSong()
{
playCount++;
System.out.println(title + " is now playing." + "\n" + toString());
}
public String toString()
{
return artist + "\n"
+ title + "\n"
+ price + "\n"
+ length;
}
}
Your description makes me think that you are calling your method like so
calcTotal();
instead of actually using the value returned by the method
double total = calcTotal();
System.out.println(total);
Your code seem to be good. Probably the function for addSong could be easier. But the problem is that you're not printing the result of the function calcTotal().

method to insert/append elements in array list

I am not sure if I am implementing the insert or append correctly but I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
-1 at AListInt.insert(AListInt.java:81) // listArray[i+1] = listArray[i]; at ListTest.main(ListTest.java:52) // list.insert(i);
Also I cannot use java.util.ArrayList
Here is the code and classes for it:
class:
public class AListInt {
int [] listArray;
int listSize;
int curr; // current position
AListInt() {
listSize = 0;
// note that curr = -1 when listSize = 0
curr = -1;
listArray = new int [2];
}
public int getValue () throws DSException {
return listArray[curr];
//returns the value of current position
//throw exception when there are no elements in the list
}
public int length() {
return listSize;
//return # of elements in the list
}
public int currPos() {
return curr;
//return current position.
}
public void moveToPos ( int pos ) throws DSException {
curr = pos;
//move the current position to pos
//throw exception if pos is not a valid position
}
public void moveToStart () throws DSException {
curr = 0;
//move the current position to the start of the list
//throw exception if no elements are in the list
}
public void moveToEnd () throws DSException {
curr = listSize;
//move the current position to the end of the list
//throw exception if no elements are in the list
}
public void prev () throws DSException {
if(curr != 0)
{
curr--;
}
//move current position to the previous element
//throws exception if the previous position is not legal or
// if there are no elements in the list
}
public void next () throws DSException {
if(curr < listSize)
{
curr++;
}
//move current position to the next element
//throws exception if the next position is not legal or
// if there are no elements in the list
}
public void insert ( int item ) {
for(int i = listSize-1; i >= curr; i++)
{
listArray[i+1] = listArray[i];
}
listArray[curr] = item;
listSize ++;
int[]temp = new int[listArray.length*2];
for(int i = 0; i< listSize; i++)
{
temp[i] = listArray[i];
}
listArray = temp;
// inserts item to the current position
// if not enough memory, double the size of listArray
}
public void append ( int item ) {
listArray[listSize++] = item;
int[]temp = new int[listArray.length*2];
for(int i = 0; i< listSize; i++)
{
temp[i] = listArray[i];
listArray = temp;
}
// inserts item to the end of the list
// if not enough memory, double the size of listArray
}
public int remove () throws DSException {
if((curr < 0)||(curr > listSize))
{
return -1;
}
int item;
item = listArray[curr];
for(int i = curr; i < listSize - 1; i++)
{
listArray[i] = listArray[i+1];
}
listSize --;
return item;
//removes the element at the current position
//returns the removed element
}
public void clear() {
listSize = 0;
curr = -1;
//reset size. Set current position to be -1
}
public boolean find ( int val ) {
for(int i = 0; i > listSize; i ++)
{
if(listArray[i] == val)
{
return true;
}
}
return false;
//searches for val in the list
//returns true if found and false if not found
}
public void print () {
System.out.print("<");
for(int i = 0; i < listSize; i++)
{
System.out.print(listArray[i]);
if(listSize == -1)
{
System.out.print("-1");
}
}
System.out.print(">");
//outprint the list
}
}
exception:
public class DSException extends Exception {
public DSException() {
}
public DSException(String msg) {
super(msg);
}
}
main:
public class ListTest {
public static void main ( String[] args ) {
try {
AListInt list = new AListInt();
list.print();
// test length()
System.out.println ( list.length() );
// test currPos()
System.out.println ( list.currPos() );
// insert some numbers
for ( int i = 0; i < 4; i++ ) {
list.append(i);
list.print();
}
list.moveToPos(0);
list.print();
list.moveToEnd();
list.print();
// test getValue()
System.out.println ( list.getValue() );
System.out.println ( "remove: " + list.remove() );
list.print();
list.moveToStart();
list.print();
System.out.println ( "remove: " + list.remove() );
list.print();
list.clear();
list.print();
list.clear();
list.print();
System.out.println ( "find 0 : " + list.find ( 0 ) );
for ( int i = 0; i < 4; i++ ) {
list.insert(i);
list.print();
}
for ( int i = 0; i < 5; i++ ) {
System.out.println ( "find " + i + " : " + list.find ( i ) );
list.print();
}
list.next();
list.print();
list.insert ( -9 );
list.print();
list.append ( -2 );
list.print();
list.moveToEnd();
list.insert ( -1 );
list.print();
System.out.println ( "remove: " + list.remove() );
list.print();
} catch ( DSException e ) {
e.printStackTrace();
}
}
}
You reading outside the Array. in
for(int i = listSize-1; i >= curr; i++)
{
listArray[i+1] = listArray[i];
}
if i = listSize -1, then listArray[i+1] is listArray[listSize], which is out of bounds, since arrays go from 0 to length -1
EDIT:
But since listArray has an initial size of 2, and you double the size at each insert you get away with that. However, at the first insert curr is -1, and since the termination is i >= curr, the loop will be entered and you will read listArray[-1] (Out of bounds)
it's gotta be listArray[i]=listArray[i-1]
because you are shifting the position of listArray[i-1] to the position of listArray[i]

Categories

Resources