I am trying to learn how to add dynamically data into a list but I am facing a problem.
Why am I getting wrong value index of 0. when ever I trying to add a value position of index.
import java.util.*;
public class MyList{
String[] mList = null;
int pointer;
public MyList(){
mList = new String[pointer];
}
public void add(String aStringValue){
System.out.println("add: "+pointer+ " " +aStringValue+ " "+mList.length);
if (pointer < mList.length-1) {
System.out.println(pointer+ " " +aStringValue);
mList[pointer] = aStringValue;
pointer++;
}else{
System.out.println("New List:");
String[] lStringList = new String[mList.length + 20];
System.arraycopy(mList, 0, lStringList, 0, mList.length);
mList = lStringList;
System.out.println("New List: "+mList.length);
}
}
public int size(){
int size = 0;
for (int i = 0;i<mList.length;i++) {
if (mList[i] == null) {
return size;
}else{
size++;
}
}
return size;
}
public String get(int index){
return mList[index];
}
}
public class ListSize{
public static void main(String[] args){
MyList lList = new MyList();
lList.add("Amit");
lList.add("Deepak");
lList.add("Vishal");
lList.add("hello");
lList.add("abc");
lList.add("rahul");
lList.add("ajit");
lList.add("durgesh");
lList.add("a");
lList.add("b");
lList.add("c");
lList.add("d");
lList.add("e");
System.out.println("MyList is: "+lList.size());
for (int i = 0; i<lList.size(); i++) {
System.out.println(lList.get(i));
}
}
}
I expect the Output of Amit, Deepak but the Actual output is Deepak, vishal
When you create a new array, you don't add anything to it. I suggest you always check the size is ok, and afterwards, always add the element. If you want to see this clearly, I suggest stepping through the code in your debugger.
public void add(String aStringValue) {
// ensure capacity.
if (pointer == mList.length)
mList = Arrays.copyOf(mList, mList.length + 20);
mList[pointer++] = aStringValue;
}
In your add method, if the array hasn’t got room for the string you want to add, you are creating a new and bigger array, but not adding the string to the new array.
I believe that the code in the if part of your if statement should go after the if statement instead.
Related
I was able to make the Constructor and capacity methods to works but don;t know why size(),isFull() and isEmpty() fails.I believe its pretty simple but i am just unable to see a minor error and fix it.Hope someone can clarify what i am doing wrong with thorough explaination.Also,my constructor works with the test file and it passes,but just want to know Is my constructor correct as specified by question?
import java.util.Arrays;
import java.util.Iterator;
public class SortedArray<T extends Comparable> implements
java.lang.Iterable<T> {
public SortedArray(int capacity) {
this.array = (T[]) new Comparable[0];
this.capacity = capacity;
this.size = 0;
}
public SortedArray(int capacity, T[] data) {
if(capacity > data.length)
{
this.capacity = capacity;
}
else {
this.capacity = data.length;
}
this.size = data.length;
this.array = (T[]) new Comparable[0];
}
final public int size() {
return this.size
}
final public int capacity() {
return this.capacity;
}
final boolean isEmpty() {
return size == 0;
}
final boolean isFull(){
return size == capacity;
}
#Override
final public Iterator<T> iterator() {
// Do not modify this method.
return Arrays.stream(array).iterator();
}
// Do not modify these data members.
final private T[] array; // Storage for the array's element
private int size; // Current size of the array
final private int capacity; // Maximum size of the array
}
//// Test File:
#Test
public void testConstructor() {
System.out.println("Constructors");
SortedArray array = new SortedArray(20);
assertEquals(array.size(), 0);
assertEquals(array.capacity(), 20);
Integer[] data = {1, 2, 3, 4};
array = new SortedArray(20, data);
assertEquals(array.size(), 4);
assertEquals(array.capacity(), 20);
array = new SortedArray(2, data);
assertEquals(array.size(), 4);
assertEquals(array.capacity(), 4);
}
#Test
public void testSize() {
System.out.println("size");
SortedArray arr = new SortedArray(10);
// Array is initially empty
assertEquals(arr.size(), 0);
// Inserting elements increases size
arr.add(12);
arr.add(13);
arr.add(14);
assertEquals(arr.size(), 3);
// Inserting duplicates increases size
arr.add(12);
arr.add(13);
assertEquals(arr.size(),5);
// Fill up the array
for(int i = 0; i < 5; ++i)
arr.add(i);
assertEquals(arr.size(), 10);
// Size does not change when array is full
arr.add(10);
arr.add(11);
assertEquals(arr.size(), 10);
// Removing elements decreases size
arr.remove(0);
arr.remove(1);
arr.remove(2);
assertEquals(arr.size(), 7);
// but removing elements that don't exist doesn't change anything
arr.remove(100);
assertEquals(arr.size(), 7);
// Removing from the empty array doesn't change size.
SortedArray empty = new SortedArray(10);
empty.remove(10);
assertEquals(empty.size(), 0);
}
#Test
public void testCapacity() {
System.out.println("capacity");
SortedArray array = new SortedArray(20);
assertEquals(array.capacity(), 20);
array = new SortedArray(100);
assertEquals(array.capacity(), 100);
Integer[] data = {1,2,3,4,5,6,7,8,9,0};
array = new SortedArray(20, data);
assertEquals(array.capacity(), 20);
array= new SortedArray(5, data);
assertEquals(array.capacity(), 10);
}
#Test
public void testIsEmpty() {
System.out.println("isEmpty");
SortedArray array = new SortedArray(10);
assertTrue(array.isEmpty());
array.add(10);
assertFalse(array.isEmpty());
array.remove(10);
assertTrue(array.isEmpty());
}
#Test
public void testIsFull() {
System.out.println("isFull");
SortedArray array = new SortedArray(5);
assertFalse(array.isFull());
array.add(10);
array.add(11);
array.add(12);
array.add(13);
array.add(14);
assertTrue(array.isFull());
array.remove(10);
assertFalse(array.isFull());
}
#Test
public void testIterator() {
}
testSize Failed : Expected <0> but was <3>
testCapacity Failed : Expected <5> but was <10>
testConstructor Failed : Expected <0> but was <4>
testisFull Failed : jUnit.framework.AssertionFailedError
testisEmpty Failed : jUnit.framework.AssertionFailedError
You forgot to include your "add(T toAdd)" and "remove(T toRemove)" methods, which when I was going through to make the tests pass, was the source of a vast majority of the fails. (Note: a trace of the fails would help, since your adds and removes need to be pretty complicated to fit the design it seems you intend)
Anyways, on to fixing what I can see.
In your second constructor, you never actually assign the data you take in. You call this.array = (T[]) new Comparable[0]; which creates an empty array of type Comparable. In reality, you need to call this.array = data in order to keep what's been given to you.
Another thing, in your size() method you forgot to place a semicolon after this.size. That tends to prevent things from passing.
Finally, final private T[] array can't have final, or you'll never be able to add or remove elements.
As a bonus, here are the add() and remove() methods I used to fit the requirements and make the tests pass (with comments!!!!):
public void add(T t) {
if (!(size >= capacity)) { //If there's room...
if (size == 0) //If the array is empty...
array[0] = t; //Add to first index
else
array[size] = t; //Add to next available index
size++;
}
}
public void remove(T element) {
if (size <= 0) //If the array is empty...
return; //Stop here
else {
for (int i = 0; i <= this.size(); i++) { //Linear search front-to-back
if (array[i].equals(element)) { //Find first match
array[i] = null; //Delete it
size--;
if (i != size) { //If the match was not at the end of the array...
for (int j = i; j <= (this.size() - 1); j++)
array[j] = array[j + 1]; //Move everything after the match to the left
}
return; //Stop here
}
}
}
}
On a side note, your calls to create SortedArray objects should really be parameterized (Using the <> such as SortedArray<Integer> arr = new SortedArray<Integer>(5, data);).
public static int arraysize=1;
public String namabuku;
public String penulis;
public String Kategori;
public String buku[][]=new String[arraysize][3];
public static int a=0;
public void isiData(String kategori, String buku, String penulis){
this.buku[a][0]=kategori;
this.buku[a][1]=buku;
this.buku[a][2]=penulis;
arraysize++;
a++;
}
Hi guys I tried to increase my array length every time I call a method named "isiData", but it didn't work. I already checked the increment, but nothing wrong with it. Is there any way to increase its length every time I use the method? I want to make a simple way to input book, category, and its author using array.
You cannot increase the size of array.
There are 3 approaches to solve this problem:
Use ArrayList as suggested by others.
You can create another temp array of size one greater than the previous array and then copy the temp array to already created array.
You can use the copyOf(array, size) function of Arrays in Java
For example:
previousArray = Arrays.copyOf(previousArray , arraysize + 1);
arraysize += 1
Just try this Approach:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
/**
*
* #author Maverick
*/
public class Buku {
public static int arraysize;
public String namabuku;
public String penulis;
public String Kategori;
public List<List<String>> bukuList = new ArrayList<List<String>>();
public static void main(String[] args) {
Buku n = new Buku();
for (int i = 0; i < 5; i++) {
n.isiData("ab" + i, "cd" + i, "ef" + i);
}
n.arraysize = n.bukuList.size();
for (int i = 0; i < n.bukuList.size(); i++) {
System.out.println(n.bukuList.get(i).toString());
}
}
public void isiData(String kategori, String buku, String penulis) {
bukuList.add(Arrays.asList(kategori, buku, penulis));
}
}
Output:
[ab0, cd0, ef0]
[ab1, cd1, ef1]
[ab2, cd2, ef2]
[ab3, cd3, ef3]
[ab4, cd4, ef4]
You have to call new array to change the size of an array. I assume this is an exercise to practice using an array, so I'm going to avoid the classes like Arrays and System in the isiData method. You should look at those classes though.
So something like this:
public class BukuTest
{
public String namabuku;
public String penulis;
public String Kategori;
public String buku[][] = new String[ 0 ][ 3 ];
public void isiData( String kategori, String buku, String penulis )
{
String[][] temp = this.buku;
final int len = temp.length;
this.buku = new String[ len + 1 ][];
for( int i = 0; i < len; i++ )
this.buku[i] = temp[i];
this.buku[len] = new String[ 3 ];
this.buku[len][0] = kategori;
this.buku[len][1] = buku;
this.buku[len][2] = penulis;
// not needed
// arraysize++;
// a++;
}
public static void main(String[] args) {
BukuTest b = new BukuTest();
b.isiData( "test1", "test2", "test3" );
b.isiData( "test4", "test5", "test6" );
b.isiData( "test7", "test8", "test9" );
System.out.println(b);
}
#Override
public String toString()
{
return "BukuTest{" + "namabuku=" + namabuku + ", penulis=" + penulis +
", Kategori=" + Kategori + ", buku=" +
Arrays.deepToString(buku) + '}';
}
}
Using an ArrayList is definitely the way to go here as others have commented and displayed but, if you are absolutely bent on using a Two Dimensional String Array then this can be done with a custom method conveniently named redimPreserve() as I have shown below.
As #Jdman1699 had mentioned in his comment under your post, this is a very inefficient way of doing this sort of thing especially for larger arrays but since you asked, here is how it can be done:
// YOUR METHOD:
public int arraysize = 1;
public String[][] buku = new String[arraysize][3];
public void isiData(String kategori, String buka, String penulis){
// I have renamed the buku argument for this method to buka
// since you can not have a parameter variable named the
// same as a Class Global variable.
buku = redimPreserve(buku, arraysize, 3);
buku[arraysize-1][0] = kategori;
buku[arraysize-1][1] = buka;
buku[arraysize-1][2] = penulis;
arraysize++;
}
// THE redimPreserve() METHOD:
public static String[][] redimPreserve(String[][] yourArray, int newRowSize, int... newColSize) {
int newCol = 0;
if (newColSize.length != 0) { newCol = newColSize[0]; }
// The first row of your supplied 2D array will always establish
// the number of columns that will be contained within the entire
// scope of the array. Any column value passed to this method
// after the first row has been established is simply ignored.
if (newRowSize > 1 && yourArray.length != 0) { newCol = yourArray[0].length; }
if (newCol == 0 && newRowSize <= 1) {
throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
+ "No Column dimension provided for 2D Array!\n");
}
if (newCol > 0 && newRowSize < 1 && yourArray.length != 0) {
throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
+ "No Row dimension provided for 2D Array!\n");
}
String[][] tmp = new String[newRowSize][newCol];
if (yourArray.length != 0) {
for(int i = 0; i < yourArray.length; i++) {
System.arraycopy(yourArray[i], 0, tmp[i], 0, yourArray[i].length);
}
}
return tmp;
}
How can I alter the below method to work with an ArrayList?
I was thinking something like this:
public static boolean sortArrayList(ArrayList<Integer> list) {
return false;
}
but i'm not sure how to complete it.
Here is the method that I am trying to convert from working with an Array to instead work with an ArrayList:
public static boolean sortArrayList(final int[] data) {
for(int i = 1; i < data.length; i++) {
if(data[i-1] > data[i]) {
return false;
}
}
return true;
}
public static boolean sortArrayList(final ArrayList <Integer> data) {
for (int i = 1; i < data.size(); i++) {
if (data.get(i - 1) > data.get(i)) {
return false;
}
}
return true;
}
I have a few problems with the accepted answer, as given by #Sanj: (A) it doesn't handle nulls within the list, (B) it is unnecessarily specialized to ArrayList<Integer> when it could easily be merely Iterable<Integer>, and (C) the method name is misleading.
NOTE: For (A), it's quite possible that getting an NPE is appropriate - the OP didn't say. For the demo code, I assume that nulls are ignorable. Other interpretations a also fair, e.g. null is always a "least" value (requiring different coding, LAAEFTR). Regardless, the behaviour should be JavaDoc'ed - which I didn't do in my demo #8>P
NOTE: For (B), keeping the specialized version might improve runtime performance, since the method "knows" that the backing data is in an array and the compiler might extract some runtime efficiency over the version using an Iterable but such claim seem dubious to me and, in any event, I would want to see benchmark results to support such. ALSO Even the version I demo could be further abstracted using a generic element type (vs limited to Integer). Such a method might have definition like:
public static <T extends Comparable<T>> boolean isAscendingOrder(final Iterable<T> sequence)
NOTE: For (C), I follow #Valentine's method naming advice (almost). I like the idea so much, I took it one step further to explicitly call out the directionality of the checked-for-sortedness.
Below is a demonstration class that shows good behaviour for a isAscendingOrder which address all those issues, followed by similar behaviour by #Sanj's solution (until the NPE). When I run it, I get console output:
true, true, true, true, false, true
------------------------------------
true, true, true, true, false,
Exception in thread "main" java.lang.NullPointerException
at SortCheck.sortArrayList(SortCheck.java:35)
at SortCheck.main(SortCheck.java:78)
.
import java.util.ArrayList;
public class SortCheck
{
public static boolean isAscendingOrder(final Iterable<Integer> sequence)
{
Integer prev = null;
for (final Integer scan : sequence)
{
if (prev == null)
{
prev = scan;
}
else
{
if (scan != null)
{
if (prev.compareTo(scan) > 0)
{
return false;
}
prev = scan;
}
}
}
return true;
}
public static boolean sortArrayList(final ArrayList<Integer> data)
{
for (int i = 1; i < data.size(); i++)
{
if (data.get(i - 1) > data.get(i))
{
return false;
}
}
return true;
}
private static ArrayList<Integer> createArrayList(final Integer... vals)
{
final ArrayList<Integer> rval = new ArrayList<>();
for(final Integer x : vals)
{
rval.add(x);
}
return rval;
}
public static void main(final String[] args)
{
final ArrayList<Integer> listEmpty = createArrayList();
final ArrayList<Integer> listSingleton = createArrayList(2);
final ArrayList<Integer> listAscending = createArrayList(2, 5, 8, 10 );
final ArrayList<Integer> listPlatuea = createArrayList(2, 5, 5, 10 );
final ArrayList<Integer> listMixedUp = createArrayList(2, 5, 3, 10 );
final ArrayList<Integer> listWithNull = createArrayList(2, 5, 8, null);
System.out.print(isAscendingOrder(listEmpty ) + ", ");
System.out.print(isAscendingOrder(listSingleton) + ", ");
System.out.print(isAscendingOrder(listAscending) + ", ");
System.out.print(isAscendingOrder(listPlatuea ) + ", ");
System.out.print(isAscendingOrder(listMixedUp ) + ", ");
System.out.print(isAscendingOrder(listWithNull ) + "\n");
System.out.println("------------------------------------");
System.out.print(sortArrayList(listEmpty ) + ", ");
System.out.print(sortArrayList(listSingleton) + ", ");
System.out.print(sortArrayList(listAscending) + ", ");
System.out.print(sortArrayList(listPlatuea ) + ", ");
System.out.print(sortArrayList(listMixedUp ) + ", ");
System.out.print(sortArrayList(listWithNull ) + "\n");
}
}
Try below function, it takes integer array and converts it into a ArrayList and then computes the result :
public static boolean sortArrayList(final int[] data) {
List<Integer> aList = new ArrayList<Integer>();
for (int index = 0; index < data.length; index++)
aList.add(data[index]);
for (int i = 1; i < aList.size(); i++) {
if (aList.get(i - 1) > aList.get(i)) {
return false;
}
}
return true;
}
So I have this code:
public class SortedIntList extends IntList
{
private int[] newlist;
public SortedIntList(int size)
{
super(size);
newlist = new int[size];
}
public void add(int value)
{
for(int i = 0; i < list.length; i++)
{
int count = 0,
current = list[i];
if(current < value)
{
newlist[count] = current;
count++;
}
else
{
newlist[count] = value;
count++;
}
}
}
}
Yet, when I run the test, nothing prints out. I have the system.out.print in another class in the same source.
Where am I going wrong?
EDIT: Print code from comment:
public class ListTest
{
public static void main(String[] args)
{
SortedIntList myList = new SortedIntList(10);
myList.add(100);
myList.add(50);
myList.add(200);
myList.add(25);
System.out.println(myList);
}
}
EDIT2: Superclass from comment below
public class IntList
{
protected int[] list;
protected int numElements = 0;
public IntList(int size)
{
list = new int[size];
}
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else {
list[numElements] = value; numElements++;
}
}
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}
Let's walk through the logic of how you want it to work here:
first you make a new sorted list passing 10 to the constructor, which make an integer array of size 10.
now you call your add method passing 100 into it. the method sets position 0 to 100
now you add 50, the method sets 50 in position 0 and 100 in position 1
now you add 200, which gets placed at position 2
and you add 25. which gets set to position 0, and everything else gets shuffled on down
then your method will print out everything in this list.
So here are your problems:
For the first add, you compare current, which is initialized at 0, to 50. 0 will always be less than 50, so 50 never gets set into the array. This is true for all elements.
EDIT: Seeing the super class this is how you should look to fix your code:
public class SortedIntList extends IntList
{
private int[] newlist;
private int listSize;
public SortedIntList(int size)
{
super(size);
// I removed the newList bit becuase the superclass has a list we are using
listSize = 0; // this keeps track of the number of elements in the list
}
public void add(int value)
{
int placeholder;
if (listSize == 0)
{
list[0] = value; // sets first element eqal to the value
listSize++; // incriments the size, since we added a value
return; // breaks out of the method
}
for(int i = 0; i < listSize; i++)
{
if (list[i] > value) // checks if the current place is greater than value
{
placeholder = list[i]; // these three lines swap the value with the value in the array, and then sets up a comparison to continue
list[i] = value;
value = placeholder;
}
}
list[i] = value; // we are done checking the existing array, so the remaining value gets added to the end
listSize++; // we added an element so this needs to increase;
}
public String toString()
{
String returnString = "";
for (int i=0; i<listSize; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}
Now that I see the superclass, the reason why it never prints anything is clear. numElements is always zero. You never increment it because you never call the superclass version of the add method.
This means that the loop in the toString method is not iterated at all, and toString always just returns empty string.
Note
This is superseded by my later answer. I have left it here, rather than deleting it, in case the information in it is useful to you.
Two problems.
(1) You define list in the superclass, and presumably that's what you print out; but you add elements to newList, which is a different field.
(2) You only add as many elements to your new list as there are in your old list. So you'll always have one element too few. In particular, when you first try to add an element, your list has zero elements both before and after the add.
You should probably have just a single list, not two of them. Also, you should break that for loop into two separate loops - one loop to add the elements before the value that you're inserting, and a second loop to add the elements after it.
I'm new here..
I want to make a code to remember the last 10 numbers and to be not same.
private static ArrayList<Integer> nums = new ArrayList<Integer>();
public static void main(String[] args)
{
System.out.println(getRandomNumber());
}
public static int getRandomNumber()
{
int randomN = 0, rand = Rnd.nextInt(20);
while (nums.size() == 10)
{
nums.remove(nums.get(0));
continue;
}
if (!nums.contains(rand))
{
nums.add(rand);
randomN = rand;
}
else getRandomNumber();
return randomN;
}
when the array reach 10 values the first one will be deleted .. I hope you understand what I want :) Thanks
Try using an ArrayDequeue and when the length grows to more than 10, you simple remove the items from the tail.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
class main{
public ArrayList<Integer> nums;
public Random generator;
public static void main(String[] args){
// Calling Start
(new main()).start();
}
public void start(){
nums = nums = new ArrayList<Integer>();
generator = new Random();
for(int i=0;i<15;i++){
add(generator.nextInt(20));
print();
}
}
public void add(int newNumber){
// Check by iterating if i is already in nums
Iterator it = nums.iterator();
while(it.hasNext()){
if(newNumber == (Integer) it.next())
return; // i is already in our list
// so get out add()
}
if(nums.size() == 10){
int forward = nums.get(0);
for(int i = 1; i < 10; i++){
// Move numbers back 1 position
nums.set(i-1,forward);
// Save next number in forward
forward = nums.get(i);
}
}
nums.add(newNumber);
}
public void print(){
String str = "";
Iterator it = nums.iterator();
if(it.hasNext()){
str += "num: [ " + (Integer) it.next();
}
while(it.hasNext()){
str += " , " + (Integer) it.next();
}
str += " ]";
System.out.println(str);
}
}
I would either use a circular array or a linked list for this. Depending on what you plan to use the list of numbers for.