trouble defining array locally and passing parameters to other methods - java

My assignment was to write a Java class that creates an array of integers, fills it with values, prints the unsorted values, sorts the values into ascending order, and finally prints the sorted values.
For the most part I have done that and my output is fine. However I have not been able to define the array locally within the main(), and pass it as a parameter to the other methods.
I try to define it as a static member of the class which cannot be done.
Can anyone help me out? I need to define the array in the main() and pass it as a parameter to the methods. But I just cannot figure it out despite tireless research.
Here is what I have so far.
public class ArraySort {
private static Object sc;
int[] array;
// creates question and int for user input
/**
*
*/
public void fillArray() {
Scanner keyboardScanner = new Scanner(System.in);
System.out.println("Enter the size of the array (3 to 10): ");
int n = keyboardScanner.nextInt();
array = new int[n];
// creates new question by including int
System.out.println("Enter " + n + " values" );
// creates for loop for repeating question based on array size
for (int i=0; i<n; i++) {
System.out.println("Enter value for element " + i + ": ");
array[i] = keyboardScanner.nextInt();
}
}
// prints i in the for loop
public void printArray(String msg) {
System.out.println(msg);
for (int i=0; i<array.length; i++) {
System.out.println(array[i]);
}
}
// defines method
public void sortArray() {
// sets up to output in ascending order
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
// main output and visual layout
public static void main(String[] args) {
ArraySort arraySort = new ArraySort();
arraySort.fillArray();
System.out.println();
arraySort.printArray("The unsorted values... ");
arraySort.sortArray();
System.out.println();
arraySort.printArray("The sorted values... ");
// Keep console window alive until 'enter' pressed (if needed).
System.out.println();
System.out.println("Done - press enter key to end program");
}
}
I have no errors, I just need help on how to define the array locally in the main()
Thanks.

Remove the int[] array; declaration from the class. Add it to the main method:
int[] array = new int[n];
And add an argument int[] array to each method which needs to access it. For example:
public void printArray(String msg, int[] array) {
...
}

You can declare your array locally in your main method. And pass it as a parameter to the method you are calling.
Since when you pass array as parameter to another method, its reference will be copied to the parameter. So any change you make to passed array in your method, will get reflected back in your main() method in your original array. Try using this. I don't think you will face any problem.
UPDATE: - Ok, here's the modified code: -
import java.util.Scanner;
public class ArraySort {
private static Object sc;
private static Scanner keyboardScanner = new Scanner(System.in);
// creates question and int for user input
/**
*
*/
public void fillArray(int[] array) {
// creates for loop for repeating question based on array size
for (int i=0; i<array.length; i++) {
System.out.println("Enter value for element " + i + ": ");
array[i] = keyboardScanner.nextInt();
}
}
// prints i in the for loop
public void printArray(String msg, int[] argsArray) {
System.out.println(msg);
for (int i=0; i<argsArray.length; i++) {
System.out.println(argsArray[i]);
}
}
// defines method
public void sortArray(int[] array) {
// sets up to output in ascending order
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
// main output and visual layout
public static void main(String[] args) {
System.out.println("Enter the size of the array (3 to 10): ");
int n = keyboardScanner.nextInt();
int[] array = new int[n];
ArraySort arraySort = new ArraySort();
arraySort.fillArray(array);
System.out.println();
//I still get an error saying " cannot find symbol"
arraySort.printArray("The unsorted values... ", array);
//same here
arraySort.sortArray(array);
System.out.println();
//and here
arraySort.printArray("The sorted values... ", array);
// Keep console window alive until 'enter' pressed (if needed).
System.out.println();
System.out.println("Done - press enter key to end program");
}
}

Update public void printArray(String msg) { and public void sortArray() { to accept int [] as
/ prints i in the for loop
public void printArray(String msg, int[] argsArray) {
System.out.println(msg);
for (int i=0; i<argsArray.length; i++) {
System.out.println(argsArray[i]);
}
}
// defines method
public void sortArray(int[] argsArray) {
// sets up to output in ascending order
for (int i=0; i<argsArray.length; i++) {
for (int j=i+1; j<argsArray.length; j++) {
if (argsArray[i] > argsArray[j]) {
int temp = argsArray[i];
argsArray[i] = argsArray[j];
argsArray[j] = temp;
}
}
}
}
And you may want to leave array = new int[n]; in fillArray as local as:
int[] array = new int[n];
and remove it from class variable declaration.

You've said that you need to define the array in the main() and pass it as a parameter to the methods. If so, then you'll need to change those methods, e.g.:
public void printArray(String msg, int[] argsArray)
public void sortArray(int[] array)
fillArray is different, because you create the array in the method based on a size which is input by the user, so you can't simply pass the array as an argument. You can return the new array:
public int[] fillArray()
{
int[] array;
// ...
return array;
}
But if you're only trying to test your class then note that you have access to the ArraySort.array field from main: you can set the field to an array that you create in main.
So in main:
ArraySort arraySort = new ArraySort();
arraySort.array = new int[]{ 5, 4, 3, 6, 7};
// and remove the fillArray call
// ...
Note that if you want to set the array like this, then you should also remove the fillArray call, which tries to set the array from user-entered values.

Related

Scope of the array:

Here I am trying to find the max and min number entered into the array so I'm using a min and a max method(not declared yet) but I'm not quite sure how to access my array in these methods as the array userArray and array are not in the scope of the method and can't be accessed. can someone help me out?
package edu.skidmore.cs106.lab07.problem1;
import java.util.Scanner;
public class numberArray {
//Method to take user input
public int[] getUserData() {
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
// Create variable to store user's desired number of values
int totalNumbers = keyboard.nextInt();
// Declare and initialze an array
int[] userArray = new int[totalNumbers];
// Create a loop to ask for values from the user
// Within the loop, store user input in the array
for (int x = 0; x < totalNumbers; ++x) {
System.out.println("Enter number " + x);
int userInput = keyboard.nextInt();
userArray[x] = userInput;
}
return userArray;
}
public int minNumber() {
for (int y : array)
}
public static void main(String[] args) {
numberArray instance = new numberArray();
int array[] = instance.getUserData();
for (int element: array){
System.out.println(element);
}
}
}
public int minNumber(int[] userDataArray) {
// use userDataArray here
}
...
public static void main(String[] args) {
numberArray instance = new numberArray();
int[] userDataArray = instance.getUserData();
int min = instance.minNumber(userDataArray); // pass userDataArray as argument
}

Conflicting method parameters

This is a portion of the client provided by my prof and I'm not allowed to make changes to it.
public static void print (String title, int [] anArray) {
System.out.print(title + ": ");
for (int i = 0; i < anArray.length; i++) {
System.out.print(anArray[i] + " ");
}
System.out.println();
}
public static void main (String [] args) {
System.out.println("\nTesting constructor");
ScoreList list1 = new ScoreList(13);
System.out.println("\nTesting accessor (getter)");
int[] list1_array = list1.getScores();
System.out.println("\nTesting toString");
System.out.print("list1: " + list1);
System.out.println("\nTesting our print method");
print("list1's array", list1_array);
ScoreList list2 = new ScoreList(list1_array);
System.out.println("\nTesting list1 and list2");
System.out.println("list1: " + list1);
System.out.println("list2: " + list2);
System.out.println("\nTesting equals");
System.out.println("It is " + list1.equals(list2)
+ " that list1 is equal to list2");
if (!list1.equals(list2)) {
System.out.println("Error. The equals method does not work correctly");
System.exit(1);
}
This is a portion of my code that I wrote that will be tested by this client:
int [] scores;
public ScoreList(int size) {
if (size >= 1) {
this.scores = new int [size];
for(int i = 0; i < this.scores.length; i++) {
this.scores[i] = random(100);
}
}
else {
System.out.println("Length of array must be greater than or equal to 1.");
}
}
public ScoreList(int [] size) {
if (size.length >= 1) {
this.scores = new int [size.length];
for(int i = 0; i < this.scores.length; i++) {
this.scores[i] = random(100);
}
}
}
private int random(int randomAmount) {
Random rand = new Random();
int randomNumber = rand.nextInt(randomAmount);
return randomNumber;
}
public int [] getScores() {
int [] temp = new int [scores.length];
for(int i = 0; i < scores.length; i++) {
temp[i] = this.scores[i];
}
return temp;
}
The error here is that list1 and list2 will never be equal because I have 2 constructors, one that accepts int as a parameter and one that accepts int []. They both call random() simultaneously to provide the elements for list1 and list2. To make them equal, I think there should only be one constructor, so random() will only be called once. However, the parameters conflict. You see, according to the client, list1's parameter is 13, an int; list2's parameter is an int[].
This is the instruction I got from my prof on how to create the constructor for this class:
A constructor with just one parameter, the size of this object’s scores array, which must
be ≥ 1. It creates an array of the supplied size and the then fills that array with random
integers between 0 and 100, inclusive.
I don't know exactly what you want, but I think you just create the function creating new array from the other.
The second constructor could be like below.
public ScoreList(int[] array) {
// If you have to check array size, do it in here.
this.scores = new int[array.length];
for(int i=0;i<array.length;i++) {
this.scores[i] = array[i];
}
}
or If there should be only one constructor, please make it as a function.

How to put command line args into an array method?

I need to create class that has a setter to assign values to an array, then in the main method take command line arguments and use the method to put that in an array. I have no clue how to do this. Any help would be appreciated.
import java.util.*;
public class Number{
private double [] number = new double[3];
private double value ;
private int i;
public double[] getNumber() {
return sweet;
}
public void printNumber() {
System.out.println("Array " + Arrays.toString(number));
}
public double getValue(int i) {
return this.i;
}
public void setMethod(int i, double value) {
this.value = value;
this.i = i;
}
public class Score {
public static void main (String [] args) {
Number score = new Number();
// code to get values from keyboard into the array
edit: Thank you for your help I managed to create the new array. Now I need to be able to change the array value. In my setMethod I am guessing I need to change it to something like this..,
public void setMethod(int i, double value { //
for ( i = 0; i < this.array.length; i ++){
this.array[this.i] =this. value;
}
this.mark = mark;
this.pos = pos;
}
If you look at main() method's list of arguments, you'll see String[] args - command line arguments are passed to the main() method as arguments. You can simply read them using a for loop:
String[] yourNewArray = new String[args.length]:
for(int i = 0; i< args.length; i++) {
yourNewArray[i] = args[i];
}
Now in yourNewArray you have stored command line arguments.
It is worth to mention that yourNewArray doesn't need to be an array containg Strings. Arguments passed as command line arguments can be parsed and used as, for example integers, doubles and other types of values.
Now, as you edited your question and have new thing to figure out, I will show you an example, how you could implement method to assign new array to an existing one and another method to change single value in this array:
import java.util.*;
// This is your class - there is String[] arr - you want to be able to change whole array or its single value:
class MyClass {
String[] arr;
// To change whole array:
public void setMethod(String[] array) {
this.arr = array;
}
// To change only one value in array:
public void changeSingleValue(int index, String value) {
arr[index] = value;
}
}
public class Test {
public static void main(String[] args) {
String[] arrayFromArgs = new String[args.length];
for(int i = 0; i < args.length; i++) {
arrayFromArgs[i] = args[i];
}
MyClass obj = new MyClass();
// In this method you assign array storing command line arguments to the array in MyClass:
obj.setMethod(arrayFromArgs);
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Here is an example of assigning another array to obj.arr:
String[] anotherArray = { "A", "B", "C", "D"};
obj.setMethod(anotherArray);
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Here is another way to assign new values to obj.arr:
obj.setMethod(new String[]{"x", "y", "z"});
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Simple example how to change single value in obj.arr by passing the index where and value that needs to be changed:
obj.changeSingleValue(1, "Changed");
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
}
}
And the output of the above program:
obj.arr: [] // in this array you will see values passed as the command line arguments
obj.arr: [A, B, C, D]
obj.arr: [x, y, z]
obj.arr: [x, Changed, z]
Try something like the following code to copy your array:
public static void main (String [] args) {
// code to get values from keyboard into the array
String[] myArgs = new String[args.length];
for (int i = 0; i < args.length; i++) {
myArgs[i] = args[i];
}
// ...
}

How to make an Array Accessible from instantiation in main class? Accessible to all classes in same class

I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance

Swap array element in java in accending order

I'm trying to swap an array in ascending order but somewhere I'm going wrong. I'm taking input using
int n = Integer.parse.int(args[0]);
but it isn't working. Below is the full code.
package tech;
import java.util.*;
import java.io.*;
public class Techgig {
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Amount Mark has:");
int rs=50;//Integer.parseInt(args[0]);
//int a=0;
System.out.println(rs);
// for(int k=0;k<ta.length;k++)
//System.out.print("\t"+ ta);
int min,temp;
for(int i=0;i<ta.length;i++)
{
min=i;
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[i]<ta[min])
{
temp=ta[i];
ta[i]=ta[min];
ta[min]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
for(int k=0;k<ta.length;k++)
{
System.out.print("\t"+ ta[k]);
}
}
}
You should replace variable i with j here:
if(ta[i]<ta[min])
{
temp=ta[i];
ta[i]=ta[min];
ta[min]=temp;
}
Reason is you are comparing 'i'th index with itself which you assigned to min variable and hence it will never go in your if condition to swap.
You could resolve this as below by using i and j as index and checking between the two:
for(int i=0;i<ta.length;i++)
{
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[j]<ta[i])
{
temp=ta[j];
ta[j]=ta[i];
ta[i]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
Your logic of comparison is wrong.
Refer to the below code. Instead of applying so much logic. Why not just call upon sort method like below?
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
// print all the elements available in array
for (int number : ta) {
System.out.println("Number = " + number);
}
// sorting array
Arrays.sort(ta);
System.out.println("The sorted int array is:");
for (int number : ta) {
System.out.println("Number = " + number);
}

Categories

Resources