I'm unsure how do I call my code so that it matches my randomizer. My randomizer basically generates a number of random integers in an array and prints them like so.
Edit: If i wasn't clear, i want to call my randomizer into both the methods of the insertion sort class!
I tried using the insertion sort implementation i grabbed from geeks4geeks. They all have the parameter int[arr].
This is my code
public class randomArr {
public void randomizer(){
Scanner sc = new Scanner(System.in);
Random r = new Random();
System.out.println("Please enter the amount of integers you want in your array: ");
int n = sc.nextInt();
// Create array of 1000 ints
int[] intArr = new int[n];
// Fill array with random ints
for ( int i = 0; i < intArr.length; i++) {
intArr[i] = r.nextInt(100);
System.out.print(intArr[i] + ", ");
}
}
}
This is what i want to happen basically:
As you can see im calling sort and print array with my "intArr". How do i call my method with the given methods?
I have commented out the object i made using my method but if i were to leave it in, how would i use that object to call sort() and printarray()?
public class insertionSort {
public static void main(String[] args){
//randomArr arry = new randomArr(); \\the object of my method
//arry.randomizer());
Scanner sc = new Scanner(System.in);
Random r = new Random();
System.out.println("Please enter the amount of integers you want in your array: ");
int n = sc.nextInt();
// Create array of 1000 ints
int[] intArr = new int[n];
// Fill array with random ints
for ( int i = 0; i < intArr.length; i++) {
intArr[i] = r.nextInt(100);
System.out.print(intArr[i] + ", ");
}
sort(intArr);
printArray(intArr);
}
public static void sort(int arr[]){
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + ", ");
System.out.println();
}
}
Ok if you want to call the method of one class into another, you simply need to call it by adding the methods name next to the object of that class with a period in between like so ("object.method()"). So what you would do is:
import java.util.*;
class randomArr {
public int[] randomizer()
{
Scanner sc = new Scanner(System.in);
Random r = new Random();
System.out.println("Please enter the amount of integers you want in your array: ");
int n = sc.nextInt();
// Create array of 1000 ints
int[] intArr = new int[n];
// Fill array with random ints
for ( int i = 0; i < intArr.length; i++) {
intArr[i] = r.nextInt(100);
System.out.print(intArr[i] + ", ");
}
return intArr;
}
}
class Stack
{
public static void main(String[] args)
{
randomArr rArr = new randomArr();
int[] intArr = rArr.randomizer();
}
}
this way you can make that array in your other class and use it in your new class.
If you want to call the methods of insertionSort class you can call them without an object since they are static. You cannot use the object of another class to call a method not belonging to that object's class.
You can use insertionSort's methods in the randomArr class by creating it's object in the randomArr class and vice versa. But an object can only access the methods of it's own class.
you want to call method in another class you can create object of that class and then using the object reference you can call available the methods from that class.
insertionSort object = new insertionSort();
object.sort(intArr);
object.printArray(intArr);
As you defined sort and printArry are static methods , you can directly invoke them in your main method.
Related
I am stuck in my beginner java course and am trying to get my array to print out with the user's input on randomly selected index's. With the code I have so far it will only print out an index with all 0's such as this "{0, 0, 0, 0, 0, 0}"
Here is the prompt:
Create an empty int array of size 6.
Create a method called populateArray that will pass an array, use random class to choose a random index and prompt the user to enter a value, store the value in the array. Note: Generate 6 random index numbers in an attempt to fill the array.
Create a method called printArray that prints the contents of the array using the for each enhanced loop.
Here is my code:
public class ChangeUp {
public static void main(String[] args) {
int[] array = new int[6];
System.out.println("Please enter 6 numbers to add to a list.");
populateArray(array);
printArray(array);
}
public static void populateArray(int[] array) {
Random r = new Random();
Scanner input = new Scanner(System.in);
int rArray = r.nextInt(array.length);
int i = 0;
for (i = rArray; i <= array.length; i++) {
i = input.nextInt();
}
}
public static void printArray(int[] array) {
System.out.print("{" + array[0]);
for (int i = 1; i < array.length; i++) {
System.out.print(", " + array[i]);
}
System.out.println("}");
}
}
for (int i = rArray; i <= array.length; i++) {
i = input.nextInt();
}
Here is your problem. You assign the value(s) to i, not to elements of the array.
Turn:
i = input.nextInt();
into:
array[i] = input.nextInt();
You do not change any values of array. You can do it with array[i] = value where i is index which value you want to change.
Here is example of what populateArray would looks like:
public static void populateArray(int[] array) {
Random r = new Random();
Scanner input = new Scanner(System.in);
int i = r.nextInt(array.length);
array[i] = input.nextInt();
}
You did not assigne input values to the array: array[i] = ....
I would recommend you to not randomly insert an elements, but just fill an array and then shuffle it.
public class ChangeUp {
public static void main(String... args) {
int[] arr = new int[6];
System.out.format("Please enter %d numbers to add to a list:\n", arr.length);
populateArray(arr);
printArray(arr);
}
public static void populateArray(int... arr) {
Scanner scan = new Scanner(System.in);
List<Integer> tmp = new ArrayList<>(arr.length);
for (int i = 0; i < arr.length; i++)
tmp.add(scan.nextInt());
Collections.shuffle(tmp);
int i = 0;
for (int val : tmp)
arr[i++] = val;
}
public static void printArray(int... arr) {
System.out.println(Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ", "{", "}")));
}
}
Demo:
Please enter 6 numbers to add to a list:
1
2
3
4
5
6
{4, 3, 1, 5, 2, 6}
So I am very new to learning java and I have a sub class which contains the main and a parent class which does all the calculations. I am having problems on how to pass the elements of an array from the main class to the parent class.
Here is my code. Please help me with how to instantiate the array.
import java.util.Scanner;
public class GreatestLeastAverageApp {
public GreatestLeastAverageApp() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
GreatestLeastAverage number = new GreatestLeastAverage();
int[] x = {0};
int a = 0, b = 0;
x = new int[a];
{
for (int i = 0; i <= a; i++)
{
for (int j = 0; j <= a; j++)
GreatestLeastAverage.a[i] = x[j]; // loop to pass the values of the array elements to the parent class from the sub class.
}
}
Scanner keyboard = new Scanner(System.in); // for the input from the user
System.out.println("Enter the number of elements:");
a = keyboard.nextInt(); // enter the number of integers to be entered so loop can run accordingly
System.out.println("Enter a set of integers( Enter -99 to exit):");
do // do loop so the user can input the variables until one of the variable is =-99.
{
{
for (b = 0; b <= a; b++)
x[b] = keyboard.nextInt();
}
} while (x[b] != -99);
//GreatestLeastAverage number = new GreatestLeastAverage(); // object made for parent class.
System.out.println("The Greatest Number is" + number.computegreatest()); // output line.
System.out.println("The Smallest Number is" + number.computeleast());
System.out.println("The average is " + number.computeaverage());
keyboard.close();
}
}
public class GreatestLeastAverage {
static int x; //variables declared for input in super class.
public static int[] a; // static variable to access in both classes.
int temp;
int temp1;
int temp2;
int average;
public int greatestleastaverage(int d) {
d = x;
return x;
}
public static int getarray(int[] b) {
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= x; j++) {
a[i] = b[j];
}
}
return b[];
}
I know you can't return elements of an array but I really need help.
Use Lists. They're generally more flexible, and if you use ArrayList properly, it can be virtually just as performant as an array.
public class GreatestLeastAverage {
// ... other private members
private List<Integer> a = new ArrayList<Integer>();
public List<Integer> getA() {
return a;
}
}
This lets you do code like:
GreatestLeastAverage gla = new GreatestLeastAverage();
for (int b = 0; b <= a; b++) {
gla.getA().add(keyboard.nextInt());
}
If you should require that data for other uses, it's in gla already! Simply reuse it.
for(int a : gla.getA()) {
// Do something with a
}
I'm sure you used static members because you didn't know how to make it work otherwise, but just know that using static members is generally discouraged unless they're final (constant).
You shouldn't pass data (array) to methods in GreatestLeastAverage class by setting the value of the static field (public static int[] a;). Instead you should pass data to methods as theirs arguments. Your program should look like this:
import java.util.Scanner;
public class GreatestLeastAverageApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int numOfElems = input.nextInt();
int[] numbers = new int[numOfElems];
System.out.println("Enter a set of integers:");
for (int i = 0; i < numOfElems; i++) {
numbers[i] = input.nextInt();
}
System.out.println("Statistics:");
System.out.println(" min: " + GreatestLeastAverage.findMin(numbers));
System.out.println(" max: " + GreatestLeastAverage.findMax(numbers));
System.out.println(" average: " + GreatestLeastAverage.findAverage(numbers));
}
}
class GreatestLeastAverage {
public static int findMin(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num < candidate) candidate = num;
}
return candidate;
}
public static int findMax(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num > candidate) candidate = num;
}
return candidate;
}
public static double findAverage(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum / (double) numbers.length;
}
}
To make this code even better:
The min/max/average calculations above are not great, e.g. If you pass empty array to findAverage, then numbers.length will be 0 and you'll divide by 0. You should make those calculations better, see: #1, #2, #3.
Consider using ArrayList instead of array, when you need to dynamically change the size of the list during runtime (See Neil's answer).
Our assignment was to solve the Hackerrank question on arraylist without using 2D arrays or lists. Basically, you would need to input multiple arrays of different sizes and display an element based on the input of (array number, position). My implementation seemed to work just fine for my test cases but failed 4/6 of Hackerrank's test cases. Our lecturer's code (of course) worked perfectly. But what I fail to understand, is advantage of his approach:
My Code ::
import java.io.PrintStream;
import java.util.Scanner;
class arraylist {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int NoOfLines = sc.nextInt();
int[] input = new int[20000];//To store all input arrays one after the other in one 1D array.
int[] index = new int[NoOfLines];//Starting positions of each array input.
int[] NoOfArrayElements = new int[NoOfLines];//Sizes of each corresponding input array.
int position = 0;
int count = 0;
int arrayelementpos = 0;
//Store the input and note the size of each array and the index position.
for (int i = 0; i < NoOfLines; i++) {
int arrarLength = sc.nextInt();
NoOfArrayElements[arrayelementpos++] = arrarLength;
index[position++] = count;
for (int j = 0; j < arrarLength; j++)
input[count++] = sc.nextInt();
}
//Code to input queries (array no, element position)
int NoOfQueries = sc.nextInt();
int[] result = new int[NoOfQueries];
int pos = 0;
for (int i = 0; i < NoOfQueries; i++) {
int arrayNo = sc.nextInt();
int element = sc.nextInt();
if ((arrayNo > NoOfLines) || element > NoOfArrayElements[arrayNo - 1]) {
System.out.println("ERROR!");
continue;
}
pos = index[arrayNo - 1] + element - 1;
System.out.println("THE ELEMENT IS ::" + input[pos]);
}
}
}
My lecturer's code ::
import java.io.*;
import java.util.*;
public class arraylistsolved {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Object [] store=new Object[n];
for(int i=0; i<n;i++){
int d=sc.nextInt();
int [] ar=new int[d];
for(int j=0;j<d;j++) {
ar[j]=sc.nextInt();
}
store[i]=ar;
}
int q=sc.nextInt();
for(int i=0;i<q;i++){
int array=sc.nextInt()-1;
int element=sc.nextInt()-1;
Object obj=store[array];
int [] retrieve = (int []) obj;
if(array>n||element>retrieve.length-1)
System.out.println("ERROR!");
else
System.out.println(retrieve[element]);
}
}
}
As mentioned, both the codes are working for small test cases, but mine breaks down for very large ones for some reason. You can try copy-pasting the code here: https://www.hackerrank.com/challenges/java-arraylist/problem
Working on building an array that can generate random integer values inside an array. It prints the random numbers but it prints it like this
[10][2][5][7][6][2][4][7][2][10][0]--->(down the side)--------> and want it to print like this [10,7,5,9,4,3,4,7,2,3] (one line).
public class ArrayLab
{
//array instance variable
private int[] array1 = new int[10];
//array constructor
public ArrayLab(int integer)
{
//class parameter = 10
int[] array1 = new int[]{integer};
}
public void initialize()
{
//allow randomization of numbers inside the array field.
System.out.println(Arrays.toString(array1));
//prints [0,0,0,0,0,0,0,0,0,0] which is ok
System.out.println();
for (int iteration = 0; iteration < array1.length; iteration ++)
{
Random number = new Random();
number.nextInt(10);
int n = number.nextInt(11);
int[] array1 = new int[]{n};
System.out.println(Arrays.toString(array1));
//prints down the side. Want on one line?
}
}
}
Just change
System.out.println(Arrays.toString(array1));
//new output
System.out.print(Arrays.toString(array1));
another way you can get this done is by using a for loop to iterate through the array in similar fashion
for( int i = 0; i < array1.length; i++ ){
System.out.print(array1[i]+" ");
}
for the random numbers
Random ran = new Random();
for( int i = 0; i < array1.length; i++ ){
int number = ran.nextInt((max - min) + 1) + min;
//insert the maximum and min values for your generator
array1[i] = number;
So I was tasked with asking the user to input 10 numbers into an array and then printing the numbers in order and reverse order using a tester class and not just the main.
I'm having problems with how to return the array that has been passed. Here's my code so far:
public class PrintIt
{
static int[] numbers = new int[10];
static int i = 0;
public static int PrintOrder()
{
System.out.println("\nList of numbers in order: \n");
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}
return ;
}
public static int PrintReverse()
{
System.out.println("\nList of numbers in reverse order: \n");
for (int i = numbers.length - 1; i >= 0; i--)
{
System.out.println(numbers[i]);
}
return ;
}
}
and the tester class:
import java.util.Scanner;
public class PrintItTester
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
int i = 0;
int[] numbers = new int[10];
System.out.println("\nPlease input " + 10 + " numbers.");
for (i=0; i < numbers.length; i++)
{
PrintIt.numbers[i] = input.nextInt();
}
System.out.print(PrintIt.PrintOrder());
System.out.print(PrintIt.PrintReverse());
}
}
When I run the code with numbers[i] in the return it reads i as being 0 and only outputs the first element in the array. I've looked for a long time and I can't figure this out.
I know, obviously, that there needs to be something returned, but whatever I put doesn't work. For example, when I try to return the array, numbers[i], it only returns the first element because the variable has a value of 0.
You have several problems in your code:
The declaration int[] numbers = new int[10]; in the main is useless. Remove it, and replace numbers.length with PrintIt.numbers.length
Your methods return ints, not arrays. Make them void, and call them without System.out.print.
Remove the unnecessary return statements from the PrintOrder and PrintReverse methods.
This should fix the problem (demo).