I have these two code for the deletion of an element from an array ,but there is just one difference the these two for loops for(int k=i;k< l-1;k++)
and for(int k =i;k< l;k++) in first we are de-crementing the size of the length of an array but in second we are not. Both the code are same else and does its deletion job fine. But I couldn't get the difference.
1st
import java.util.Scanner;
public class SearchDeletion1 {
public static void main(String[] args) {
int []a = new int[10];
a[0]=33;
a[1]=11;
a[2]=22;
a[3]=333;
a[4]=343;
a[5]=233;
a[6]=373;
a[7]=3223;
a[8]=313;
a[9]=332;
int i;
System.out.println();
int l=a.length;
Scanner s = new Scanner(System.in);
System.out.println("Enter the item to be searched");
int e = s.nextInt();
//searching
for(i=0;i<l;i++)
if(a[i]==e)
break;
if(i==a.length)
System.out.println("couldn't found");
else
System.out.println("found at position "+"a["+i+"]");
//deleting
for(int k=i;k<l-1;k++)
a[k]=a[k+1];
l--;
System.out.println("item deleted and new array");
for(int q=0;q<l;q++){
System.out.println("a["+q+"]"+"="+a[q]);
}
}
}
2nd
import java.util.Scanner;
public class SearchDeletion2 {
private int a[] ;
SearchDeletion2(int size){
a =new int[size];
}
public void set(int index,int elem){
a[index]=elem;
}
public int get(int index){
return a[index];
}
public static void main(String[] args) {
SearchDeletion2 arr = new SearchDeletion2(100);
arr.set(0,33);
arr.set(1,22);
arr.set(2,11);
arr.set(3,99);
arr.set(4,66);
arr.set(5,44);
arr.set(6,77);
arr.set(7,88);
arr.set(8,55);
arr.set(9,112);
int i;
int l=10;
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
for(i=0;i<l;i++)
if(arr.get(i)==r)
break;
System.out.println(i);
for(int k =i;k<l;k++)
arr.set(k,arr.get(k+1));
l--;
System.out.println(l);
for (int o=0;o<l;o++)
System.out.println(arr.get(o));
}
}
The second piece of code is wrong, because at the last iteration (with k==l-1) it performs arr.get(k+1), which means arr.get(l-1+1), which is arr.get(l), which is an invalid index for an array of l elements (going from 0 to l-1).
The code doesn't break because the actual array is bigger than l (100 'slots' are allocated, against 10 actually used). Anyway, it isn't a code that is safe under all the possible circumstances. So you shouldn't use it.
PS: the code would actually be safe, if the get method was implemented to be somehow resilient to invalid indices. Such as:
public int get(int index){
return (index < size) ? a[index] : 0;
}
You are not increasing or decreasing the size of array at any point in this code. All you are doing is changing the variable l, which dictates how many elements you are going to traverse. So even if you changed the loop to for(int k =i;k<l+10;k++) it would behave in the same way unless you started accessing elements beyond the allocated 100 in which case you would get ArrayIndexOutOfBounds exception.
Related
I have an assignment to create an array class where there are 2 constructors where each constructor sets a different size for the array.
The array is already an instance variable along with another instance variable to keep track of the current position in the array.
I have to create a method called add with an integer parameter that will store the parameter value in the array at the index of the position variable, then add 1 to the position variable. If the incremented position variable is outside the bounds of the array, the method calls the addspace method.
The addspace method creates a new array 25% larger than the instance variable array, copies all the values of the instance array to the new array, and assigns the new array to the instance variable.
I also need a method called size that will return the value in the position variable and a method called get that with 1 parameter(an index), the method returns the value at the parameter index.
The last thing I need is a print method that uses a for loop to print the values in the array.
So far this is what I have
public class ArrayClass
{
private int array[];
private int x=0;
public ArrayClass()
{
this.array= new int[10];
add(1);
getThat(0);
print();
}
public ArrayClass(int y)
{
this.array= new int[y];
add(2);
getThat(0);
print();
}
public void add(int a)
{
array[x]=a;
x++;
if(x>array.length)
addspace();
}
public void addspace()
{
double d=array.length+(array.length*0.25);
int v=(int)d;
int newArray[]= new int[v];
for(int i=0; i<array.length; i++)
{
newArray[i]=array[i];
System.out.println(newArray[i]);
}
}
public int size()
{
return x;
}
public int getThat(int index)
{
return array[index];
}
public void print()
{
for(int i=0; i<array.length; i++)
System.out.println(array[i]+" ");
}
public static void main(String[] args)
{
new ArrayClass();
new ArrayClass(5);
}
}
I know the title only asks for help with the first method but if someone would be kind enough to help with the other methods and the reason why my code won't run and print what I want it to that would be much appreciated.
Use the ArrayClass for only for declaring your functionality.Call add method as obj.add(number) until and unless you need to add something inside ArrayClass constructor itself.
Modified these things as per my understanding
In your add method you are assigning the value first and then adding space if the array is full, in this case, you are increasing the size even if it might not be needed (i.e not calling add method again).
Instead of this increase the size only when you require it.
In print function you are iterating through the whole array.Modified to-> it will iterate till the last index of value (i.e x)
package com.example;
public class ArrayClass
{
private int array[];
private int x=0;
private final int DEFAULT_SIZE=4;
public ArrayClass(){
this.array = new int[DEFAULT_SIZE];
}
public ArrayClass(int size){
this.array = new int[size];
}
public void add(int number){
//check whether array have space or not .if not then increase the space.
if(x > this.array.length-1){
addSpace();
}
array[x] =number;
x++;
}
private void addSpace(){
double newSize = array.length + array.length * 0.25;
int tempArray[] = new int[(int) newSize];
for(int i=0; i<array.length; i++){
tempArray[i]=array[i];
}
this.array = tempArray;
}
public int size()
{
return x;
}
public int getThat(int index)
{
return array[index];
}
public void print()
{
//instead of of printing the whole array Printed till last value index.
for(int i=0; i<x; i++)
System.out.println(array[i]+" ");
}
}
From the main method
ArrayClass ac1 = new ArrayClass();
ac1.add(5);
ac1.add(4);
ac1.add(5);
ac1.add(4);
ac1.add(7);
ac1.add(19);
ac1.print();
ArrayClass ac2 = new ArrayClass(5);
ac2.add(1);
//rest of your function call here
So I am trying to create a more time efficient stack implementation in java but I don't know how to make it work faster. Here is my code:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
int[] n = new int[0];
Scanner scan = new Scanner(System.in);
loop: while(true){
String stringy = scan.next();
switch(stringy){
case "push":
int x = scan.nextInt();
n = push(x, n);
System.out.println("ok");
break;
case "pop":
n = pop(n);
break;
case "exit":
System.out.println("bye");
break loop;
case "size":
System.out.println(n.length);
break;
case "back":
back(n);
break;
case "clear":
n = clear();
System.out.println("ok");
break;
}
}
}
static int[] push(int n, int[] x) {
int[] z = new int[x.length + 1];
for (int i = 0; i < x.length; i++){
z[i] = x[i];
}
z[x.length] = n;
return z;
}
static int[] pop(int[] x){
int z[] = new int[x.length-1];
for(int i = 0; i < z.length; i++){
z[i] = x[i];
}
System.out.println(x[x.length-1]);
return z;
}
static void back(int[] x){
System.out.println(x[x.length-1]);
}
static int[] clear(){
int x[] = new int[0];
return x;
}
}
Brief explanation:
Program takes values from scanner. And depending on a word that was entered, program proceeds with the corresponding instructions like push, pop, back... And it prints out the expected values to console with ok. Everything so far works properly as expected except the performance.
As you can see, in methods push and pop, my program creates new arrays and copies the values of the taken array which is x and adds 1 index with a pushed value or removes the popped value. This approach seems rather slow and inefficient. I couldn't find a more efficient way of doing that without picking arraylist or other classes from java library. But I have to use default integer arrays. And are there any other issues worsening the perfomance of the program?
How can I make my program work faster?
You can create member variables outside your method to keep track of the array and what is the size of it (similar to how array lists are implemented), no need to recopy the whole array everytime you need to pop/push.
You will need 2 variables, the array itself and the size (which will expand/shrink based on what you do)
You're better off creating a new class, I am gonna name it CustomStack
public class CustomStack
{
private int[] elements = new int[10]; // instantiated with a size of 10
private int size; // To track how many ints we currently have
....
}
You can now access the array and the size within the methods.
So first you need the push method, but wait there is a trick here, what if I already reached the max size of the array? (i.e: 10 numbers are already inside the array), well you need to cater for this, a known way to tackle this is create a new array with double the size of the current array and then copy all the values to the new array.
private void validateArraySize()
{
if (size == elements.length)
{
int[] temp = new int[elements.length * 2]; //double the size
System.arraycopy(elements, 0, temp, 0, elements.length); // copy the array
elements = temp; //set our member variable array to the new array
}
}
And the push method:
public void push(int n)
{
validateArraySize(); // The previos method to check if we can safely insert the value
elements[size] = n;
size++;
}
Regarding the pop method, it is very straight forward, you just need to check if there are any integers inside the array:
public int pop()
{
int valueRemoved = 0;
if (size == 0)
System.out.println("No elements found to pop");
else
{
valueRemoved = elements[size - 1]; //Get the last value
elements[size - 1] = 0; // remove the last value
size--;
}
return valueRemoved; // return removed value
}
The whole class will look like this:
public class CustomStack
{
private int[] elements = new int[10];
private int size;
public void push(int n)
{
validateArraySize();
elements[size] = n;
size++;
}
private void validateArraySize()
{
if (size == elements.length)
{
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
elements = temp;
}
}
public int pop()
{
int valueRemoved = 0;
if (size == 0)
System.out.println("No elements found to pop");
else
{
valueRemoved = elements[size - 1];
elements[size - 1] = 0;
size--;
}
return valueRemoved;
}
public int getSize()
{
return size;
}
public void back()
{
if (size == 0)
System.out.println("No elements found");
else
System.out.println(elements[size - 1]);
}
public void clear()
{
elements = new int[10];
}
}
Your main method will become:
public static void main(String[] args) {
CustomStack customStack = new CustomStack();
Scanner scan = new Scanner(System.in);
loop: while(true){
String stringy = scan.next();
switch(stringy){
case "push":
int x = scan.nextInt();
customStack.push(x);
System.out.println("ok");
break;
case "pop":
int val = customStack.pop();
System.out.println(val + " is popped");
break;
case "exit":
System.out.println("bye");
break loop;
case "size":
System.out.println(customStack.getSize());
break;
case "back":
customStack.back();
break;
case "clear":
customStack.clear();
System.out.println("ok");
break;
}
}
I was trying to execute the below code. It ran without any compilation errors. But the remove(int index) method is not working as expected.
import java.util.*;
public class Stones {
static int findLastStoneWeight(ArrayList<Integer> weight)
{
while(true)
{
Collections.sort(weight);
int n=weight.size();
if (n==1)
return weight.get(0);
else if(weight.get(n-1)>weight.get(n-2))
{
int temp1=weight.get(n-1);
int temp2=weight.get(n-2);
weight.add(n-2,temp1-temp2);
weight.remove(n-1);
System.out.println(weight.size()); //The new size of weight should be decreased by 1 but it does not!!
}
else
{
weight.remove(n-1);
weight.remove(n-2);
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<Integer> weight=new ArrayList<Integer>();
System.out.println("Enter the weights:");
while(true)
{
int w=sc.nextInt();
if(w<0)
break;
weight.add(w);
}
int lswt=findLastStoneWeight(weight);
System.out.println("Last stone weight:"+lswt);
}
}
When I used the remove(int index) method on the ArrayList weight the size of the ArrayList should get reduced by 1 but it remains the same. Why?
in the else if branch you noted, you first add an element to the weight ArrayList:
weight.add(n-2,temp1-temp2);
and then remove an element:
weight.remove(n-1);
All in all, you've added an element and removed an element, so the size of the list at the end of the method will be same as it was in the metho'd begining.
I made a bunch of methods and encountered this part of the question:
"Test your methods in a program and include a method that reads a list, terminated by -999, into an array."
I am not sure what to do on this part and hopefully someone can show me and explain how I can do this. Here is my Code:
(NOTE: the comment showing "4-Termination Method" section is empty. That is where I'm trying to make the code)
import java.util.Scanner;
public class Problem3 {
//1-MAXIMUM METHOD//
public static int max(int[] arr)
{
int tmpMax = arr[0];
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > tmpMax)
{
tmpMax = arr[i];
}
}
return tmpMax;
}
//2-MINIMUM METHOD//
public static int min(int[] arr)
{
int tmpMin = arr[0];
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < tmpMin)
{
tmpMin = arr[i];
}
}
return tmpMin;
}
//3-MIN-MAX METHOD//
public static int[] maxMin(int[] arr)
{
int[] myArray = new int [2];
myArray[0] = min(arr);
myArray[1] = max(arr);
return myArray;
}
//4-TERMINATION METHOD//
public static int termination(int[] arr)
{
}
//5-MAIN-METHOD//
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int a, b, c, d, e;
System.out.println("Input the Numbers: ");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
d = input.nextInt();
e = input.nextInt();
int[] test = {a, b, c, d, e};
System.out.println("The Maximum Number is: " + min(test));
System.out.println("The Minimum Number is: " + max(test));
int [] x = maxMin(test);
System.out.println("Min: " + x[0]);
System.out.println("Max: " + x[1]);
}
}
EDIT #1:
It has been nearly 24 hours so I'll give you some more hints regarding the requirement to "include a method that reads a list..."
You want to use a loop that ends when the user inputs a value of -999. You also have to consider that the requirement is to read the values into an array so that means you will have to resize the array each time through the loop.
So your logic would go something like this:
Get the first integer from System.in and store it in a variable
Initialize an array to hold the input values, initial length 0
Begin looping until the variable from #1 equals -999
a) Resize the array from #2
b) Add the integer to the resized array
b) Read the next integer from System.in and store in the same variable as #1
END EDIT #1
I don't want to give too much away too soon - see how to ask homework questions. So please see my comment regarding the requirement "include a method that reads a list...".
I will give you a short example of how to test your code "in a program":
public class TestProblem3{
public static void main(String[] args){
testMin();
}
public static void testMin(){
int[] data = {1,2,3,4,5};
int minValue = Problem3.min(data);
if( minValue != 1 )
System.err.println("FAILURE expected 1, but actual value is "+minValue);
data = new int[]{-1,2,3,4,5};
minValue = Problem3.min(data);
if( minValue != -1 )
System.err.println("FAILURE expected -1, but actual value is "+minValue);
//More tests here!
}
//More test methods here!
}
If you're really ambitious you could learn about JUnit and/or other testing frameworks (like TestNG)
My program is to sort numbers in ascending order and finally merge the answer which should also be in ascending order.
Compilation Errors -
**My Error****
Main.java:71: error: incompatible types
k=Integer.parseInt(res);
^
required: int[]
found: int
1 error
I had tried a lot to remove this error but could not find any logic.
**this my code**
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main(String[]args)
{
int w=0,x=0;
int[] k=new int[100];
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n<0)
{
System.out.println("Invalid Input");
System.exit(1);
}
int[] m=new int[n];
for(int i=0;i<n;i++)
{
m[i]=sc.nextInt();
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(m[i]>m[j])
{
int temp=m[i];
m[i]=m[j];
m[j]=temp;
}
}
}
for(int i=0;i<n;i++)
{
System.out.print(m[i]+" ");
}
w=m[n-1];
System.out.print(w);
int v=sc.nextInt();
if(v<0)
{
System.out.print("Invalid Input");
System.exit(1);
}
int[]r=new int[v];
for(int i=0;i<v;i++)
{
r[i]=sc.nextInt();
}
for(int i=0;i<v;i++)
{
for(int j=i+1;j<v;j++)
{
if(r[i]>r[j])
{
int temp=r[i];
r[i]=r[j];
r[j]=temp;
}
}
}
for(int i=0;i<v-1;i++)
{
System.out.print(r[i]+" ");
}
x=r[v-1];
System.out.print(x);
String res=" "+w+x;
k=Integer.parseInt(res);// error in this line;
Arrays.sort(k);
System.out.println(k);
}
}`
The final K is used merge the output of w and x which should also be in ascending order.
Is there any other method to resolve this.
Thank you in advance
k is an int[] (array of int) not an int.
Therefore
k = Integer.parseInt(res);
should be
k[someIndex] = Integer.parseInt(res);
You need to assign the returned value to an actual value (cell) from your array like:
for(int i=0; i<v; i++) {
....
k[i] = Integer.parseInt(res);
...
}
I agree with Eran .
incompatible types generally means left part of = and right part of = are NOT the same type. It is not a difficult error .
In your case the right part is an int while left part is int array , so just adding index to left part is fine.