In the following code, I have resized an array, increased in length by 5 elements. length is displaying correctly. But when I run a loop to display the elements of the array, only initialized elements are displayed. How can I show all the elements?
package arraychallenge;
import java.util.*;
public class ArrayChallenge {
public static void main(String[] args) {
Scanner CountScanner = new Scanner(System.in);
System.out.println("How many integers you have in your list? ");
int count = CountScanner.nextInt();
System.out.println("Enter the integers now - ");
int[] MyArray = getIntegers(count);
System.out.println("Unsorted Array is present here:");
for (int i = 0; i < MyArray.length; i++) {
System.out.println(MyArray[i]);
}
sortArray(MyArray);
printArray(MyArray);
resizeArray(MyArray, MyArray.length, 5);
printArray(MyArray);
}
public static int[] getIntegers(int count) {
Scanner MyScanner = new Scanner(System.in);
int[] MyArray = new int[count];
for (int i = 0; i < MyArray.length; i++) {
MyArray[i] = MyScanner.nextInt();
}
return MyArray;
}
public static void sortArray(int[] MyArray) {
int temp;
for (int i = 0; i < MyArray.length; i++) {
for (int j = i+1; j < MyArray.length; j++) {
if (MyArray[i] > MyArray[j]) {
temp = MyArray[i];
MyArray[i] = MyArray[j];
MyArray[j] = temp;
}
}
}
}
public static void printArray(int[] MyArray) {
System.out.println("Sorted Array is present here:");
for (int i = 0; i < MyArray.length; i++) {
System.out.println(MyArray[i]);
}
}
public static void resizeArray(int[] MyArray, int count, int increase){
int[] tempArray = MyArray;
MyArray = new int[count+increase];
System.out.println("length of MyArray is now " + MyArray.length);
for (int i = 0; i < count; i++) {
MyArray[i] = tempArray[i];
}
}
}
In your resizeArray method, you are passing in MyArray. Then you are creating a new array of size 5, and assigning it to the MyArray variable, but this is not the same as the one you passed in.
Read this answer: https://stackoverflow.com/a/40523/3887715
My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed. – dhackner Oct 20 '10 at 16:38
In short, you call the variable MyArray in resizeArray, but it's not the same MyArray you created in main. It's a new variable inside resizeArray that happens to have the same name. So by doing MyArray = new int[count+increase];, you are not changing your original MyArray, you are changing a new one.
If you run this:
public class ArrayTest {
public static void main(String[] args) {
int[] array1 = new int[]{1,2,3,4,5};
System.out.println("Print array in main 1:");
printArray(array1);
increaseArraySize(array1, 5);
System.out.println("Print array in main 2:");
printArray(array1);
}
private static void increaseArraySize(int[] array1, int size) {
int[] tempArray = array1;
array1 = new int[tempArray.length + size];
for (int i = 0; i < tempArray.length; i++) {
array1[i] = tempArray[i];
}
System.out.println("Print array in increaseArraySize:");
printArray(array1);
}
public static void printArray(int[] MyArray) {
for (int i = 0; i < MyArray.length; i++) {
System.out.println(MyArray[i]);
}
}
}
You get:
Print array in main 1:
1
2
3
4
5
Print array in increaseArraySize:
1
2
3
4
5
0
0
0
0
0
Print array in main 2:
1
2
3
4
5
So you can see the 0s are being printed the second time the printArray method is called.
If you change the name of MyArray in resizeArray, maybe that will help you understand.
As suggested by the comments, you can have resizeArray return an array, and then assign that back to MyArray in main().
Related
I am trying to print only distinct integer values once even though they are repeated multiple times in an array with the introduced order. Firstly, I need to take array size from user but I cannot determine how to initialize that variable.Can I use n -inclueded in the code- as an array size variable? When I compiled I doesn't print anything. Where are my mistakes, and how to deal with them? Any idea?
public static void uniqueNumbers(int arr[], int n)
{
for (int i=0; i<n; i++)
{
for (int j =0; j<i;j++)
{
if (arr [i]==arr[j])
break;
if (i==j)
System.out.print(arr[i] + " ");
}
}
}
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int arr [] = new int [n];
uniqueNumbers(arr,n);
}
}
You need to fill the array,that is, you need to take input for the array elements.
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int arr [] = new int [n];
//Add the following lines.
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
uniqueNumbers(arr,n);
}
Print the array and try your logic again.
you need to first request for the size of the array as shown below:
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter array size");
int n =scan.nextInt();
// declaring and creating array objects
int[] arr = new int[n];
// displaying default values
System.out.println("Default values of array:");
for (int i=0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
// initializing array
System.out.println("\n\n***Initializing Array***");
System.out.println("Enter "+ arr.length
+ " integer values:");
for(int i=0; i < arr.length; i++) {
// read input
arr[i] = scan.nextInt();
}
uniqueNumbers(arr, n);
}
public static void uniqueNumbers(int[] arr, int n) {
int slow = 1;
for (int fast = 1; fast < n; fast++) {
if (arr[fast] != arr[slow - 1]) {
arr[slow++] = arr[fast];
}
}
arr = Arrays.copyOf(arr, slow);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
I was trying to create a code that rearranges given elements in an array -by the user- in ascending order, and I have done that, but the program requires
printing the given elements after sorting them firstly, then printing them before sorting.
I have no problem with printing the elements after sorting
the problem is with printing them before sorting
how to re-use ar[S] = in.nextInt() the given elements by the user out of its for loop
import java.util.*;
public class SortingnumbersANDswapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int swap;
int ar[] = new int[3]; //{8,10,5}
for (int S = 0; S < ar.length; S++) {
ar[S] = in.nextInt(); //this for loop is used to store numbers in the array
}
for (int i = 0; i < ar.length; i++) {
/* this nested for loop is used to compare the first element with the second one in the array
or the second element with the third.
*/
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) { //8>10-->F , 8>5 -->T , {5,10,8} the new arrangment we are going to use
swap = ar[i]; // 10>8-->T {5,8,10}
ar[i] = ar[j];
ar[j] = swap;
}
}
System.out.println(ar[i]); // to print the new order print it inside the array
}
// I wanna do something like that
// System.out.println(ar[S]);
// but of course I cant cause array S is only defined in it's loop
}
}
You can't reuse it, you need to keep the original array stored in another array that stays untouched. Additionally, Arrays are usually declared as int[] ar in Java, instead of int ar[]. Something along the following lines should work as intended:
public class SortingnumbersANDswapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int swap;
int[] ar = new int[3]; //{8,10,5}
for (int S = 0; S < ar.length; S++) {
ar[S] = in.nextInt(); //this for loop is used to store numbers in the array
}
System.out.println("::: Original Array :::");
int[] originalArray = Arrays.copyOf(ar, ar.length);
for (int j : originalArray) {
System.out.println(j);
}
System.out.println("::: Sorted Array :::");
for (int i = 0; i < ar.length; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) { //8>10-->F , 8>5 -->T , {5,10,8} the new arrangment we are going to use
swap = ar[i]; // 10>8-->T {5,8,10}
ar[i] = ar[j];
ar[j] = swap;
}
}
System.out.println(ar[i]); // to print the new order print it inside the array
}
}
}
You can do a copy of the array using the copyOf method from the Arrays library (java.util.Arrays) before you start changing the array.
Here you can find some different approaches - https://www.softwaretestinghelp.com/java-copy-array/amp/
You can use System.out.print(Arrays.toString(arr)); to print the entire array.
public static void main(String... args) {
int[] arr = readArray(3);
System.out.print(Arrays.toString(arr));
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (arr[i] > arr[j]) {
swap(arr, i, j);
System.out.print(Arrays.toString(arr));
}
}
}
}
private static int[] readArray(int size) {
System.out.format("Enter %d elements:\n", size);
Scanner scan = new Scanner(System.in);
int[] arr = new int[size];
for(itn i = 0; i < arr.length; i++)
arr[i] = scan.nextInt();
return arr;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
I was asked to
Create a method with a single parameter, an array of integers, that will return an array of integers. Count how many odd values exists within the array. Create a new array with that many elements. Place all the odd values into this new array ( that is all odd values from the array passed through as a parameter ). Return this new array
but I am having some difficulty in transferring the odd values into the new array. I can get the correct size based on the number of odd values in the first array but right now they appear as zeros. Here is the code:
import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}
According to your question, method output needs to...
Return this new array
Hence method output needs to return int[] (and not int).
After counting the number of odd values in the array passed to method output and creating the array that the method needs to return, in order to populate the returned array, you need to maintain a second [array] index. You are using the same index to populate the returned array and to iterate the array parameter. The returned array may be smaller in size, i.e. contain less elements, than the array parameter so using the same index for both arrays may cause method output to throw ArrayIndexOutOfBoundsException. In any method, you should also always check whether the method parameters are valid.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null && beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}
Your output function should return an array, so return type will not be int. It will be int[]. See the below code and let me know.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}
public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}
So I need to create a new array that swaps the first and last values of my existing array. Here's what I have so far:
import java.util.Scanner;
import java.util.Arrays;
public class P9_ArrayManipulate
{ public static void main (String[] args)
{ Scanner in = new Scanner(System.in);
System.out.println("Please enter seven numbers for an Array.");
int []array = new int[7];
int total = 0;
for (int i = 0; i < 7;i++){
array[i] = in.nextInt();
}
System.out.println("Your reversed array is "+reverseArray(array));
System.out.println("Your swapped array is "+swapArray(array));
System.out.println("Your array without even numbers is "+evenArray(array));
System.out.println("The program has finished calling array methods.");
}
public static int []reverseArray(int []array)
{ int[] reversed = new int[array.length];
int i;
for(i=0; i < array.length; i++)
{
reversed[i] = array[(array.length - i -1)];
}
return reversed;
}
public static int []swapArray (int []array)
{
array[0] += array[array.length-1];
array[array.length-1] = array[0] - array[array.length-1];
array[0] -= array[array.length-1];
return array;
}
public static int []evenArray(int []array)
{ for (int i = 0; i < array.length;i++){
if (array[i]%2 !=0)
{array[i] = 0;}
i++;}
return array;
}
}
Everything compiles correctly (as far as I can tell), but I'm getting a weird run time error. After seven inputs, I get this as my output:
Your reversed array is [I#b4d079
Your swapped array is [I#3644d1
Your array without even numbers is [I#3644d1
The program has finished calling array methods.
It would be much easier to just swap the first and last values of the array passed in to the swapArray() function and return that instead of creating a new array.
Something like the following will work (and it doesn't create a new variable to facilitate swapping):
public static int[] swapArray(int[] array) {
array[0] += array[array.length-1];
array[array.length-1] = array[0] - array[array.length-1];
array[0] -= array[array.length-1];
return array;
}
You have to import Arrays from java.util.Arrays
You may use the following answer to merge the arrays in swapArray() method
How can I concatenate two arrays in Java?
Try something like this:
*Edit: If its a must to create new array, just create int newarray[] = method(); instead of array[]=method();
import java.util.Scanner;
public class Array
{
public static void main (String[] args)
{ Scanner in = new Scanner(System.in);
System.out.println("Please enter seven numbers for an Array.");
int []array = new int[7];
for (int i = 0; i < 7;i++){
array[i] = in.nextInt();
}
array = reverseArray(array);
System.out.println("Your reversed array is :");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
System.out.println();
array = swapArray(array);
System.out.println("Your swapped array is :");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
// System.out.println("Your array without even numbers is "+evenArray(array));
System.out.println();
System.out.println("The program has finished calling array methods.");
}
public static int[] reverseArray(int []array)
{ int left = 0;
int right = array.length-1;
while(left<right){
int reverse = array[left];
array[left]=array[right];
array[right] = reverse;
left++;
right--;
}
return array;
}
public static int []swapArray (int []array)
{
int help = 0;
help = array[0];
array[0] = array[6];
array[6] = help;
return array;
}
}
Trying to make a HIT(x). when Hit called it decreases the elements( which are greater than x) of array by one and then print the array. and x is also an array which contains some element. For example. AR[7 4 5 3] and x= [4 2 5] then output is [5 3 4 2]. I am trying but not getting the relevant output. my code terminates only after taking the array element.
import java.util.Scanner;
public class Kom1 {
static int[] array;
public void hit(int x) {
for (int i = 0; i < array.length; i++) {
if (array[i] > x) {
array[i] --;
}
}
printArray();
}
public void printArray() {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int maxElements = scanner.nextInt();
array = new int[maxElements];
for (int i = 0; i < maxElements; i++) {
array[i] = scanner.nextInt();
}
}
}
Your algorithm should be like this
for(int i=0;i<x.length;i++){
for(int j=0;j<array.length;j++){
if(array[j]>x[i]){
array[j]--;
}
}
}
Things you missed
x is a array of elements. but you are using as single integer value
you haven't define or get x
your main method don't have a calling methods for processing