If I have an array that gets updated as I run a program (say I ask the player for 5 numbers), call is ClassA and then want to save it using a different class, call it ClassB that imports the data from ClassA, how would I do this?
I am able to create a global variable and pass that information to ClassB but how would I pass a method that takes an argument from a different method to this file?
Here is what I have attempted so far:
class quiz
{
--- other code irrelavent to question ---
public static int[] scorearrayp1()
{
int[] scorep1 = new int[4]; // this creates the array that gets filled later
return new int[4];
}
public static void askQ(scorep1)
{
JOptionPane.showInputDialog("Some numbers");
// this method then fills the array depending on user input
// it is the values from here that I wish to save in classB
}
public static int[] passArray(int[] scorep1)
{
return scorep1; // this is from class A and takes the value from a method before
}
And this is the class I want to send this array to:
class saveScores
{
public static void main(String[] params) throws IOException
{
PrintWriter outputStream = new PrintWriter(new FileWriter("scores.txt"));
finalproject data = new finalproject();
int[] scores = data.passArray(int[] scorep1);
for (int i = 0; i < scores.length; i++)
{
outputStream.println(scores[i]);
}
outputStream.close();
System.exit(0);
}
}
At the moment I'm being thrown two errors
error:'.class' expected
int[] scores = data.passArray(int[] scorep1);
^
error:';' expected
int[] scores = data.passArray(int[] scorep1);
^
I had the idea to change passArray(int[] scorep1) to passArray(scorep1) but then it just tells me that the symbol cannot be found.
Change
int[] scores = data.passArray(int[] scorep1);
to
int[] scores = data.passArray(scorep1);
But still you will need to declare scorep1, for example like:
int[] scorep1 = new int[]{1, 0, 0}
According to your edited question (and if I understand right), your code should look like the following:
int[] scores = quiz.passArray(quiz.scorearrayp1());
Anyway, please keep in mind that class names should always be uppercase.
You can do something like this:
class quiz{
int[] scorep1 = null;
public quiz()
{
scorep1 = new int[4]; // this creates the array that gets filled later
}
public static int[] askQ()
{
JOptionPane.showInputDialog("Some numbers");
// here call fills the array depending on user input
}
And do this:
int[] somearray = quiz.askQ();
int[] scores = data.passArray(somearray);
You should create an array somearray like above to pass at the method data.passArray(somearray);
Related
How would I initialize an Array within an object who's length is that of a user's input? I want to set the number of bats via user input, and make that the array length, then within the array of basesAchieved, I want to set a number based on user input (1-4) representing the base achieved.
// set up a Batter
public class Batter
{
private String batterName;
private int numberOfBats;
private int[] basesAchieved;
// fill fields with empty data, how is this done with an array??
public Batter()
{
this("", 0,0);
}
//
public Batter(String batterName, int numberOfBats, int[] basesAchieved)
{
this.batterName = batterName;
this.numberOfBats = numberOfBats;
this.basesAchieved = basesAchieved;
}
public void setBatterName(String batterName)
{
this.batterName = batterName;
}
public String getBatterName()
{
return batterName;
}
public void setNumberOfBats(int numberOfBats)
{
this.numberOfBats = numberOfBats;
}
public int getNumberOfBats()
{
return numberOfBats;
}
// want to set an array to get a number (1-4) for each number of # bats
// (numberOfBats).
public void setBasesAchieved(int[] basesAchieved)
{
this.basesAchieved = ;
}
public int getBasesAchieved()
{
return basesAchieved;
}
}
In the setter method you should assign this.basesAchieved = basesAchieved;. If you want to initialize the basesAchieved with a length then just: int[] basesAchieved = new int[yourlength] in the class you initialize Batter class, then call the setter method of this class
You have some errors in your class where you try to use an int array.
public Batter()
{
this("", 0, new int[0]);
}
// skipped...
public void setBasesAchieved(int[] basesAchieved)
{
this.basesAchieved = basesAchieved;
}
public int[] getBasesAchieved()
{
return basesAchieved;
}
This question explains how to get user input How can I get the user input in Java?
One of the simplest ways is to use a Scanner object as follows:
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
You can use this method to read the number of numberOfBats and create your object with the right array length. Then you can keep asking the user for input and put those into the basesAchieved array. Or you can ask the reader for all inputs first and then create your object.
I have written a method (part of a program) which takes in two int values(code below). One int value representing number of guys for whom java training is completed and another int value for guys for whom php training is completed. I expect the arraylist to grow with every function call. Example: First time I called the function with values (5,0). So the arrayList for java would be [5] and for php it would be [0] . Next time I call the function with values (2,3). The arrayList for java should now be [5][2] and sum should be 7. The the arraylist for php should be [0][3] ans sum should be 3. The problem with my code is that when I call the method for the second time, it wipes away the [5](value of first index from the first call) in the java arrayList and just takes the form of [2] and gives the sum 2(instead of the required 7). The arrayList is never growing. (same for the php arrayList) I am sure I am doing something conceptually wrong here . Please help Somehow, the way I have coded it, every function call seems to make a new arrayList and not growing the arrayList obtained from the previous call.
public class TrainingCamp {
public static int trainedJavaGuys ;
public static int trainedPHPGuys ;
public void trainedTroopsInCamp(int java,int php){
//System.out.println("********* Current Status of Training Camp ********* ");
ArrayList<Integer> trainingListJava = new ArrayList<>();
trainingListJava.add(java);
//System.out.println("---JavaARRAYLIST----"+trainingListJava);
trainedJavaGuys = sumList(trainingListJava);
ArrayList<Integer> trainingListPHP = new ArrayList<>();
trainingListPHP.add(php);
trainedPHPGuys = sumList(trainingListPHP);
//System.out.println("---phpARRAYLIST----"+trainingListPHP);
Calling it like this from another class:
TrainingCamp currentTrainingCamp = new TrainingCamp();
currentTrainingCamp.trainedTroopsInCamp(2, 0);
and next time the same two lines get executed with just the input params changed
The arraylists are reinitialized each time you call trainedTroopsInCamp() because they are declared within it.
You should make the arraylists member variables, so that they only get initialized once, in the class's constructor.
public class TrainingCamp {
public static int trainedJavaGuys ;
public static int trainedPHPGuys ;
// Declare once
ArrayList<Integer> trainingListJava;
ArrayList<Integer> trainingListPHP;
public TrainingCamp() {
// Initialize once
trainingListJava = new ArrayList<>();
trainingListPHP = new ArrayList<>();
}
public void trainedTroopsInCamp(int java,int php){
// Use everywhere
trainingListJava.add(java);
trainedJavaGuys = sumList(trainingListJava);
trainingListPHP.add(php);
trainedPHPGuys = sumList(trainingListPHP);
}
}
you're re-initializing the list references in the method call, so every time you call the method you're using a new (empty) list.
instead, try keeping the lists as member variables for your class, something like this:
class TrainingCamp {
private final List<Integer> javaTrained = new LinkedList<>();
private final List<Integer> phpTrained = new LinkedList<>();
public void trainedTroopsInCamp(int java,int php){
//System.out.println("********* Current Status of Training Camp ********* ");
javaTrained.add(java);
trainedJavaGuys = sumList(javaTrained);
phpTrained.add(php);
trainedPHPGuys = sumList(phpTrained);
}
...
}
The question is
Write a method readStock(String[] sAr, double[] pAr, int[] qAr) to read the following details from a file named “stock.txt”.
So I created the stock file which contain
pillow 14.50 30
Sheet 43 40
Quilt 52.50 40
Set 100 200
and I do this method
public static void readStock(String[] sAr, double[] pAr, int[] qAr) throws FileNotFoundException
{
Scanner input = new Scanner(new FileReader("stock.txt")) ;
int i = 0;
while (input.hasNext())
{
sAr[i]= input.next();
pAr[i] = input.nextDouble();
qAr[i] =input.nextInt();
i++;
}
input.close();
System.out.print("ITEM"+" "+"Price"+" "+"Quantity");
for (i=0;i<qAr.length;i++)
{
System.out.println(sAr[i]+" "+pAr[i]+" "+qAr[i]+"");
}
}
but I don't know the way to call it ?
I did
public static void main(String[] args)
{
readStock();
}
}
but there is an error.
You should pass in 3 corresponding parameters, in your case they are String[] sAr, double[] pAr, int[] qAr. Therefore you should do something like readStock(sAr, pAr, qAr);
You require 3 parameters in you method signature, 3 arrays so you need to pass them to the method. You can do it like: readStock(new String[4], new double[4], new int[4]); However with this design you need to know how many lines you file contains (because you need to create arrays with proper size). To make it work with any file length just replace arrays with Lists:
public static void readStock(List<String> names, List<Double> prices, List<Integer> quantity) throws FileNotFoundException
{
Scanner input = new Scanner(new FileReader("stock.txt")) ;
while (input.hasNext())
{
names.add(input.next());
prices.add(input.nextDouble());
quantity.add(input.nextInt());
}
input.close();
System.out.print("ITEM"+" "+"Price"+" "+"Quantity");
for (int i=0; i<names.size(); i++)
{
System.out.println(names.get(i)+" "+prices.get(i)+" "+quantity.get(i)+"");
}
}
Lists have the ability to expand their size when you are adding an element and there is not enough space for him. To create new List you can use for example new ArrayList<String>()
My program is suppose to take a text file, read the first four names, create a random number between 1-4, and then assign the names to 4 different teams based on what the random number was. For instance, if the number was 3, then the first name would go to team 3, second name to team 4, etc. etc.(repeat process until there are no more names) I believe I have all of the code for that correct, the problem is I can't figure out how to return all the names I have put into the arrays that were brought into the method. Here is my code:
public static void main(String args[]) throws IOException
{
BufferedReader girlFile = new BufferedReader(new FileReader("girls40.txt"));
PrintWriter teamFile = new PrintWriter(new FileWriter("xxxxxxx-teamlist.txt"));
String team1[] = new String[20];
String team2[] = new String[20];
String team3[] = new String[20];
String team4[] = new String[20];
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
}
public static String[] loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile)
{
int n;
int random;
String name1;
String name2;
String name3;
String name4;
while((name1=girlFile.readLine())!=null)
{
name2=girlFile.readLine();
name3=girlFile.readLine();
name4=girlFile.readLine();
random = 1 + (int)(Math.random() * 4);
if(random==1)
{
team1[n]=name1;
team2[n]=name2;
team3[n]=name3;
team4[n]=name4;
}
if(random==2)
{
team1[n]=name4;
team2[n]=name1;
team3[n]=name2;
team4[n]=name3;
}
if(random==3)
{
team1[n]=name3;
team2[n]=name4;
team3[n]=name1;
team4[n]=name2;
}
if(random==4)
{
team1[n]=name2;
team2[n]=name3;
team3[n]=name4;
team4[n]=name1;
}
n++;
}
return team1[],team2[],team3[],team4[];
}`
The main method was given to me, so it cannot be changed.
If there is more code in main method than you've posted here. You'll have to mention what is the variable n and how is it being used else follow the answer.
main Method can't be changed
In your main method,
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
} // End of Main Method
You have not used returned value n for nothing. So it really doesn't matter what you return from method loadTeams() as long as it is an int.
Also, here loadTeams() returns an String[] which can't be assigned be int n, you'll have to change return type of loadTeams() to int as
public static int loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile) {
/*
...
*/
return 0; // whatever, it isn't being used
}
This the solution if you can't change the main method.
The call to loadTeams() expects a return value of type int. Not an array or multiple arrays. If you can't change the main method then loadTeams should return an integer.
// ...
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
// ...
you don't have to return anything, arrays created in main() will be passed to your method by reference, you can fill them there, and after execution of your method, values will be kept in these arrays
The loadTeams should return an int and not String[].
There is no need to return arrays. Changes made in the arrays in the loadTeams methods will be reflected back to the array in main method.
I have extended a class in hope to store a global array (make the array within the class be seen by another object) by using the set1sub(sub.local) method
public class BattleShipsClient extends ShipLocations implements Runnable, BattleShipConstants
{
BattleShipsClient()
{
}
public void placeBoard(int player) throws IOException// this is only called once and not updated when clicked again
{
while(getLocations())
{
while(isWaiting())//true
{
toServer.writeInt(player);
int row = getRowSelected();
int col = getColumnSelected();
int choice=Integer.parseInt(JOptionPane.showInputDialog("Please 1 for a sub, 2 for a battleship and 3 for a destroyer"));
clickCount ++;
if(clickCount >2)
{
setLocation(false);
continueToPlay=true;
}
if (choice ==1 &&sub.placed==false)
{
String orientation =JOptionPane.showInputDialog("please enter your orientations");
if(orientation.equalsIgnoreCase("h"))
{
//row os the same
//column number will be sent, then plus one on the other side
sub.local = new int[2][2];
sub.local[0][0] =row;
sub.local[0][1]=col;
sub.local[1][0]=row;
sub.local[1][1] =col+1;
toServer.writeInt(row);
toServer.writeInt(col);
toServer.writeChar('s');
sub.placed=true;
setp1sub(sub.local);
/*setp1sub(new int[][]{{row,col},
{row,col+1}});*/
grid[row][col+1].setToken(getMyToken());
}
I then have a ship Locations class however when i create a new object of the ship locations class and try to read this array it always is set to [[0, 0], [0, 0]], ive tried making it static and atomic
public class ShipLocations {
int [][] p1sub;
public ShipLocations()
{
p1sub = new int[2][2];
}
public int[][] getp1sub()
{
return p1sub;
}
public void setp1sub(int[][] local) {
for (int i = 0;i <local.length;i++)
{
for(int j = 0;j<local.length;j++)
{
p1sub [i][j]= local[i][j];
}
}
}
}
Whenever you create a new instance of ShipLocations(or a subclass) the constructor is called, which in your case, reinitializes the p1sub array.
In your design, you are overusing inheritance. You should not inherit from a class just to use its methods and variables.
To store a global variable in a class:
public class ShipLocations {
static int [][] p1sub;
static{
p1sub = new int[2][2];
}
public static void setp1sub(...){...}
public static int[][] getp1sub(){...}
}
And then use it by class name instead of creating instances:
int [][] x = ShipLocations.getp1sub();
Though the use of global variables shoud be avoided when possible. It is considered bad design and might be a problem when reusing the code.
The correct way of doing this is to have the ShipLocations object as a local variable in BattleShipsClient and set it when initializing new instance. You will then first create a common ShipLocation object and hand it to every client that should see the same array.