Can't get array to copy with written copy() method - java

So the premise of this code is to build apon it as we learn different things like nodes and such through out the semester.
Currently, in this version of the code, I need to replace anything that uses 0 to signify the end of the collection of numbers. So let's say if array A has [1,2,5,4,0], 0 would be the indicator that we are at the end of the array.
Now in this version, we have to use a counter(a.k.a howmany in this code) to signify the end of the collection of numbers.
Currently, with this code, I'm getting out of bounds errors and I'm not fully understanding why. I'm getting it in the copy()method and also the omit() method.
Here is the main class:
import java.util.*;
public class Intcoll2client {
public static final int SENTINEL = 0;
public static void main(String[] args) {
int value;
Scanner keyboard = new Scanner(System.in);
Intcoll2 P = new Intcoll2(), N = new Intcoll2(), L = new Intcoll2(5);
System.out.println("Enter an integer to be inserted or 0 to quit:");
value = keyboard.nextInt();
while (value != SENTINEL) {
if (value > 0) {
P.insert(value);
L.insert(value);
} else {
N.insert(-value);
L.omit(-value);
}
// L.arraySize();
System.out.println("Enter next integer to be inserted or 0 to quit:");
value = keyboard.nextInt();
}
System.out.println("\nThe values in collection P are:");
P.print();
System.out.println("\nThe values in collection N are:");
N.print();
System.out.println("\nThe values in collection L are:");
L.print();
if (P.equals(N)) {
System.out.println("\nP and N are equal.");
} else {
System.out.println("\nP and N are NOT equal.");
}
Intcoll2 A = new Intcoll2();
A.copy(L);
System.out.println("\nThe values in the copy of L are:\n");
A.print();
}
}
Here is the class with all of the methods I'm working with:
import java.util.*;
public class Intcoll2 {
private int[] c;
private int howmany;
/**
* Creates a new array c with the size 500
*/
public Intcoll2() {
c = new int[500];
howmany = 0;
}
/**
* Creates a new array with the size i
*
* #param i positive integer
*/
public Intcoll2(int i) {
c = new int[i];
howmany = 0;
}
/**
* Pre-condition: Takes in an object of Intcoll2 Post-condition: If obj does
* not equal c, create a new array and copy all elements from c to obj
*
* #param obj
*/
public void copy(Intcoll2 obj) {
if (this != obj) {
c = new int[obj.c.length];
int j = 0;
while (obj.c[j] != 0) {
c[j] = obj.c[j];
j++;
}
c[j] = 0;
}
}
/**
* Pre-condition: Take in positive integer i
* Post-condition: Return true if
* i is greater than 0 and i is equal to element in array. Otherwise, false
*
* #param i positive integer
* #return
*/
public boolean belongs(int i) {
int j = 0;
while ((c[j] != 0) && (c[j] != i)) {
j++;
}
return ((i > 0) && (c[j] == i));
}
/**
* Pre-condition: Take in a positive integer i
* Post-condition: If i is greater than 0 and is not in the current collection, insert
* into collection. Otherwise, do nothing. If current array is too small to
* insert new integer, create new array double the size and copy all
* elements into new array. Redirect new array to old reference variable.
*
* #param i positive integer to insert in object
*/
public void insert(int i) {
if (i > 0) {
int j = 0;
while ((j < howmany) && (c[j] != 0)) {
j++;
}
if (j == howmany) {
if (j == c.length) {
int[] newC = new int[c.length * 2];
for (int index = 0; index < c.length; index++) {
newC[index] = c[index];
}
c = newC;
}
c[j] = i;
howmany++;
}
}
}
public void arraySize(){
int size = c.length;
System.out.println("Howmany: " + howmany);
System.out.println("Size of L: " + size);
}
/**
* if i is greater than 0, then scan array. If i is found in the array, take
* away and move any element after the index to fill in the 0 space
*
* #param i positive integer
*/
public void omit(int i) {
if (i > 0) {
int j = 0;
while ((c[j] != 0) && (c[j] != i)) {
j++;
}
if (c[j] == i) {
int k = j + 1;
while (c[k] != 0) {
k++;
}
c[j] = c[k - 1];
c[k - 1] = 0;
}
}
}
/**
* Returns number of integers in a collection until loop hits 0
*
* #return howmany
*/
public int get_howmany() {
return howmany;
}
/**
* Prints out the entire collection until it reaches an element of 0
*/
public void print() {
int j = 0;
System.out.println();
while (j < howmany) {
System.out.println(c[j]);
j++;
}
}
/**
* Pre-condition: Takes in an existing object of Intcoll1 Post-condition:
* Compares two objects, if both collections are equal, return true.
* Otherwise, false.
*
* #param obj object containing an array
* #return result
*/
public boolean equals(Intcoll2 obj) {
int j = 0;
boolean result = true;
while ((c[j] != 0) && result) {
result = obj.belongs(c[j]);
j++;
}
j = 0;
while ((obj.c[j] != 0) && result) {
result = belongs(obj.c[j]);
j++;
}
return result;
}
}
Any type of input or help would be greatly appreciated!

Related

Solving puzzle NxN with IDA* and Manhattan

Given the game http://mypuzzle.org/sliding, which starts with square grid containing tiles with numbers
from 1 to N and one empty block represented with X.The goal is to put the tiles according to their numbers.The
moving is done by moving a tile from left,right,top,bottom to the position of the empty tile.I have to solve this problem using IDA* and Manhattan approach
My goal is to output
1.On the first row output the length of the "optimal" path from the start to the destination state
2.The steps which solve the problem in order to reach our final state. The steps are left,right,up,down
Here is my current code working on solution for 3x3 :
/**
*
* Problem Name: Eight Algorithm: IDA* (Iterative deepening A*) using Manhattan Distance Heuristic
* Source: AI: A Modern Approach
*
*/
// Beware my messy code follows!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
*
*
*
* #class used to keep State Machine of Eight Puzzle with f,g,h along with board
*
*/
class StateEightPuzzle {
private int f, g, h;
private StringBuilder stateofBoard;
private int xEmptyTile, yEmptyTile;
private int pre;
public void setStateofBoard(StringBuilder stateofBoard) {
this.stateofBoard = stateofBoard;
}
public void setPre(int pre) {
this.pre = pre;
}
public void setXEmptyTile(int xEmptyTile) {
this.xEmptyTile = xEmptyTile;
}
public void setYEmptyTile(int yEmptyTile) {
this.yEmptyTile = yEmptyTile;
}
public void setF(int f) {
this.f = f;
}
public void setG(int g) {
this.g = g;
}
public void setH(int h) {
this.h = h;
}
public int getPre() {
return pre;
}
public int getXEmptyTile() {
return xEmptyTile;
}
public int getYEmptyTile() {
return yEmptyTile;
}
public StringBuilder getStateofBoard() {
return stateofBoard;
}
public int getF() {
return f;
}
public int getG() {
return g;
}
public int getH() {
return h;
}
}
/**
*
* #class used as return type where flimit is used as current flimit and sol indicates whether
* solution is found
*
*/
class ReturnResult {
int flimit;
StateEightPuzzle sol;
}
public class Main {
/**
* #param args
*/
static int flag;
static int[] tracePath;
static private int ROWSIZE = 3;
static private int BOARDSIZE = 9;
/*
*
* function used to see whether the current Eight puzzle can be solvable that is can we subjugate
* our beloved using inversion permutation
*/
public static boolean isSolvable(String dpState) {
int inversion = 0;
for (int i = 0; i < BOARDSIZE; i++)
for (int j = i + 1; j < BOARDSIZE; j++)
if (dpState.charAt(i) > '0' && dpState.charAt(j) > '0'
&& dpState.charAt(i) > dpState.charAt(j))
inversion++;
if (inversion % 2 == 1)
return false;
else
return true;
}
/*
*
* getManhattanDistance returns Manhattan distance between current Node of Eight puzzle State
* Machine and Goal State(Final Destination)
*/
public static int getManhattanDistance(StringBuilder knightBoard) {
int manhattanVal = 0;
for (int i = 0; i < ROWSIZE; i++)
for (int j = 0; j < ROWSIZE; j++) {
int pos = i * ROWSIZE + j;
int val = (knightBoard.charAt(pos) - '0') - 1;
if (val == -1)
continue;
manhattanVal = manhattanVal + Math.abs((val / ROWSIZE) - i) + Math.abs((val % ROWSIZE) - j);
}
return manhattanVal;
}
/**
*
*
*
* #param stat
* #param x
* #param y
* #return
*
* function used to generate next State Machine of Eight Puzzle aka Successor Node(Child
* Node) of Current State(Father Node)
*
*/
public static StateEightPuzzle findSuccessor(StateEightPuzzle fatherNode, int x, int y, int pre) {
int nextXCordiante, nextYCordiante;
nextXCordiante = fatherNode.getXEmptyTile();
nextYCordiante = fatherNode.getYEmptyTile();
StateEightPuzzle childNode = new StateEightPuzzle();
if ((nextXCordiante + x) < 0 || (nextYCordiante + y) < 0 || (nextXCordiante + x) > (ROWSIZE - 1)
|| (nextYCordiante + y) > (ROWSIZE - 1)) {
flag = 0;
return childNode;
}
int nextEmptyTile = (nextXCordiante + x) * ROWSIZE + (nextYCordiante + y);
StringBuilder s1 = new StringBuilder(fatherNode.getStateofBoard());
char ch = s1.charAt(nextEmptyTile);
s1.setCharAt(nextEmptyTile, '0');
s1.setCharAt(ROWSIZE * nextXCordiante + nextYCordiante, ch);
childNode.setStateofBoard(s1);
childNode.setXEmptyTile(nextXCordiante + x);
childNode.setYEmptyTile(nextYCordiante + y);
childNode.setG(fatherNode.getG() + 1);
childNode.setH(getManhattanDistance(s1));
childNode.setPre(pre);
int maxfValue = (fatherNode.getF()) > (childNode.getG() + childNode.getH()) ? fatherNode.getF()
: (childNode.getG() + childNode.getH());
childNode.setF(maxfValue);
flag = 1;
return childNode;
}
/**
*
* #param init
* #param flimit
* #param res
* #return function known as Iterative Deepening DFS for A* which uses f-cost for limiting it
* search depth. Once the search inside a given contour has been completed , a new
* iteration is started with new f-cost for the next DFS-CONTOUR.pls consult Artificial
* Intelligence A Modern Approach, 1st edition by Approach By Russell
*
*/
public static ReturnResult DFS_CONTOUR(StateEightPuzzle Node, int flimit, ReturnResult res) {
int newf = Integer.MAX_VALUE;
ReturnResult resTemp = new ReturnResult();
StateEightPuzzle stat;
tracePath[Node.getG()] = Node.getPre();
// distance matrix for Eight Puzzle which helps to get successor
int dist[][] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
// if current node exceeds flimit return it as flimit
if (Node.getF() > flimit) {
resTemp.flimit = Node.getF();
resTemp.sol = null;
return resTemp;
}
// I see : IDA* is going to give me juicy cool!
if (Node.getH() == 0) {
resTemp.flimit = flimit;
resTemp.sol = Node;
String sol = "uldr";
for (int i = 1; i <= Node.getG(); i++)
System.out.print(sol.charAt(tracePath[i]));
System.out.println("");
return resTemp;
}
// create next valid successor
for (int i = 0; i < 4; i++) {
if (Math.abs(i - Node.getPre()) == 2)
continue;
stat = findSuccessor(Node, dist[i][0], dist[i][1], i);
if (flag == 0)
continue;
resTemp = DFS_CONTOUR(stat, flimit, res);
if (resTemp.sol != null) {
resTemp.flimit = res.flimit;
return resTemp;
}
newf = resTemp.flimit < newf ? resTemp.flimit : newf;
}
resTemp.flimit = newf;
resTemp.sol = null;
return resTemp;
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s_2;
while ((s_2 = in.readLine()) != null) {
String str = "";
tracePath = new int[1000];
int emptySquare = 0;
String[] s2 = s_2.split("\\s+");
for (int i = 0; i < s2.length; i++) {
if (s2[i].equals("x") == false)
str += s2[i];
else
str += "0";
}
if (isSolvable(str) == false) {
System.out.println("unsolvable");
} else {
StringBuilder str_bld = new StringBuilder(str);
for (int i = 0; i < str_bld.length(); i++)
if (str_bld.charAt(i) == '0') {
emptySquare += i;
break;
}
// Create Initial Eight puzzle State Machine and let him dance
// with
// prima donna :-)
StateEightPuzzle init = new StateEightPuzzle();
init.setStateofBoard(str_bld);
init.setG(0);
init.setH(getManhattanDistance(str_bld));
init.setF(init.getH() + init.getG());
init.setXEmptyTile(emptySquare / ROWSIZE);
init.setYEmptyTile(emptySquare % ROWSIZE);
init.setPre(5);
int flimit = init.getF();
ReturnResult result = new ReturnResult();
result.flimit = flimit;
result.sol = init;
// loop loop i m a strange loop living a mundane life with hopes
for (;;) {
ReturnResult resTemp = DFS_CONTOUR(init, flimit, result);
if (resTemp.sol != null) {
break;
}
flimit = resTemp.flimit;
}
}
}
}
}
The problem I find is for example for the puzzle when inputed 1 2 3 4 5 6 x 7 8 , it
should input just "ll" moving the "x" tile to the right two times however it inputs "urdlurdlurdr"
any ideas where the problem can be?

Why is my stack only adding one element and then it deletes it?

I already debugged the code and found, that it adds the fist element (Stack size = 1)
but when trying to add the next element, the stack size jumps back to 0
I think the problem is in public void convert.
public void convert(int N) {
this.N = N;
int binary[] = new int[10];
int index = 0;
while (N > 0) {
binary[index++] = N % 2;
N = N / 2;
}
for (int x = index - 1; x >= 0; x--) {
this.binStack.push(binary[x]); //Here is the Problem
}
}
This is the whole code:
import java.util.Stack;
public class Dec2Bin {
public Stack<Integer> binStack; // We make it public to modify it in our tests.
private int N;
/**
* Constructor of an empty object. Use method {#code convert()} to convert a number.
*/
public Dec2Bin() {
binStack = new Stack<>();
}
/**
* Returns the number that is converted as {#code int}.
*
* #return the converted number
*/
public int getN() {
return N;
}
/**
* Converts the given number into binary format, with each digit being represented in a
* stack of {#code int}.
*
* #param N the number that is to be converted.
*/
public void convert(int N) {
// TODO implement this method
this.N = N;
int binary[] = new int[10];
int index = 0;
while (N > 0) {
binary[index++] = N % 2;
N = N / 2;
}
for (int x = index - 1; x >= 0; x--) {
this.binStack.push(binary[x]);
}
}
/**
* Returns the digits that are stored in {#code binStack} as a string. To is the binary format of the
* converted number.
* For testing purpose, we require that the function works also, if the variable {#code binStack} is
* modified externally.
*
* #return a string representation of the number in binary format.
*/
#Override
public String toString() {
// Caution: Stack.toString() does NOT respect stack order. Do not use it.
// TODO implement this method
String finalBinär = new String();
for (int y = 0; y < binStack.size(); y++){
String binär = Integer.toString(binStack.pop());
String prevBinär = new String();
finalBinär = prevBinär.concat(binär);
}
return finalBinär;
}
public static void main(String[] args) {
Dec2Bin dec2bin = new Dec2Bin();
dec2bin.convert(50);
System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
// Do it another time to demonstrate that toString does not erase the binStack.
System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
}
}
´´´
import java.util.Stack;
public class Dec2Bin {
public Stack<Integer> binStack; // We make it public to modify it in our tests.
private int N;
/**
* Constructor of an empty object. Use method {#code convert()} to convert a number.
*/
public Dec2Bin() {
binStack = new Stack<>();
}
/**
* Returns the number that is converted as {#code int}.
*
* #return the converted number
*/
public int getN() {
return N;
}
/**
* Converts the given number into binary format, with each digit being represented in a
* stack of {#code int}.
*
* #param N the number that is to be converted.
*/
public void convert(int N) {
// TODO implement this method
this.N = N;
int binary[] = new int[10];
int index = 0;
while (N > 0) {
binary[index++] = N % 2;
N = N / 2;
}
for (int x = index - 1; x >= 0; x--) {
this.binStack.push(binary[x]);
}
}
/**
* Returns the digits that are stored in {#code binStack} as a string. To is the binary format of the
* converted number.
* For testing purpose, we require that the function works also, if the variable {#code binStack} is
* modified externally.
*
* #return a string representation of the number in binary format.
*/
#Override
public String toString() {
// Caution: Stack.toString() does NOT respect stack order. Do not use it.
// TODO implement this method
String finalBinär = new String();
for (int y = 0; y < binStack.size(); y++){
String binär = Integer.toString(binStack.pop());
String prevBinär = new String();
finalBinär = prevBinär.concat(binär);
}
return finalBinär;
}
public static void main(String[] args) {
Dec2Bin dec2bin = new Dec2Bin();
dec2bin.convert(50);
System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
// Do it another time to demonstrate that toString does not erase the binStack.
System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
}
}
´´´
Your toString() method has at least two problems:
#Override
public String toString() {
// Caution: Stack.toString() does NOT respect stack order. Do not use it.
// TODO implement this method
String finalBinär = new String();
for (int y = 0; y < binStack.size(); y++){ // <1>
String binär = Integer.toString(binStack.pop()); // <2>
String prevBinär = new String();
finalBinär = prevBinär.concat(binär); // <3>
}
return finalBinär;
}
Lines <1> and <2>: during the for loop y is incremented on line <1>. At the same time the stack size decreases because on line <2> you remove elements from the stack with binStack.pop().
That means that you will only get about half the digits. (For example, if binStack.size() was 6 at the start: after 3 runs through the loop y == 3 and binStack.size() == 3, so your loop will terminate.)
Line <3> means that no matter what was in the binStack, your result will only ever contain one binary digit: that line (together with the previous line) has the same effect as finalBinär = ""+binär;, which effectively means: finalBinär = binär;

Adding max method to return the largest element on list

Our instructor told us to add a max method to return the largest element on the list and write the definition of the method max, The problem is since it already have a maxListSize which returns the maximum size of the list do I need to put a a max method again?
public abstract class ArrayListClass {
protected int length;
protected int maxSize;
protected DataElement[] list;
public ArrayListClass(){
length = 0;
maxSize = 100;
list = new DataElement[maxSize];
}
public ArrayListClass(int size){
if(size < 0){
System.out.println("The array size must be positive. Creating an array of size 100...");
}else{
maxSize = size;
}
length = 0;
list = new DataElement[maxSize];
}
//copy constructor
public ArrayListClass(ArrayListClass otherList){
maxSize = otherList.maxSize;
length = otherList.length;
list = new DataElement[maxSize];
for(int j = 0; j < length; j++){
list[j] = otherList.list[j].getCopy();
}
}
public boolean isEmpty(){
return (length == 0);
}
public boolean isFull(){
return (length == maxSize);
}
/*
* method that returns the number of elements
* in the list
*/
public int listSize(){
return length;
}
/*
* method that returns the maximum size
* of the list
*/
public int maxListSize(){
return maxSize;
}
/*
* method that prints the elements of the list
*/
public void print(){
for(int index = 0; index < length; index++){
System.out.print(list[index].getCopy() + " ");
}
System.out.println();
}
/*
* method that determines whether an item is the
* same as the item in the list at the position
* specified by location
*/
public boolean isItemAtEqual(int location, DataElement item){
return (list[location].equals(item));
}
/*
* method that inserts insertItem in the list
* at the position specified by location
*/
public void insertAt(int location, DataElement insertItem){
if(location < 0 || location >= maxSize){
System.out.println("The position of the item to be inserted is out of range.");
}else{
if(length >= maxSize){
System.out.println("Cannot insert in a full list");
}else{
for(int index = length; index > location; index--){
list[index] = list[index-1];
}
list[location] = insertItem.getCopy();
length++;
}
}
}
public void insertEnd(DataElement insertItem){
if(length >= maxSize){
System.out.println("Cannot insert in a full list");
}else{
list[length] = insertItem.getCopy();
length++;
}
}
public void removeAt(int location){
if(location < 0 || location >= length){
System.out.println("The location of the item to be removed is out of range.");
}else{
for(int index = location; index < length; index++){
list[index] = list[index + 1];
}
list[length-1] = null;
length--;
}
}
/*
* method that retrieves the element from the list
* at the position specified by location
*/
public DataElement retrieveAt(int location){
if(location < 0 || location >= length){
System.out.println("The location of the item to be retrieved is out of range.");
return null;
}else{
return list[location].getCopy();
}
}
public void replaceAt(int location, DataElement repItem){
if(location < 0 || location >= length){
System.out.println("The location of the item to be replaced is out of range.");
}else{
list[location].makeCopy(repItem);
}
}
public void clearList(){
for(int index = 0; index < length; index++){
list[index] = null;
}
length = 0;
}
public void copyList(ArrayListClass otherList){
if(this != otherList){
for(int index = 0; index < length; index++){
list[index] = null;
}
maxSize = otherList.maxSize;
length = otherList.length;
list = new DataElement[maxSize];
for(int index = 0; index < length; index++){
list[index] = otherList.list[index].getCopy();
}
}
}
public abstract int seqSearch(DataElement searchItem);
public abstract void insert(DataElement insertItem);
public abstract void remove(DataElement removeItem);
public abstract void removeAll (DataElement removeAllItem);
}
I think you missunderstood the code you provide.
maxListSize() is actually the size of the largest array that can be built : the number of elements contained (it is simply a getter, giving the maxSize property).
Your instructor wants you to write a method giving the largest element contained in your array, regardless the size of your array. You have to define : "How can i say this element is larger than another element ?"
Then write your code and you are done.

int array toString method that displays the values with spaces in between and a new line every ten values

I am a beginner when it comes to java and am having some issues(been sitting in front of this all day). I have searched far and wide for a solution, yet to no avail. My professor has asked me to fill out the blank methods, and I am especially having trouble with the toString method(although I am not feeling to good about the rest either), any help would be appreciated.
import java.util.Random;
public class SmartArray {
// declare an array of ints
int[] list;
Random r = new Random();
int pos = 0;
/**
* Creates and initializes an array of size n. It does not initialize the
* contents of the array.
*/
public SmartArray(int n) {
list = new int[n];
}
/**
*
* Initializes the contents of the array with random
*
* non-negative* numbers.
*
*/
public void initRandom() {
int i = 0;
int hold = 0;
while (i < list.length) {
hold = r.nextInt();
if (hold % 2 == 0) {
list[i] = hold;
i++;
} else {
hold = hold + 1;
list[i] = hold;
i++;
}
}
}
/**
*
* Allows client code to add an element to the array
*
* at the given position. Throws an ArrayIndexOutOfBounds
*
* exception with a message if the
*
* position is out of bounds.
*
*/
public void insert(int value, int pos) {
if (list.length > pos) {
list[pos] = value;
} else {
throw new ArrayIndexOutOfBoundsException("The position of your value is greater than the array");
}
}
/**
*
* Returns the position of target if target is
*
* one of the values in the array, otherwise -1.
*
* Implemented with a loop.
*
*/
public int find(int target) {
int position = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == target) {
position = i;
} else {
position = -1;
}
}
return position;
}
/**
*
* Same as the find method, except that it's implemented
*
* using recursion. (Hint: use a helper method.)
*
*/
public int recursiveFind(int pos, int target) {
if (pos >= list.length) {
return -1;
} else if (list[pos] == target) {
return pos;
} else {
return recursiveFind(pos + 1, target);
}
}
/**
*
* Returns the elements of the array, separated by
*
* spaces, with a newline after every 10 elements,
*
* so they can be easily displayed.
*
*/
public String toString() {
String listString = "";
int pos = 0;
for (int i = 0; i < list.length; i++) {
//list[i].toString();
listString = listString + (String) list[i] + " ";
pos++;
if (pos > 9) {
list = list + "\n";
pos = 0;
}
return listString;
}
}
}
Your method looks almost fine.
To add the newline, you should check for the remainder of the index.
You're also returning the resulting String inside the loop. You should only return after it.
public String toString() {
String listString = "";
for (int i = 0; i<list.length; i++){
listString = listString + (String)list[i] + " ";
if (i%9 == 0){ // if remainder of i%9 = 0, then add a newline
list = list + "\n";
}
}
return listString;
}
I don't want to give too much away since it's an academic assignment, but instead of pos, consider mod (%), which you use, so I know you're familiar with it.
Consider starting i at 1 and iterating through all values (no need to take 10 at a time). But test for the need for a newline like this:
i % 10 == 0
Whenever the ith value is divisible by 10, insert a newline.
Also, consider using Integer instead of int. In this way, you could simply do this:
listString = listString + list[i].toString() + " ";
Take a look at this post on SO.
Good luck!
How about:
public String toString() {
String listString = "";
for (int i = 1; i < list.length; i++) {
listString += list[i - 1] + (i % 10 == 0 ? "\n" : " ");
}
return listString;
}

error: illegal start of expression; reached end of file while parsing

I'm new to Java programming. This is part of homework questions. I need to provide a set of comparison methods on arrays. I tried my best and this is my attempt so far. Can somebody enlighten me? Any help will be much appreciated!
Several requirements I need to follow:
You must not add any public methods to the Selector class. You are free to add any private methods that you think are appropriate, but you can't add any public methods.
You must not add any fields, either public or private, to the Selector class.
You must not import anything other than java.util.Arrays, but you are not required to import this at all.
You are only allowed to use sorting as part of your solution in the nearest and farthest
methods.
You must not modify the existing constructor or add other constructors. This class is designed to be strictly a provider of static methods and should not be instantiated.
import java.util.Arrays;
/**
* A class that contains various selection methods on arrays.
* All methods assume that the array is completely filled with
* non-null values. If this is not true, the behavior is not specified.
* All the methods throw an IllegalArgumentException if the array
* parameter is null or has zero length. The array parameter to
* each method is guaranteed to not be changed as a result of the call.
*/
public final class Comparision{
/**
* C A N N O T I N S T A N T I A T E T H I S C L A S S .
*
*/
private Comparision(){
}
/**
* Return the element of a nearest to val. This method throws an
* IllegalArgumentException if a is null or has zero-length.
* The array a is not changed as a result of calling this method.
*
* #param a the array to be searched
* #param val the reference value
* #return the element a[i] such that ABS(a[i] - val) is minimum
*
*/
public static int nearest(int[] a, int val) {
int[] a = new int[10];
if (a == null || a.length == 0){
throw new IllegalArgumentException("a is null or has zero-length");
}
int idx = 0;
int distance = Math.abs(a[0]-val);
for(int c = 1; c< a.length; c++){
int cdistance = Math.abs(a[c] - val);
if(cdistance < distance){
idx=c;
distance = cdistance;
}
}
int theNumber = a[idx];
return theNumber;
}
/**
* Return the element of a farthest from val. This method throws an
* IllegalArgumentException if a is null or has zero-length.
* The array a is not changed as a result of calling this method.
*
* #param a the array to be searched
* #param val the reference value
* #return the element a[i] such that ABS(a[i] - val) is maximum
*
*/
public static int farthest(int[] a, int val) {
int[] a = new int[10];
if (a == null || a.length == 0){
throw new IllegalArgumentException("a is null or has zero-length");
}
int idx = 0;
int distance = Math.abs(a[0]-val);
for(int c = 1; c< a.length; c++){
int cdistance = Math.abs(a[c] - val);
if(cdistance > distance){
idx=c;
distance = cdistance;
}
}
int theNumber = a[idx];
return theNumber;
}
/**
* Return the k elements of a nearest to val.
* The array a is not changed as a result of calling this method.
* This method throws an IllegalArgumentException if k is negative.
* This method returns an array of zero length if k == 0 or if
* k > a.length.
*
* #param a the array to be searched
* #param val the reference value
* #param k the number of near elements to identify
* #return the k elements a[i] such that ABS(a[i] - val)
* are the k smallest evaluations
*
*/
public static int[] nearestK(int[] a, int val, int k) {
int[] b = new int[10];
for (int i = 0; i < b.length; i++){
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int[w];
w = 0;
for (int i = 0; i < k; i++){
if (k < 0){
throw new IllegalArgumentException("k is not invalid!");
}
c[w] = b[i];
w++;
}
return c;
}
/**
* Return the k elements of a farthest from val.
* The array a is not changed as a result of calling this method.
* This method throws an IllegalArgumentException if k is negative.
* This method returns an array of zero length if k == 0 or if
* k > a.length.
*
* #param a the array to be searched
* #param val the reference value
* #param k the number of far elements to identify
* #return the k elements a[i] such that ABS(a[i] - val)
* are the k largest evaluations
*
*/
public static int[] farthestK(int[] a, int val, int k) {
int[] b = new int[10];
for (int i = 0; i < 10; i++){
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int[w];
int w = 0;
for (int i = array.length-1; i >= array.length-k; i--){
if (k < 0){
throw new IllegalArgumentException("k is not invalid!");
}
else if (k == 0 || k > a.length){
int[] c = "";
}
c[w] = b[i];
w++;
}
return c;
}
/**
* Return the number of elements of a that are greater than val.
*
* #param a the array to be searched
* #param val the reference value
* #return the number of elements a[i] such that a[i] > val
*
*/
public static int numGreater(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
w++;
}
return w;
}
/**
* Return an array of all the elements of a that are greater than val.
* If a contains no elements greater than val, this method returns an
* array of zero length.
*
* #param a the array to be searched
* #param val the reference value
* #return the elements a[i] such that a[i] > val
*
*/
public static int[] greater(int[] a, int val){
int[] b = new int[w];
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
b[w] = a[i];
w++;
}
}
if (w = 0){
int[] b = {};
}
return b;
}
/**
* Return the number of elements of a that are less than val.
*
* #param a the array to be searched
* #param val the reference value
* #return the number of elements a[i] such that a[i] < val
*
*/
public static int numLess(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)<0){
w++;
}
return w;
}
/**
* Return an array of all the elements of a that are less than val.
* If a contains no elements less than val, this method returns an
* array of zero length.
*
* #param a the array to be searched
* #param val the reference value
* #return the elements a[i] such that a[i] < val
*
*/
public static int[] less(int[] a, int val) {
int[] b = new int[w];
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)<0){
b[w] = a[i];
w++;
}
}
if (w = 0){
int[] b = {};
}
return b;
}
}
You problem is in lines 194-197: you aren't closing your if statement, so your close curly braces after that are all messed up. To fix it, change numLess to:
public static int numLess(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)<0){
w++;
} // This is the curly brace you are missing
}
return w;
}
EDIT: the other answer is right as well; you have the same problem in both numGreater and numLess. Add the close-curly brace in both functions and it should compile correctly.
I think you're missing brackets or semi-colons:
This should be:
public static int numGreater(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
w++;
}
return w;
}
Should be:
public static int numGreater(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
w++;
}//<---missing this fella
}
return w;
}

Categories

Resources