Reputation: 3
I'm completely new to Java, and doing some online courses. I was doing this task when the online instructions did the task under a single Main class. I was trying to do some testing as I like to try keep my main class simple and was wondering how I could go about bringing about different arrays and method from another class over to my main class.
import java.util.Scanner;
public class Arrays {
public static Scanner scan = new Scanner(System.in);
public static int[] getIntegers(int number) {
System.out.println("Please enter " + number + " numbers\r");
int[] entered = new int[number];
for(int i = 0; i < entered.length; i++) {
entered[i] = scan.nextInt();
}
return entered;
}
public static void printArray(int[] entered) {
for(int i = 0; i < entered.length; i++) {
System.out.println("Element " + i + ", typed value was " + entered[i]);
}
}
public static int[] sortIntegers(int[] entered) {
int[] sortedArray = new int[entered.length];
for(int i = 0; i < entered.length; i++) {
sortedArray[i] = entered[i];
}
boolean flag = true;
int temp;
while(flag) {
flag = false;
for(int i = 0; i < sortedArray.length - 1; i++) {
if(sortedArray[i] < sortedArray[i + 1]) {
temp = sortedArray[i];
sortedArray[i] = sortedArray[i + 1];
sortedArray[i + 1] = temp;
flag = true;
}
}
}
return sortedArray;
}
}
And my Main class.
public class Main {
public static void main (String[] args) {
int[] myIntegers = getIntegers(5);
int[] sorted = sortIntegers(myIntegers);
printArray(myIntegers);
printArray(sorted);
}
}
IntelliJ allows me to just import static className over but I want to try it without a method that just imports the class over by using OOP standards.
as you can see I want to bring over getIntegers, printArray, and sortIntegers.
Upvotes: 0
Views: 959
Reputation: 338654
Re-design your app to use objects.
main
method.To answer your query, “How do I bring over an Array from another class?”:
static
global variables.The problem is that you are not really thinking in terms of objects. You are basically doing procedural programming, writing methods as subroutines, and using static
variables as global variables. Such procedural programming is not necessarily a bad thing, at least not for simple little apps. But you are not learning OOP.
Tip: Avoid static
. By definition static
is not object-oriented. Its frequent use is usually a big warning sign that your OOP design is flawed.
For OOP, do not think about input -> processing -> output. Think about responsibilities, jobs to be done.
We have two main areas of responsibility here in your app: user-interface and managing state.
The part of your app that interacts with the user really does not care about how arrays are stored (in memory as an array, in memory as an ArrayList
, in a database, etc.). Nor does the UI part of the app care about what algorithm is used in sorting.
Likewise, the part of the app handling the arrays need not know anything about how to interact with the user. The state management does not care if the user is communicating via a console, a GUI desktop app, a web app, or a web service.
First a class to manage the state.
package work.basil.example.maths;
import java.util.Arrays;
import java.util.Objects;
public class NumbersJuggler
{
private final int[] numbersOriginal;
private final int[] numbersSorted;
public NumbersJuggler ( final int[] numbers )
{
this.numbersOriginal = Objects.requireNonNull( numbers );
this.numbersSorted = Arrays.copyOf( this.numbersOriginal , this.numbersOriginal.length );
Arrays.sort( this.numbersSorted );
}
public int[] getNumbersOriginal ( )
{
return Arrays.copyOf( this.numbersOriginal , this.numbersOriginal.length );
}
public int[] getNumbersSorted ( )
{
return Arrays.copyOf( this.numbersSorted , this.numbersSorted.length );
}
@Override
public String toString ( )
{
return "NumbersJuggler{" +
"numbersOriginal=" + Arrays.toString( numbersOriginal ) +
", numbersSorted=" + Arrays.toString( numbersSorted ) +
'}';
}
@Override
public boolean equals ( final Object o )
{
if ( this == o ) { return true; }
if ( o == null || getClass() != o.getClass() ) { return false; }
NumbersJuggler that = ( NumbersJuggler ) o;
return Arrays.equals( numbersOriginal , that.numbersOriginal ) && Arrays.equals( numbersSorted , that.numbersSorted );
}
@Override
public int hashCode ( )
{
int result = Arrays.hashCode( numbersOriginal );
result = 31 * result + Arrays.hashCode( numbersSorted );
return result;
}
}
Notice how that NumbersJuggler
class knows nothing about interacting with a user. Its job is to hold a collection of numbers, and sort those numbers. We could later rewrite this class to use ArrayList
internally rather than a mere array, and the rest of our app would not break, would not care in the least.
Also notice how the getter methods use return Arrays.copyOf
to return a copy of the arrays. We do not want other classes to have access to manipulating the content being managed by the NumbersJuggler
class.
Next we need a class for the user-interface. Its only tasks:
package work.basil.example.maths;
import java.time.Instant;
import java.util.Scanner;
public class NumbersConsoleUI
{
private final Scanner scanner;
private final int countOfNumbers;
public NumbersConsoleUI ( final Scanner scanner , final int countOfNumbers )
{
this.scanner = scanner;
this.countOfNumbers = countOfNumbers;
}
public int[] gatherNumbers ( )
{
System.out.println( "Please enter " + this.countOfNumbers + " numbers:" );
int[] numbers = new int[ this.countOfNumbers ];
for ( int index = 0 ; index < numbers.length ; index++ )
{
numbers[ index ] = scanner.nextInt();
}
return numbers;
}
public void reportOriginalNumbers ( final int[] numbersOriginal )
{
for ( int index = 0 ; index < numbersOriginal.length ; index++ )
{
int ordinal = index + 1;
System.out.println( "Element # " + ordinal + ", typed value was " + numbersOriginal[ index ] );
}
}
public void reportSortedNumbers ( final int[] numbersSorted )
{
for ( int index = 0 ; index < numbersSorted.length ; index++ )
{
int ordinal = index + 1;
System.out.println( "Element # " + ordinal + ", sorted value was " + numbersSorted[ index ] );
}
}
public void reportAppEnding ( )
{
System.out.println( "App ending at " + Instant.now() );
}
}
Notice how that NumbersConsoleUI
class knows nothing about how numbers are stored, and knows nothing about sorting algorithms.
Lastly, we need an app class to pull this all together. Its job is to instantiate the other parts of our app (state manager, and UI).
This app class acts like the conductor of an orchestra, signaling the various instrument players when to play their part. And just like a conductor need not know the intricacies of the reed within the oboe, this app class need not know about the intricacies of storing and sorting numbers nor the intricacies of how to interact with a console. Just like a conductor relies on the oboist to manage their oboe, the app class relies on the NumbersJuggler
& NumbersConsoleUI
classes to each manage their own details.
package work.basil.example.maths;
import java.util.Objects;
import java.util.Scanner;
public class NumbersApp
{
public static void main ( String[] args )
{
Scanner scannner = new Scanner( System.in );
int countOfNumbers = 5;
NumbersConsoleUI ui = new NumbersConsoleUI( scannner , countOfNumbers );
int[] numbers = ui.gatherNumbers();
NumbersJuggler numbersJuggler = new NumbersJuggler( numbers );
ui.reportOriginalNumbers( numbersJuggler.getNumbersOriginal() );
ui.reportSortedNumbers( numbersJuggler.getNumbersSorted() );
ui.reportAppEnding();
}
}
When run.
Please enter 5 numbers:
42
555
105
7
55
Element # 1, typed value was 42
Element # 2, typed value was 555
Element # 3, typed value was 105
Element # 4, typed value was 7
Element # 5, typed value was 55
Element # 1, sorted value was 7
Element # 2, sorted value was 42
Element # 3, sorted value was 55
Element # 4, sorted value was 105
Element # 5, sorted value was 555
App ending at 2022-11-12T09:49:47.231213Z
Upvotes: 0
Reputation: 86
I recommend you to learn java modifiers. It will be helpful to you for your future. In this case. you can use instance method instead of static method. example :-
public class Main {
public static void main(String[] args) {
Arrays arrays = new Arrays();
int[] myIntegers = arrays.getIntegers(5);
int[] sorted = arrays.sortIntegers(myIntegers);
arrays.printArray(myIntegers);
arrays.printArray(sorted);
}
}
class Arrays {
public static Scanner scan = new Scanner(System.in);
public int[] getIntegers(int number) {
System.out.println("Please enter " + number + " numbers\r");
int[] entered = new int[number];
for(int i = 0; i < entered.length; i++) {
entered[i] = scan.nextInt();
}
return entered;
}
public void printArray(int[] entered) {
for(int i = 0; i < entered.length; i++) {
System.out.println("Element " + i + ", typed value was " + entered[i]);
}
}
public int[] sortIntegers(int[] entered) {
int[] sortedArray = new int[entered.length];
for(int i = 0; i < entered.length; i++) {
sortedArray[i] = entered[i];
}
boolean flag = true;
int temp;
while(flag) {
flag = false;
for(int i = 0; i < sortedArray.length - 1; i++) {
if(sortedArray[i] < sortedArray[i + 1]) {
temp = sortedArray[i];
sortedArray[i] = sortedArray[i + 1];
sortedArray[i + 1] = temp;
flag = true;
}
}
}
return sortedArray;
}
}
Upvotes: 0
Reputation: 179
You can have the Main class inherit the Arrays class by using the extends but Java doesn't allow multiple inheritance so you wouldn't be able to extend any other classes. Aside from the fact that inheritance should be done where the parent and child class share a logical relationship.
Instead you can create a generic interface and the Arrays class can implement all the methods that you already have in there. Then the Main class can implement the interface (i.e. IterableInterface) and you can even specify which concrete type you're using and what ivars it should contain, but that's more work than what you're probably trying to achieve.
Honestly, importing a class like is no problem. Often times you will find that the disadvantage of OOP is that inheritance in cases where composition or aggregation should be used. This is not applicable in this case because an import is more appropriate but be aware of it.
Upvotes: 1