How to import Java file method to another Java file? - java

I have two Java files, one called Assign_2 and another called ArrayMath. I want to allow ArrayMath's methods to be used in Assign_2 like so:
ArrayMath.arrayAddition(a, b); //Called ArrayMath from Assign_2.java
What code allows ArrayMath.java methods to be used in Assign_2.java?
public class Assign_2 {
/**
* Main method to execute whole code.
*
* #param theArgs is used to keep consistency
*/
public static void main(String[] theArgs) {
Scanner input = null; // For file input
PrintStream output = null; // For file output
String inFileName = "in2a.txt"; //Input file and outputs
String outFileName = "out.txt";
boolean filesOk = false; // Checks for files to be accessed
int[][] a = null; // Declaring the 4 arrays for operations
int[][] b = null;
int[][] c = null;
int[][] d = null;
// Opens file for input and readys for output
try {
input = new Scanner(new File(inFileName));
output = new PrintStream(new File(outFileName));
filesOk = true;
}
catch (FileNotFoundException e) {
System.out.println("Can't open file - " + e);
}
if (filesOk) {
a = get2DArray(input);
b = get2DArray(input);
c = get2DArray(input);
d = get2DArray(input);
// Sanity check for what is in the array and if right
//System.out.println(Arrays.deepToString(a));
//System.out.println(Arrays.deepToString(b));
//System.out.println(Arrays.deepToString(c));
//System.out.println(Arrays.deepToString(d));
// Calling to ArrayMath.java for operation results
// Declaring arrays for final results
int[][] sum = ArrayMath.arrayAddition(a, b);
System.out.println(Arrays.deepToString(sum));
//int[][] difference = ArrayMath.arraySubtraction(a, b);
//int[][] multiplication = ArrayMath.arrayMultiply(a, b);
}
}
/**
* get2DArray reads input file then creates 2D array
* from the file.
*
* #param input is a Scanner to input the file
*
* #return a 2D integer array filled with input values
*/
public static int[][] get2DArray(Scanner theIn) {
int rowSize = theIn.nextInt(); // Takes the first 2 numbers
int colSize = theIn.nextInt(); // that provided column + row #'s
int[][] a = new int[rowSize][colSize]; // New array with ^ #'s
// For loops that add integers to arrays
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a[i].length && theIn.hasNextInt(); k++) {
a[i][k] = theIn.nextInt();
}
}
return a; // Returns value to main method that was called from
}
}
And ArrayMath.java is:
public class ArrayMath {
/**
* Addition for 2D Arrays method
*
* #param theA and theB are 2D arrays from Assign_2
*
* #return sum to Assign_2 main program
*/
public static int[][] arrayAddition(int[][] theA, int[][] theB) {
int[][] sum = new int[theA.length][theA.length];
for (int i = 0; i < theA.length; i++) {
for (int k = 0; k < theA[i].length; k++) {
sum[i][k] = theA[i][k] + theB[i][k];
}
}
return sum;
}
}

What you need is to define the method(s) in ArrayMath as public and static, e.g.:
public static void arrayAddition(int a, int b)
{
// do something
}

Define the method in you want to import ArrayMath.java as static.
Assume the wrapper class is just called ArrayMath, make it a public method and then from Assign_2 do import ArrayMath.
refer to the method like ArrayMath.yourMethod().

Call the method after you create an object for ArrayMath class:
ArrayMath ob = new ArrayMath();
Then call the method in Assign_2 class asfollowing
ob.arrayAddition(a, b);
Make sure the method is public.

What all you have to do is to create an object from ArrayMath and use the method declared inside Assign_2
E.g:
ArrayMath obj = new ArrayMath();
obj.arrayAddition(a, b);
Read more about creating objects in Java

There are multiple ways
1. inheritance is-a relationship
2. composition has-a relationship - but in case of has-a relationship you have to made public and static to your method to call from another class.

Related

copy a 2d array of type int from a file in java

I am trying to load a 2d int array that I loaded into a file in a previous method of my code. When i reach the method LoadFromFile, I can't seem to get my head around how I should implement this back to my Course class and add it back to the Map that was declared in the class. This is the code i have at the moment with the instructions my professor has given us and my attempt to try and figure this out. At this point i was pretty much doing nonsense stuff hoping it would trigger something to get this to work.
thanks in advance for any help or guidance!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.awt.Point;
import java.awt.Dimension;
public class TileMap implements Loadable
{
private Dimension Size;
private int[][] Map;
public TileMap(int NewWidth, int NewHeight)
{
Size = new Dimension(NewWidth, NewHeight);
Map = new int[NewWidth][NewHeight];
}
// accessors and mutators for Size
public Dimension GetSize()
{
return Size;
}
public void SetSize(int NewWidth, int NewHeight)
{
Size = new Dimension(NewWidth, NewHeight);
Map = new int[NewWidth][NewHeight];
}
// accessor and mutator for Map
public int[][] GetMap()
{
return Map;
}
public void SetMap(int[][] NewMap)
{
// copy the reference
Map = NewMap;
}
/**
* Loads a TileMap from a file. The first line of the file will have the width, the
* first dimension of the array. The second line will have the height, the second
* dimension of the array. Then the values in the array should follow as demonstrated
* below.
*
* Example:
* 6\n
* 6\n
* 2,1,1,0,0,2\n
* 0,0,1,0,0,1\n
* 0,0,1,0,0,1\n
* 0,2,1,0,0,1\n
* 0,0,1,1,1,1\n
* 0,0,1,0,0,1\n
*
* #param Filename the file to load from
* #return the empty string "" if the load succeeds, or the exception message if it fails
*/
public String LoadFromFile(String Filename)
{
try
{
File nf = new File(Filename);
Scanner in = new Scanner(nf);
String text = "";
int x =0;
//load file and assign all scans
//to respected properties within class
while(in.hasNextLine())
{
text = in.nextLine() + "\n";
}
int w = Integer.parseInt(text[0]);
int h = Integer.parseInt(text[1]);
SetSize(w,h);
int[][] newMap = null;
int k = 2;
for(int i = 0; i < GetSize().width;i++)
{
for(int j = 0; j < GetSize().height; j++)
{
newMap[i][j] = Integer.parseInt(text[k]);
k++;
}
}
SetMap(newMap);
in.close();
}
catch(FileNotFoundException e)
{
return Filename + " (No such file or directory)";
}
catch(Exception f)
{
f.getStackTrace();
}
return "";
}
I see you're in CS 49J. Here's how we did it,
public String LoadFromFile(String Filename)
{
// YOUR CODE HERE
try
{
File inFile = new File(Filename);
Scanner inText = new Scanner(inFile);
inText.useDelimiter("[\\s,\r\n]+");
int tempW = inText.nextInt();
int tempH = inText.nextInt();
SetSize(tempW, tempH);
for (int i = 0; i < tempW; i++)
{
for (int j = 0; j < tempH; j++)
{
if (inText.hasNextInt())
{
int temp = inText.nextInt();
Map[i][j] = temp;
}
}
}
inText.close();
return "";
}
catch (Exception e)
{
String dir = " (No such file or directory)";
return Filename + dir;
}
}
Make sure to check your Map.tm between method calls so you have the right information in there.
It's fairly easy and you started in the right direction.
You read the two lines assign them to width and height which you've done.
What you did wrong was the following, you shouldn't read the whole file at once, read the first two lines parse them into numbers. You will know how much more lines you will have to read (it's w)
If you know how many lines there will be you have to do the following w times:
read the next line
parse the next line (split it on the comas) into a string array (java will do this with string.split)
iterate through the string array, convert each of the variables into numbers then put them into the corresponding array elements
also your newMap is null, you should initialize it to new int[w][h]
If values in the file are look like in your comment:
* Example:
* 6\n
* 6\n
* 2,1,1,0,0,2\n
* 0,0,1,0,0,1\n
* 0,0,1,0,0,1\n
* 0,2,1,0,0,1\n
* 0,0,1,1,1,1\n
* 0,0,1,0,0,1\n
You should use the text variable as an array of strings.. The way you did resulted that, the text variable only contained the last line of your file.
String[] text = new String[];
int x = 0;
while(in.hasNextLine())
{
text[x++] = in.nextLine();
}
int w = Integer.parseInt(text[0]);
int h = Integer.parseInt(text[1]);
Then you also have problems with the lines above 2.. Each lines contains numbers separated by commas, so you have to split them by comma delimiter, then you can assign each value to the right dimensions of the newMap:
for (int i = 2; i <= text.length; i++) {
String[] temp = text[i].split(",");
for (int j = 0; j <= temp.length-1, j++) { //temp.length-1 is because the last string will be a number + "\n"
newMap[i-2][j] = Integer.parseInt(temp[j]);
}
newMap[i-2][temp.length] = Integer.parseInt(temp[temp.length].substring(0,1)); //taking care of the last string of the row
}
And you shouldn't point the newMap to null, instead use
int[][] newMap = new int[w][h];

How to write a intersection and union methods for sets in Java

I'm new to using sets and for one of the exercise to learn how to use sets, I have been given a template file "SetInt" and a completed test file "TestSetInt". I know that I should use retainAll() and addAll() but the test class has asked me to write methods. Anyone have any idea how to write these two methods? Any help would be appreciated.
SetInt is the file which I have to add methods to and goes as follows:
public class SetInt
{
int[] setArray = new int[52];
public void add(int a)
{
if (a < setArray.length-2)
{
setArray[a] = a;
}
}
/* add a to the set in the correct position
*#param a the value to be added
**/
public SetInt intersection(SetInt anySet)
{
return anySet;
}
/* returns the set of integers common to both
* the set passed in as an argument and the set the
* method is called on
* #param anySet - the set to be intersected
* #return a set containing the result of the intersection
*/
public SetInt union(SetInt anySet)
{
return anySet;
}
/* returns the set of integers which are in either the
* set passed in as an argument or the set the method
* is called on
* #param anySet - one of the sets in the union
* #return a set containing the result of the union
*/
}
Here is TestSetInt, a file provided for me which I have to run to see if my methods work correctly:
public class TestSetInt
{
public TestSetInt()
{
SetInt test1 = new SetInt();
SetInt test2 = new SetInt();
// adding numbers to the 2 sets
for(int i = 2; i<49;i=i+3)
{
test1.add(i);
}
System.out.println();
for(int i = 2; i<49;i=i+4)
{
test2.add(i);
}
System.out.println();
// testing intersection
SetInt interx = new SetInt();
interx=test2.intersection(test1);
// testing union
SetInt unionx = test1.union(test2);
}
public static void main (String args[])
{
TestSetInt practice = new TestSetInt();
}
}
this works :)
SetInt Class
public class SetInt {
int[] setArray = new int[52];
public void add(int a) {
if (a < setArray.length - 2) {
setArray[a] = a;
}
}
/*
* add a to the set in the correct position
*
* #param a the value to be added
*/
public SetInt intersection(SetInt anySet) {
SetInt temp = new SetInt();
for (int i = 0; i < setArray.length; i++) {
for (int j = 0; j < anySet.setArray.length; j++) {
if (setArray[i] == anySet.setArray[j]) {
temp.setArray[i] = setArray[i];
}
}
}
return temp;
}
/*
* returns the set of integers common to both the set passed in as an
* argument and the set the method is called on
*
* #param anySet - the set to be intersected
*
* #return a set containing the result of the intersection
*/
public SetInt union(SetInt anySet) {
SetInt temp = new SetInt();
for (int i = 0; i < setArray.length; i++) {
for (int j = 0; j < anySet.setArray.length; j++) {
temp.setArray[i] = setArray[i];
if (anySet.setArray[j] != 0) {
temp.setArray[j] = anySet.setArray[j];
}
}
}
return temp;
}
/*
* returns the set of integers which are in either the set passed in as an
* argument or the set the method is called on
*
* #param anySet - one of the sets in the union
*
* #return a set containing the result of the union
*/
}
TestSetInt
public class TestSetInt {
public TestSetInt() {
SetInt test1 = new SetInt();
SetInt test2 = new SetInt();
// adding numbers to the 2 sets
for (int i = 2; i < 49; i = i + 3) {
test1.add(i);
}
printSetInt(test1);
for (int i = 2; i < 49; i = i + 4) {
test2.add(i);
}
printSetInt(test2);
// testing intersection
SetInt interx = new SetInt();
interx = test2.intersection(test1);
printSetInt(interx);
// testing union
SetInt unionx = test1.union(test2);
printSetInt(unionx);
}
public void printSetInt(SetInt set) {
for (int i : set.setArray) {
System.out.print(i + ",");
}
System.out.println();
}
public static void main(String args[]) {
TestSetInt practice = new TestSetInt();
}
}

Generics and using newly created methods in a Class that implements Iterable Interface

I am working on a program that checks the validity of a sudoku solution. I am close to having it finished, but for some reason when I try to call certain methods I have created, the compiler returns that they are undefined.
There are three main classes:
A sudoku class, which implements the iterable interface. It contains a two dimensional array that is the puzzle. The constructor takes a file from scanner input and builds the puzzle. It has a iterator method to satisfy the interface requirements. This method returns an interator of type SudokuIterator.
A SudokuIterator class, which implements the Iterator Interface. This is a private inner class of the Sudoku class. It also has a 2 dimensional array and a cursor as attributes. It has the standard hasNext(), next(), and a remove() stub to satisfy the interface. I have also added a nextColumn() and nextBox() that return an array based on the cursor position. The next method has been overridden to return rows.
Finally is the Validator. This method is the main method. It has a method isSolution() that returns a boolean depending on analysis of each array returned from methods defined in the SudokuIterator Class.
And this is where my problems arise; when use the iterator method to instantiate and return a SudokuIterator and try to then use my added nextColumn() and nextBox() methods, the compiler returns that those methods are undefined for Iterator.
Any advice or suggestions would be much appreciated. Thanks in advance.
import java.util.*;
/**
* Sudoku class represents the matrix of cells in a Sudoku puzzle
* #version 01/05/2012
* #author Bob Wilson
*/
public class Sudoku implements Iterable<Cell []>
{
private Cell [] [] puzzle;
/**
* Default constructor should not be called. Make it private.
*/
private Sudoku() {}
/**
* Puzzle constructor that uses a Scanner object to read a file.
* File contains 81 numbers that are the values of the 81 cells.
* #param file a Scanner object on a File object
*/
public Sudoku(Scanner file)
{
int size = file.nextInt();
System.out.println("Size: " + size);
puzzle = new Cell[size][size];
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
puzzle[i][j] = new Cell(file.nextInt());
}
public int getLength(){
return this.puzzle.length;
}
class SudokuIterator implements Iterator<Cell []> {
private Cell [][] puzzle;
private int cursor;
public SudokuIterator(Cell [][] puzzle){
this.puzzle = puzzle;
cursor = 1;
}
public boolean hasNext(){
if(cursor <= this.puzzle.length){
return true;
}
return false;
}
public Cell[] next(){
Cell[] row = puzzle[cursor-1];
cursor++;
return row;
}
public Cell[] nextColumn(){
Cell[] column = new Cell[puzzle.length];
for(int i = 0; i < puzzle.length; i++){
column[i] = puzzle[i][cursor-1];
}
cursor++;
return column;
}
public Cell[] nextBox(){
Cell[] box = new Cell[puzzle.length];
int boxIndex = 0;
for(int i = ((cursor - 1)/((int)Math.sqrt(puzzle.length)))*(int)Math.sqrt(puzzle.length) ; i < ((cursor - 1)/((int)Math.sqrt(puzzle.length)))*(int)Math.sqrt(puzzle.length) + (int)Math.sqrt(puzzle.length); i++){
for(int j = (((cursor - 1) + ((int)Math.sqrt(puzzle.length))) % ((int)Math.sqrt(puzzle.length))) * ((int)Math.sqrt(puzzle.length)); j < (((cursor - 1) + ((int)Math.sqrt(puzzle.length))) % ((int)Math.sqrt(puzzle.length))) * ((int)Math.sqrt(puzzle.length)) + ((int)Math.sqrt(puzzle.length)); j++){
box[boxIndex] = puzzle[i][j];
}
}
cursor++;
return box;
}
public void remove(){}
}
/**
* Generates and returns a String representation of the puzzle cells
* #return A String representing the contents of the puzzle array
*/
public String toString()
{
// display the puzzle
String value = "Puzzle is:\n";
for (int i = 0; i < puzzle.length; i++) {
for (int j = 0; j < puzzle[i].length; j++)
value += puzzle[i][j].toString();
value += "\n";
}
return value;
}
/**
* Instantiates and returns a new SudokuIterator object
* #return A SudokuIterator object on the puzzle array
*/
public SudokuIterator iterator(){
SudokuIterator iterator = new SudokuIterator(this.puzzle);
return iterator;
}
}
/* 201340 */
import java.util.*;
import java.io.*;
/**
* This class instantiates a Sudoku object passing a Scanner on a
* file to the Sudoku constructor. It prints the puzzle using the
* Sudoku toString method. It determines if the digit matrix is a
* valid solution for a Sudoku puzzle or not and prints the result.
*
* #version 01/05/2012
* #author Bob Wilson
*
*/
public class SudokuValidator
{
private Sudoku puzzle;
/**
* #param args - not used
*/
public static void main( String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter name of file containing puzzle to verify");
SudokuValidator myValidator = new SudokuValidator(scan.nextLine());
System.out.println(myValidator.isSolution());
}
public SudokuValidator(String fileName)
{
Scanner file = null;
try
{
file = new Scanner(new File(fileName));
}
catch (Exception e)
{
System.out.println("Bad file name");
System.exit(0);
}
puzzle = new Sudoku(file);
System.out.println(puzzle);
}
public boolean isSolution(){
boolean flag = true;
Iterator<Cell[]> game = puzzle.iterator();
while(game.hasNext()){
Cell[] row = game.next();
Cell[] column = game.nextColumn();
Cell[] box = game.nextBox();
for(Cell i: row){
for(Cell j: row){
if(j.equals(i.getValue())){
flag = false;
return flag;
}
}
}
}
return flag;
}
} /* 201340 */
The issue is, the declared type of game reference variable is Iterator, which doesn't define any nextColumn() method, so compiler cannot find it. You can fix this by changing the declared type to Sudoku.SudokuIterator (Since that is an inner class).
Change:
Iterator<Cell[]> game = puzzle.iterator();
to:
Sudoku.SudokuIterator game = puzzle.iterator();

Looping through two arrays

I have two different arrays an ArrayList of doubles and an Array of Strings
public class tester {
private final static String TIME[]={ "8:00", "9:00", "10:00", "11:00",
"12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00" };
public static void main(String[] args){
ArrayList<Double> stat = new ArrayList<>();
stat.add(1.0);
stat.add(2.0);
stat.add(3.0);
stat.add(4.0);
stat.add(5.0);
stat.add(6.0);
stat.add(7.0);
stat.add(8.0);
stat.add(9.0);
stat.add(10.0);
stat.add(11.0);
stat.add(12.0);
int i = 0;
for (String time : TIME) {
System.out.println(time+" "+stat.get(i));
i++;
}
My question is quite simple is this the best way to loop through each array if I want to get the same position of each array to match? so that stat.get(0) ==TIME.get(0)?
Update
First of all thank you all for your quick response i like the idea of creating a class however there is something you need to know.
The thing you saw was a test class that i use to test my data.
i KNOW that the two arrays will ALWAYS be the same size due to the fact that the stat ArrayList normally defined like the following:
stat is a calculated value of data gained from the database the value of stat is based on time and then sent back to the GUI to be put into a graph and a table.
This means that for each of the TIME there is an exisiting value so that stat.get(0) is ALWAYS equal to TIME.get(0) == "8:00".
With this in mind do you still think i should create a class or should i keep the class showed below and then add a HashMap containing the data then iterate over that map to insert the data in my GUI?
public class Statistics {
private ArrayList<CallQueue> queues = new ArrayList<CallQueue>();
private ArrayList<Double> averageData = new ArrayList<Double>();
private Provider p;
public Statistics(){
try {
this.p = new Provider();
} catch (DopeDBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* This recursive method calculates the average of each time table and then adds its to the arrayList in the following order:
* 8.00 = 0
* 9.00 = 1
* 10.00 = 2
* 11.00 = 3
* 12.00 = 4
* 13.00 = 5
* 14.00 = 6
* ect.
* #param time
*/
public void calculateAverage(){
int data = 0;
for (int i = 8; i < 20; i++) {
for (CallQueue cq : queues) {
data += cq.getCallsByTime(i);
}
if (data == 0) {
Main.createErrorMessage("Fejl i dataen! \r\n kontakt venligst ansvarlige i Dope");
}
averageData.add((double) data/11);
}
}
/**
* #author MRCR
* This method recives the object list from the database and sets the currentlist to the list recived.
*/
public void setQueues(Calendar start, Calendar end){
try {
queues = p.getInformation(start, end, queues);
} catch (DopeDBException e) {
// TODO Auto-generated catch block
Main.createErrorMessage("Message");
} catch (DopeResultSetException e) {
// TODO Auto-generated catch block
Main.createErrorMessage("Message");
}
}
/**
* This method returns the calculated DataList list.
* #author MRCR
* #return averageData
*/
public ArrayList<Double>getData(Calendar start, Calendar end){
setQueues(start, end);
calculateAverage();
return averageData;
}
}
import java.util.HashMap;
public class CallQueue {
private String type;
private HashMap<Integer, Integer> data = new HashMap<Integer,Integer>();
public CallQueue(String type){
this.type = type;
}
public String getType(){
return type;
}
public int getCallsByTime(int time){
return data.get(time);
}
public void addCallsByTime(int hourOfDay, int callAmount) {
data.put(hourOfDay, callAmount);
}
}
I would first check that the lengths of the 2 arrays are the same.
Then iterate using a for loop:
final int timeLength = TIME.length;
if (timeLength != stat.size()) {
//something may not be right
}
for (int i = 0; i < timeLength; i++) {
System.out.println(time[i]+" "+stat.get(i));
}
for (int i = 0; i < TIME.length; i++) {
// use i to access TIME[i] and stat.get(i)
}
but you have to ensure that those arrays are of the same length
You would need to consider the length part also. You would only need to iterate upto the maximum length possible that covers both array, and list.
So, you can first find the lower length between them. And then iterate till that length: -
int lower = TIME.length < stat.size()? TIME.length: stat.size();
for (int i = 0; i < lower; i++) {
System.out.println(TIME[i] + " : " + stat.get(i);
}
Now that was the part of iterating over two arrays.
Now I would say, if you have to iterate over two arrays simultaneously, just make a class with the attributes, you have created arrays for.
So, create a class with attributes: - time, and stats. And then create a List<YourClass>. And iterate over the list of the class instances.
if (TIME.length!=stat.size()) {
// handle error
}
int count = stat.size();
for (int i=0; i<count; ++i) {
double d = stat.get(i);
String s = TIME[i];
}
However
As pointed out in a comment, you should define a class that will gather the information of both arrays.
For instance:
public class MyTime {
private double value;
private String label;
}
Or
In that particular case, I suspect you could use time formatting functions to replace your string array.
String.format("%1$d:00", (int) myDouble);

Method Scope of variables (java)

I have a class in java for methods. Basically this class receives an array of integer numbers, adds the numbers & subtracts them too, returns the sum and the subtraction. I declared the variables at the top (not in a particular method). When the subtraction and the addition are done they're assigned to their respective variables (automatically, of course), BUT when the method is finished doing its job the values are deleted, so when I call a method of the subtraction/addition the result is a 0.
As far as I know the values shouldn't be empty because they're not initialized inside a method but outside all methods, so the scope shouldn't have ended. Any help, please ?
//Class of the methods
package chap3;
import javax.swing.JOptionPane;
/**
*
* #author jtech
*/
public class SimpleArithmeticMethods
{
int sum;
int subtraction;
public void sum_Difference(int[] nums)
{
int[] inpNums = nums;
sum = inpNums[0] + inpNums[1];
subtraction = inpNums[1] - inpNums[0];
}
public void getSum()
{
JOptionPane.showMessageDialog(null,"The sum is: "+sum, "Result.", JOptionPane.INFORMATION_MESSAGE);
}
public void getDifference()
{
JOptionPane.showMessageDialog(null,"The difference is: "+subtraction, "Result.", JOptionPane.INFORMATION_MESSAGE);
}
}
The class from which I run
package chap3;
import javax.swing.JOptionPane;
/**
*
* #author jtech
*/
public class SimpleArithmetic
{
public static void main(String[] args)
{
String[] strInptNums = new String[2];
int[] inptNums = new int[2];
SimpleArithmeticMethods obtainSum = new SimpleArithmeticMethods();
SimpleArithmeticMethods obtainDifference = new SimpleArithmeticMethods();
SimpleArithmeticMethods workSum_Difference = new SimpleArithmeticMethods();
for (int counter = 0; counter <= 1; counter++)
{
strInptNums[counter] = JOptionPane.showInputDialog(null, "Input a number, smallest first", "Input Data.", JOptionPane.QUESTION_MESSAGE);
inptNums[counter] = Integer.parseInt(strInptNums[counter]);
}
workSum_Difference.sum_Difference(inptNums);
obtainSum.getDifference();
obtainDifference.getDifference();
}
}
You're calling the sum_Difference() method on one object, and display the results using another object.
That's like storing a message in a bottle, and then looking if the message is in another bottle. Use the same object to call all three methods.

Categories