creating arrays in eclipse - java

I need to make the random array print, and it does, & then i need to make the code sort my random array and print that.
I think, i have missed something out on the code,
Can anyone help me please?
Thanks
import java.util.ArrayList;
import java.util.Random;
public class Lab5
{
public static void main(String[]args)
{
Random r = new Random();
int[]arr = new int[5];
for(int i=0;i<arr.length;i++)
{
arr[i] = Math.abs(r.nextInt()%255) +1;
System.out.print(arr[i] + "\t");
}
System.out.println();
}
public static void ShowArray(ArrayList<Integer> array) {
for (int i=0; i<array.size(); i++) {
System.out.println(array.get(i));
System.out.println("Sort A: ");
ArrayList<Integer> sortedArrayA = ThreeSorts.SortA(array);
ShowArray(sortedArrayA);
}
}
}

Random r = new Random();
int[]arr = new int[5];
for(int i=0;i<arr.length;i++)
{
arr[i] = Math.abs(r.nextInt()%255) +1;
System.out.print(arr[i] + "\t");
}
System.out.println();
Arrays.sort(arr);
for(int item: arr)
System.out.println(item);

Retrace your execution - does the code that you wrote run?
Don't forget that code in a function only runs when the function is called.

The following code may give you some useful hints:
public static void main(String[] args) {
int[] array = new int[] {3,4,65,1,43};
System.out.println(Arrays.toString(array));
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
Notes:
I skip the part related to generating random integer, because you have it
to print an array you may use Arrays.toString()
to sort an array you may use Arrays.sort()

In method main you must add ShowArray(arg).

As #Mikeb and #Belinda point out, ShowArray is not being called. Furthermore, it is an infinitely recursive function, as it calls itself without a base case to terminate; perhaps you meant to put some of the lines in the main method? I corrected the indentation on your code so as to see this better.

Related

Why does implemented insertion sort with arraylist give no output and no error?

I was hoping anyone could help me with the following code in Java, because even though it shows no error, it gives no array as output:
I am trying to implement insertion sort. I made 2 packages and classes; a main one and a InsertionSort one.
The code I used is:
package main;
import java.util.ArrayList;
import insertionSort.InsertionSort;
public class Main implements Cloneable{
public static void main(String[] args){
ArrayList<Integer> unsortedArray = new ArrayList<Integer>();
unsortedArray.add(8);
unsortedArray.add(7);
unsortedArray.add(6);
unsortedArray.add(5);
unsortedArray.add(4);
unsortedArray.add(0);
unsortedArray.add(2);
InsertionSort sort = new InsertionSort(unsortedArray);
System.out.println("Initial unsorted array: ");
for(int i:InsertionSort.inputArray()){
System.out.print(i + " ");
}
sort.doInsertionSort();
System.out.println("Sorted array after performing insertion sort: ");
for(int i:InsertionSort.inputArray()){
System.out.print(i + " ");
}
}
}
package insertionSort;
import java.util.ArrayList;
public class InsertionSort {
private static ArrayList<Integer> array = new ArrayList<Integer>();
public static ArrayList<Integer> inputArray() {
return array;
}
public InsertionSort(ArrayList<Integer> inputArray){
InsertionSort.array = array;
}
public void doInsertionSort(){
for (int j = 1; j<array.size(); j++){
int key = array.get(j);
int i;
for (i=j-1; i>=0 && array.get(i)> key; i--){
array.set(i+1,array.get(i));
array.set(i+1, key);
}
}
}
}
The output I get is just the text without the arrays. Hope someone can help! Keep in mind I am a novice. Thank you kindly in advance :)
This assigns the array variable to itself :
public InsertionSort(ArrayList<Integer> inputArray){
InsertionSort.array = array;
}
This should be :
public InsertionSort(ArrayList<Integer> inputArray){
array = inputArray;
}
Besides you have a little mistake in your swap.
array.set(i+1, key); should be executed after the inner loop.
It sets the element of the outer loop (referenced by the key variable) at its correct position.
This has to be done only when you sorted the elements at its left, so after the inner loop.
So this :
for (i=j-1; i>=0 && array.get(i)> key; i--){
array.set(i+1,array.get(i));
array.set(i+1, key);
}
should be :
for (i=j-1; i>=0 && array.get(i)> key; i--){
array.set(i+1,array.get(i));
}
array.set(i+1, key);
As a side note, you don't use correctly instance and static modifiers.
You create an instance of InsertionSort :
InsertionSort sort = new InsertionSort(unsortedArray);
But the constructor values a static field.
...
private static ArrayList<Integer> array = new ArrayList<Integer>();
public InsertionSort(ArrayList<Integer> inputArray){
InsertionSort.array = array;
}
Why creating an instance in this case ?
InsertionSort has a state that is specific to the List that you pass to, so you should not use static modifiers for members of it that should be associated to one instance of InsertionSort.
So replace the static modifiers by instance modifiers.
You are trying to do things statically, but you don't have it quite right. Look at davidxxx's solution if you want to do it that way. If you don't want to do it statically. If you don't want to do things statically...
In your for loops, you are trying to call your InsertionSort methods statically. You need to use the InsertionSort object you already created (sort).
Your for loops should look like this...
for(int i:sort.inputArray())
Also, your InsertionSort constructor isn't right. It should look like...
public InsertionSort(ArrayList<Integer> inputArray){
InsertionSort.array = inputArray;
}
There is also one small problem in your sorting method. In your inner loop, you are correctly setting the value of index i+1 to the value at index i. However, you are then setting index i+1 equal to the "key" value, which ensures that your array will never change. Here is the correct algorithm.
public void doInsertionSort(){
for (int j = 1; j<array.size(); j++){
int key = array.get(j);
for (int i=j-1; i>=0 && array.get(i)> key; i--){ //I moved i's declaration here for simplicity.
array.set(i+1,array.get(i));
array.set(i, key); //This is the line that I changed!
}
}
}
I haven't actually tried compiling/running this yet, so let me know if this works or not.

Sorting large arrays does not return output

I have been playing around with different sorting functions and the basic code. However, when I tried to increase the size of the array to over 1,000, instead of a nice output I get just blank console, and it says that the program was terminated.
Can anyone explain what might be the issue?
public class Sorting {
public static void main(String[] args)
{
int[] array = generateRandomArray(10000);
printArray(array);
insertionSort(array);
printArray(array);
}
public static void printArray(int[] arr)
{
System.out.print("[ ");
for (int i=0; i<arr.length; i++)
{
System.out.print(arr[i] +" ");
}
System.out.println("]");
}
public static int[] generateRandomArray(int n)
{
int[] arr = new int[n];
Random rnd = new Random();
for (int i=0; i<n; i++)
{
arr[i]=rnd.nextInt(5000);
}
return arr;
}
public static void insertionSort(int[] arr)
{
int temp, index;
for (int i=1; i<arr.length; i++)
{
temp=arr[i];
index=i-1;
while (index>=0 && temp<arr[index])
{
arr[index+1]=arr[index];
index--;
}
arr[index+1]=temp;
}
}
}
In most IDEs e.g. Eclipse console output is limited. If you redirect output to file in Run Configuration (assuming you are using Eclipse) you should see the output.
Also enabling "Word wrap" in the console output might make it visible, again assuming it is Eclipse.
Just ran it on my machine. Worked fine. Make sure you import java.util.Random.
It seems that there is some line length limitation in Eclipse console. When I run your code in command line, it prints well.
If you want to fix this problem in eclipse, change the settings:
(1)Click 'window' menu -> 'preferences'
(2)'Run/Debug' -> 'Console'
(3)Check 'Fixed width console'
This should make your code works in Eclipse.

Arrays Sum User Input Recursion

So I'm trying to write a recursive method to sum an arraylist of integers and create a client to test it.
My Class is:
import java.util.ArrayList;
public class SumArray
{
public static int ArraySum(int[]arrayList, int sum, int size)
{
sum = sum + arrayList[size];
size--;
while(size >= 0)
{
return ArraySum(arrayList, sum, size);
}
return sum;
}
}
My Client is:
import java.util.ArrayList;
public class ArraySumClient
{
public static void main()
{
System.out.print("The sum of the array is: ");
SumArray r = new SumArray();
int[] myList = new int[5];
myList[0] = 1;
myList[1] = 2;
myList[2] = 3;
myList[3] = 4;
int size = myList.length-1;
System.out.println(r.ArraySum(myList, 0, size));
}
}
These both compile and work. However, I'm trying to figure out a way for the user to input the size of the array and the numbers in the array instead of my inputting the array size and numbers inside the client.
you can use java scanner to take input from cmd prompt
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You could try using an ArrayList instead of an array. It would let you dynamically add as many items as needed:
public static void main() {
List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);
myList.add(3);
myList.add(4);
// compute sum
int sum = 0;
for (Integer value : myList) {
sum += value;
}
System.out.println("The sum is " + sum);
}
Using this approach, you would not need to ask how many items the user intends to add.
As #Satya suggested, you could read input from the command line as command line argument and extract them as:
Integer[] array = Stream.of(args).map(Integer::parseInt).toArray(size -> new Integer[size]);
You do not want to pass the length of the array to the method ArraySum which, I suppose you are doing because you are not able to remove an element from the array. One way of doing this is by using Arrays.copyOf() using which you could copy a part of the array as another array.
I think it is always good to use List of theses situations.

Code 'running' forever in Java

I am pretty new at Java and I am finding difficulty in solving the problem. Basically the code get a number, and generate a vector in the function generateVector. When I run this code, I am asked to put a number and then the software stay running forever. If possible, could you guys help me without other functions that is kind advanced? I am still learning. Thanks.
import java.util.Scanner;
public class Atividade02 {
static Scanner dados = new Scanner(System.in);
static int n;
//Main
public static void main(String args[]){
System.out.println("Type a number: ");
n = dados.nextInt();
int[] VetorA = generateVector(n);
for(int i=0; i<VetorA.length; i++){
System.out.println("Position: "+ VetorA[i]);
}
}
//Função
public static int[] generateVector(int n){
int[] VetorA = new int [n];
for (int i=0; i<n; i++){
VetorA[i] = dados.nextInt();
}
return VetorA;
}
}
I am asked to put a number and then the software stay running forever.
Did you enter in the n numbers required by generateVector? The program is probably just blocked on input from the user.
Try to modfiy the class as follows:
import java.util.Scanner;
public class Atividade02 {
// Added private access modifiers for properties.
// It's not necessary here, but as a general rule, try to not allow direct access to
// class properties when possible.
// Use accessor methods instead, it's a good habit
private static Scanner dados = new Scanner(System.in);
private static int n = 0;
// Main
public static void main(String args[]){
// Ask for vector size
System.out.print("Define vector size: ");
n = dados.nextInt();
// Make some space
System.out.println();
// Changed the method signature, since n it's declared
// as a class (static) property it is visible in every method of this class
int[] vetorA = generateVector();
// Make some other space
System.out.println();
// Show results
for (int i = 0; i < vetorA.length; i++){
System.out.println("Number "+ vetorA[i] +" has Position: "+ i);
}
}
// The method is intended for internal use
// So you can keep this private too.
private static int[] generateVector(){
int[] vetorA = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Insert a number into the vector: ");
vetorA[i] = dados.nextInt();
}
return vetorA;
}
}
Also when naming variables stick with the Java naming convention, only classes start with capital letters.

Printing Values in an Array in Reverse

My code is designed to print the values if the array in order and then reverse order. However, I also have to At a minimum use the following method headers when writing your methods:
public static int printOriginalArray(int[] list)
public static int printInReverse(int[] list)
I got the code running! I get it now!! It just clicked!! Yes!!! :-) Now my method is not exactly accurate though correct? I should have 2 methods instead of 1 and I need to rewrite it so it reverses the numbers, not swaps.
public class Assignment01a {
public static void main (String[] args) {
int[] numbers = {4, 5, 6, 7};
System.out.println("The list in order is: ");
for (int num: numbers)
System.out.println(num + " ");
swap(numbers, 0, 3);
for (int num: numbers)
System.out.println(num + " ");
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr [i] = arr [j];
arr [j] = temp;
}
}
First, all methods need to be declared inside some class. Here, your swap method is being declared inside the Assignment01a class. Furthermore, there are static methods, which are declared by having the static keyword after the public keyword (as you have for your swap method). A static method can be called from main() directly (from a "static context") . Non-static methods however need to be invoked on/from object instances. These are methods without the static keyword and they can be thought of as belonging to a specific object.
Ok, now I corrected it the way you wanted it to work. Since your methods are declared so that they return int value I assumed it's for error checking. If method returns anything but 0 program will let you know something went wrong. It looks like this:
public class Assignment01a {
public static void main (String[] args) {
int[] numbers = {4, 5, 6, 7};
if (printOriginalArray(numbers) != 0)
System.out.println("ERROR!");
if (printInReverse(numbers) != 0)
System.out.println("ERROR!");
System.out.println("\nProgram completed successfully!");
}
public static int printOriginalArray(int[] list) {
System.out.println("The list in order is: ");
for (int num: list)
System.out.print(num + " ");
return 0;
}
public static int printInReverse(int[] list) {
System.out.println("\nThe list in reverse order is:");
for (int i = list.length-1; i >= 0; i--) {
System.out.print(list[i] + " ");
}
return 0;
}
}
I hope that clarified your problem, if you have any other question feel free to ask.

Categories