Initialization of 2-D Arrays using Constructors in Java [duplicate] - java

This question already has answers here:
Syntax for creating a two-dimensional array in Java
(13 answers)
2D array Null Pointer Exception error
(2 answers)
Closed 4 years ago.
Matrix.java
import java.io.*;
class Matrix {
private int q[][];
public Matrix() {
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
q[i][j] = Integer.parseInt(System.console().readLine());
}
public Matrix( int a , int b ) {
int mat[][] = new int [a][b];
for(int i=0; i<mat.length; i++) {
for(int j=0;j<mat[i].length;j++)
q[i][j] = Integer.parseInt(System.console().readLine());
}
}
public void show() {
for(int i=0; i<q.length; i++) {
for(int j=0;j<q[i].length;j++)
System.out.println(q[i][j]+" ");
}
}
}
UseMatrix.java
class UseMatrix {
public static void main(String args[]) {
Matrix m1 = new Matrix();
System.out.println("First Matrtix ");
m1.show();
Matrix m2 = new Matrix(5,4);
System.out.println("Second Matrtix ");
m2.show();
}
}
This programs shows NullPointerException error at runtime
Confused why this isn't working could use a little help, I want to the create a 2D Array of Size 3*3 through Default Constructors.
Then I want to create a Array of size 5*4 using parameterized constructors.

There are a number of problems:
First: private int q[][]; // this holds a null value, never assigned on the parameterless constructor. A possible solution to this would be to add in your constructor: q[][] = new int[a][b]; and q[i] = new int[b];// each time you enter the loop. See the code below for clarity.
Second in public Matrix() { you try to access the array contents without checking its length (for(int i=0;i<3;i++) goes from 0 to 3, regarles of the actual array size). The array is empty at the beggining so this causes another NullPointerException here q[i][j] = Integer.parseInt... (I will solve this reusing the other constructor because they want to achieve the same result)
Third there is problems reading from console(), so I changed that too. (And added a line where you ask the user for a number)
And the last change I made was a small tweak to the show method.
Result:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class App {
public static void main(String[] args) {
Matrix m1 = new Matrix();
System.out.println("First Matrtix ");
m1.show();
Matrix m2 = new Matrix(5,4);
System.out.println("Second Matrtix ");
m2.show();
}
}
class Matrix {
private int q[][];
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public Matrix() {
this(3, 3);
}
public Matrix(int a, int b ) {
int value;
System.out.println("Input a number to fill the new 3x3 matrix");
try {
value = Integer.parseInt(br.readLine());
} catch (IOException e) {
throw new RuntimeException("There was a problem reading the number from console", e);
}
q = new int[a][b];
for(int i=0;i<a;i++) {
q[i] = new int[b];
for(int j=0;j<b;j++) {
q[i][j] = value;
}
}
}
public void show() {
for(int i=0; i<q.length; i++) {
for(int j=0;j<q[i].length;j++)
System.out.print(q[i][j]+" ");
System.out.print("\n");
}
}
}

Related

NullPointerException when getting elements from Array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to print out the names of the employees and their department and location from a list of the names and id numbers and I keep getting the NullPointerException even though it prints all of the names and locations. It then stops the build and doesn't xecute the print department and print location methods.
I've tried re-doing the for loops and seeing if any one data point was the problem but it seems to happen if I do the loop for all of the Employee objects or if I just do one.
package homework5_parth_desai;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
*
* #author Party Parth
*/
public class Homework5_Parth_Desai {
public static int emplIndex = -1;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
File file = new File("acmeEgr.txt");
Scanner scan = new Scanner(file);
Employee[] emp = new Employee[50];
String s = "";
String t = "";
int r = 0;
while (scan.hasNextLine()) { //scans in file
emplIndex++;
emp[emplIndex] = new Employee();
if (scan.hasNextLine() == true) { //takes first line as first name, second as last naem and third as id number and tehn ccreates an object out of that
s = scan.nextLine();
}
if (scan.hasNextLine() == true) {
t = scan.nextLine();
}
if (scan.hasNextLine() == true) {
r = Integer.parseInt(scan.nextLine());
}
emp[emplIndex].Employee(s, t, r);
// TODO code application logic here
}
printAll(emp);
printDepartment("IT", emp);
printLocation("Auburn Hills", emp);
}
static void printAll(Employee[] ppl) {
for (int i = 0; i < ppl.length; i++) {
System.out.println(ppl[i].toString());
}
}
static void printDepartment(String title, Employee[] ppl) {
for (int i = 0; i < ppl.length; i++) {
if (title.equals(ppl[i].getDept())) {
System.out.println(ppl[i].getName() + " is in " + ppl[i].getLocation());
}
}
}
static void printLocation(String loc, Employee[] ppl) {
for (int i = 0; i < ppl.length; i++) {
if (loc.equals(ppl[i].getLocation())) {
System.out.println(ppl[i].getName() + " is in " + ppl[i].getDept());
}
}
}
}
Small exert of the .txt file:
Alexander
Seiber
10010
Zehua
Showalter
20010
Cassidy
Woodle
20030
Randall
Shaukat
10030
Pam
Korda
10020
Justin
Polito
20030
public static int emplIndex = -1;
Why is the index maintained as a static field? Don't do that.
Employee[] emp = new Employee[50];
The employee array has a fixed size of 50 elements, however
while (scan.hasNextLine()) {
this loop is based on the lines of the acmeEgr.txt file, which might be more than 50.
In that case, you'll get an ArrayOutOfBoundException first
emp[emplIndex] = new Employee();
or a NullPointerException after
emp[emplIndex].Employee(s, t, r);
Instead, if the lines are less then 50, this
for (int i = 0; i < ppl.length; i++) {
System.out.println(ppl[i].toString());
}
will still loop all the 50 elements, because
ppl.length = 50
Thus, this line
ppl[i].toString()
will throw a NullPointerException.
This is what happens if the elements are, for example, 40
System.out.println(ppl[0].toString());
System.out.println(ppl[1].toString());
System.out.println(ppl[2].toString());
System.out.println(ppl[3].toString());
...
System.out.println(ppl[40].toString()); // ppl[40] is null, NullPointerException!
ArrayList is a much easier array type to deal with. Try using it instead of a normal array, because then you don't have to deal with indexes.

Possible to create two different sized arrays/matrices from a file?

Basically, I'm trying to create two different sized 2D arrays from a text file that looks like this:
2
add
3 4
2 1 7 -10
0 5 -3 12
1 7 -2 -5
0 1 2 3
4 5 6 7
8 9 0 1
subtract
2 2
2 12
10 0
4 6
9 1
The 2 is the number of problems (add and subtract), the 3 and 4 are the number of rows and columns, and the numbers below it are the two separate matrices being filled into the 2D arrays. If I just stop there, this program works correctly:
class Matrices {
private Scanner fileReader;
private int rows;
private int columns;
int problems;
String method;
public Matrices(String file) throws FileNotFoundException {
this.fileReader = new Scanner(new FileInputStream(file));
problems = fileReader.nextInt();
method = fileReader.next();
if(method.equals("add")) {
rows = fileReader.nextInt();
columns = fileReader.nextInt();
}
}
public int[][] readMatrix() throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return result;
}
public int[][] add(int[][] a, int[][] b) {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
public void printMatrix(int[][] matrix) {
for ( int[] anArray : matrix ) {
for ( int anInt : anArray ) {
System.out.print(anInt+ " ");
}
System.out.println();
}
}
}
With this driver:
public class MatricesDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
Matrices matrixReader = new Matrices(filename);
int[][] a = matrixReader.readMatrix();
int[][] b = matrixReader.readMatrix();
System.out.println("Matrix 1: ");
matrixReader.printMatrix(a);
System.out.println();
System.out.println("Matrix 2: ");
matrixReader.printMatrix(b);
System.out.println();
System.out.println("Addition: ");
int[][] addition = matrixReader.add(a,b);
matrixReader.printMatrix(addition);
}
}
It creates and prints the matrices just fine, with no problems. However, whenever I try to create and print the next two matrices (the 2x2 arrays below subtract in the text file), it returns the following error:
Enter name of file:
data/Matrices.txt
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at baker.Matrices.readMatrix(Matrices.java:27)
at baker.MatricesDriver.main(MatricesDriver.java:15
My question is, what adjustments should I make so that the program recognizes that two of the 2D arrays are to be 3x4, and the two following are to be 2x2?
I would recommend decomposing your implementation into the following parts:
class Matrix - holds the values of one matrix from problem definition
class Problem - holds the operation and the two matrices from problem definition
The Matrix class could look like:
class Matrix {
private int[][] values;
public Matrix(int[][] values) {
this.values = values;
}
public int[][] getValues() {
return values;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Matrix [values=\n");
for (int i = 0; i < values.length; i++) {
sb.append("\t" + Arrays.toString(values[i]) + "\n");
}
sb.append("]");
return sb.toString();
}
}
The Problem class could be:
class Problem {
private String operation;
private Matrix first;
private Matrix second;
public Problem(String operation, Matrix firstMatrix, Matrix secondMatrix) {
this.operation = operation;
first = firstMatrix;
second = secondMatrix;
}
public String getOperation() {
return operation;
}
public Matrix getFirst() {
return first;
}
public Matrix getSecond() {
return second;
}
#Override
public String toString() {
return "Problem [\noperation=" + operation + ", \nfirst=" + first + ", \nsecond=" + second + "\n]";
}
}
Based on this, your "driver" class does the following:
Get the filename from user input
Read from file the number of problems and construct a list with this initial size
For the number of problems (i.e. 2) get the operation, rows, and colums and construct a new Problem object containing these information and put the Problem into the list ...
Here is one simple solution - still room for improvement here :-)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MatricesDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
List<Problem> problems = readProblems(filename);
System.out.println(problems);
keyboard.close();
}
private static List<Problem> readProblems(final String filename) throws FileNotFoundException {
Scanner fileReader = new Scanner(new FileInputStream(filename));
int numberOfProblems = fileReader.nextInt();
List<Problem> problems = new ArrayList<>(numberOfProblems);
for (int i = 1; i <= numberOfProblems; i++) {
problems.add(readProblem(fileReader));
}
fileReader.close();
return problems;
}
private static Problem readProblem(Scanner fileReader) throws FileNotFoundException {
fileReader.nextLine(); // go to next line
String operation = fileReader.nextLine(); // read problem operation
int rows = fileReader.nextInt(); // read number of rows
int columns = fileReader.nextInt(); // read number of columns
Matrix firstMatrix = readMatrix(rows, columns, fileReader);
Matrix secondMatrix = readMatrix(rows, columns, fileReader);
return new Problem(operation, firstMatrix, secondMatrix);
}
private static Matrix readMatrix(final int rows, final int columns, final Scanner fileReader) throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return new Matrix(result);
}
}
Tested with your input file.
HTH
You tried to structure your data?
you can use that:
properties-file
For create array or vector without a fixed size use arrayList, you can make a arrayList from a arrayList

How to solve "Cannot Make Static Reference to Non-Static Method" in a Java mastermind game? [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 7 years ago.
This question is based on my former question. How to add a "cheat" function to a Java mastermind game
I added the cheat function to my program, but it cannot compile because of "Cannot Make Static Reference to Non-Static Method"(the old codes works, you can check it through the link I post). Here are my new codes:
import java.util.*;
public class mm {
static int[] random;
public static void main(String[] args) {
System.out.println("I'm thinking of a 4 digit code.");
//update
mm m1 = new mm();
random = m1.numberGenerator();
int exact=0, close=0;
while(exact!=4){
int[] guess= m1.userinput(); //update
exact=0;
close=0;
for(int i=0;i<guess.length;i++){
if(guess[i]==random[i]){
exact++;
}
else if (random[i]==guess[0] || random[i]==guess[1] || random[i]==guess[2] || random[i]==guess[3]) {
close++;
}
}
if(exact==4){
System.out.println("YOU GOT IT!");
}
else{
System.out.println("Exact: "+exact+" Close: "+close);
}
}
}
public int[] userinput() {
System.out.print("Your guess: ");
Scanner user = new Scanner(System.in);
String input = user.nextLine();
//cheater
if (input.equals("*")) {
System.out.format("Cheater!Secret code is:");
for(int i=0;i<random.length;i++){
System.out.print(random[i]);
}
}
int[] guess = new int[4];
for (int i = 0; i < 4; i++) {
guess[i] = Integer.parseInt(String.valueOf(input.charAt(i)));
}
return guess;
}
public int[] numberGenerator() {
Random rnd = new Random();
int[] randArray = {10,10,10,10};
for(int i=0;i<randArray.length;i++){
int temp = rnd.nextInt(9);
while(temp == randArray[0] || temp == randArray[1] || temp == randArray[2] || temp == randArray[3]){
temp=rnd.nextInt(9);
}
randArray[i]=temp;
}
return randArray;
}
}
How to solve this?
You can't call a non-static method directly from a static method. in public static main(String [] args)
To do so, you should first create an object of the class.
try this at main method:
mm m1 = new mm();
random = m1.numberGenerator();
int [] guess = m1.userInput();
this should work
The other option would be to make userinput method static as well

Try/Catch exception so i can return an array value and print out an exception?

Hi i am writing a lottery method where the user has to enter in two numbers, n and k, as arguments. The lottery gets filled with a randomized queue that goes up to k. so if i put in k=10 the queue would hold 1,2,3,4,5,6,7,8,9,10. The argument n is the number of items that has to be removed randomly. so if i chose 3 then it could return 4,6,8 or it could be 1,3,10.
Now if n is greater than k it has to throw an error saying that there is not enough items in the queue to pull. So if i put n=5 and k=3, there are still 3 items in the queue but i can't select 5 from the queue because that's too many.
Now my problem is i have to return the items that are still in the queue. so n=5 and k=3 would return 1,3,2 or 2,3,1 and so forth. But i have to print an exception after i return that array. So far i am able to return the array but i can not get the try catch exception to work. Is there another method i can try that will return the array and then print out the exception after that so it looks like this:
%java Lottery 5 2 //calls the method with the arguments n=5 k=2
2 1 //still prints the items in the queue
java.lang.Exception: Not enough items in your queue. // returns the error as well
at Lottery.pickNumbers(Lottery.java:29) //dont pay attention to these line numbers, this was a test case given to us
at Lottery.main(Lottery.java:56)
Here's my code:
import java.util.*;
import java.math.*;
public class Lottery{
RandomizedQueue rq;
Random Rnum = new Random();
int [] Larray;
// constructs a Lottery class
public Lottery(){
}
// picks the numbers and store them in an array of integers
// int n: number of items to pick
// int k: maximum integer to be picked
public int [] pickNumbers(int n, int k) throws Exception{
rq = new RandomizedQueue();
int [] remainQueue = new int [k];
if(n>k)
{
for(int i=1; i<=remainQueue.length;i++)
{
rq.enqueue(i);
}
for(int i=0; i<remainQueue.length;i++)
{
remainQueue[i] = rq.dequeue();
}
return remainQueue;
}
for(int i =1;i<=k;i++)
{
rq.enqueue(i);
}
Larray = new int[n];
for(int i = 0;i< Larray.length;i++)
{
Larray[i] = rq.dequeue();
}
return Larray;
}
// Do not change main().
public static void main(String [] args) throws Exception{
if (args.length<2){
System.out.println("Please enter your input values.");
System.out.println("e.g. java Lottery [number of integers to pick] [Maximum integer to be picked]");
}else{
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
Lottery l = new Lottery();
try{
int [] picked = l.pickNumbers(n,k);
for (int i = 0; i< picked.length; i++){
System.out.print(picked[i]+" ");
}
System.out.println();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
For this purpose you need to create your own custom Exception.
Follow the Steps.
-> Create an class that Extends Exception
-> write your own exceptions and handling
Say,
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
throw new MyException ("Something happened")
Catch as:
catch (MyException e)
{
// something
}
Here in your case
if(n
Change your main method like below code. In case of no exception you will get Result as expected in case of exception jut get previously populated Array and display that. In this way you will get populated result as well as exception both.
import java.util.*;
import java.math.*;
public class Lottery{
RandomizedQueue rq;
Random Rnum = new Random();
int [] Larray;
// constructs a Lottery class
public Lottery(){
}
// picks the numbers and store them in an array of integers
// int n: number of items to pick
// int k: maximum integer to be picked
public int [] pickNumbers(int n, int k) throws Exception{
rq = new RandomizedQueue();
int [] remainQueue = new int [k];
if(n>k)
{
for(int i=1; i<=remainQueue.length;i++)
{
rq.enqueue(i);
}
for(int i=0; i<remainQueue.length;i++)
{
remainQueue[i] = rq.dequeue();
}
return remainQueue;
}
for(int i =1;i<=k;i++)
{
rq.enqueue(i);
}
Larray = new int[n];
for(int i = 0;i< Larray.length;i++)
{
Larray[i] = rq.dequeue();
}
return Larray;
}
// Do not change main().
public static void main(String [] args) throws Exception{
if (args.length<2){
System.out.println("Please enter your input values.");
System.out.println("e.g. java Lottery [number of integers to pick] [Maximum integer to be picked]");
}else{
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
Lottery l = new Lottery();
try{
int [] picked = l.pickNumbers(n,k);
for (int i = 0; i< picked.length; i++){
System.out.print(picked[i]+" ");
}
System.out.println();
}catch (Exception e){
int [] picked = l.Larray;
for (int i = 0; i< picked.length; i++){
System.out.print(picked[i]+" ");
}
System.out.println();
e.printStackTrace();
}
}
}
}
You can't. Doing it doesn't even make sense. Exceptions are used for Exceptional behaviour. From what I understand asking for more items than is in the queue, is expected behaviour (ie. You have a use case which says "return the remaining queue". Thus if you want to handle the error, you should simply do something like.
if (picked.length != k)
{
System.out.println("You are attempting to choose more numbers than there are items (left) in the pool");
}
Alternatively since you know up front the values n and K you could simply do some input validation
if (k>n)
{
System.out.println("The amount of available numbers is smaller than the amount of numbers you wish to draw.")
}
Also you should probably use a Set instead of an Array.
This is how I would do it. Complete working code:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Lottery {
public void pickNumbers (int n, int k, List<Integer> values)
throws Exception
{
RandomizedQueue <Integer> rq = new RandomizedQueue <Integer> ();
for (int i = 0; i < k; i++)
rq.enqueue (i);
if (n <= k)
{
for (int i = 0; i < n; i++)
values.add (rq.dequeue ());
}
else
{
for (int i = 0; i < k; i++)
values.add (rq.dequeue ());
throw new Exception ("N > K");
}
}
public static void main (String [] args)
{
int n = Integer.parseInt (args [0]);
int k = Integer.parseInt (args [1]);
Lottery l = new Lottery ();
List <Integer> picked = new ArrayList <Integer> (n);
try
{
l.pickNumbers (n, k, picked);
}
catch (Exception e)
{
e.printStackTrace();
}
for (int i = 0; i < picked.size (); i++){
System.out.print (picked.get (i) + " ");
}
System.out.println();
}
private static class RandomizedQueue <T> extends ArrayList <T>
{
private final Random r = new Random ();
public void enqueue (T x)
{
add (x);
}
public T dequeue ()
{
return remove (r.nextInt(size ()));
}
}
}
Try this approach:
Create a list in main()
Pass that list to pickNumbers()
Make pickNumbers() return void and add the results to the list instead.
When you run into an error, throw the exception
In main(), catch the exception. The list will then contain all the results that have been computed so far.
Alternatively, write your own exception which accepts the existing results as arguments. main() can then read them from the exception.
You can either return value of throw Exception from a method, both can not be done at once.
You can create custom Exception class and where you can keep your processed result and throw that if exception arise.
public class MyException extends Exception{
private int[] processedResult;
public MyException(String str,int[] result){
this.processedResult = result;
}
...
#override
public String toString(){
....
}
}
...
public int [] pickNumbers(int n, int k) throws MyException{
int[] larray = new int[n];
try{
...
}catch(Exception ex){
new MyException("...",larray );
}
}
You can create your own Exception type which overrides setMessage
or simple instead of e.printStackTrace() use e.getMessage()
You can't both throw an exception and return a value at the same time.
Take a step back and look at what you are trying to achieve. You need to return multiple values from your method - a list of numbers and a status - which would suggest to me returning a complex object containing these values instead of a plain int[]:
public class LotteryPick {
public int status;
public int[] numbers;
}
public LotteryPick pickNumbers(int n, int k) {
...
}
In reality I'd use a Set<Integer> for numbers, an enum for status, and probably getter/setters for the fields.
Alternatively, if you must throw an exception, create a custom exception class (... extends IllegalArgumentException ?) that also has an int[] field to hold the picked numbers. I wouldn't recommend this approach though and it's functionally equivalent to the above in any case.

trouble defining array locally and passing parameters to other methods

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.

Categories

Resources