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.
Related
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);
I'm trying to populate an ArrayList with data stored in a text file, the data is 5 different values separated by white space, and a mix of boolean, strings and integers. Also, I'm using BlueJ, not sure if that changes anything though.
When the data is read from the file, objects of type Room should be created based on that data
I am new to Java, I've just started learning it within the last few weeks, my read data class is as follows:
Room Data Class:
public class RoomData
{
//Default Values of a Room
private int roomNumber = 0;
private int bookingNights = 0;
private boolean hasEnSuite = false;
private boolean isBooked = false;
private String bookingName = "<None>";
public void setRoomNumber(int roomNumber)
{
this.roomNumber = roomNumber;
}
public void setBookingNights(int bookingNights)
{
this.bookingNights = bookingNights;
}
public void setHasEnSuite()
{
this.hasEnSuite = hasEnSuite;
}
public void setIsBooked()
{
this.isBooked = isBooked;
}
public void setBookingName()
{
this.bookingName = bookingName;
}
}
ReadDataClass:
public class ReadHotelData
{
private String filePath;
public ReadHotelData()
{
filePath = "hotelData.txt";
}
private List<RoomData> list = new ArrayList <>();
public boolean hasNext() throws FileNotFoundException
{
Scanner s = new Scanner(new File("hotelData.txt"));
while (s.hasNext())
{
String nextLine = s.nextLine(); //reads text file line by line
RoomData roomData = new RoomData();
String[] values = nextLine.split(" "); // splits the text file by white space
roomData.setRoomNumber(Integer.parseInt(values[0]));
roomData.setBookingNights(Integer.parseInt(values[1]));
roomData.setHasEnSuite(Boolean.parseBoolean(values[2]));
roomData.setIsBooked(Boolean.parseBoolean(values[3]));
roomData.setBookingName(String.parseString(values[4]));
list.add(roomData);
}// end loop
s.close();
return true;
}
public List <RoomData> getRoomDataList()
{
return list;
}
}
Like I said I'm new so if I'm missed anything I'd really appreciate any help!
Example of data stored in text file:
0 false David 0 false
0 true John 0 false
0 false Jim 0 true
First create a class RoomData to hold the data for each room and give each variable a meaningful name along with the appropriate type.
Change your arraylist to hold that type instead of String
private List<RoomData> list = new ArrayList<>();
Read each line using s.nextLine()
while(s.hasNext())
{
String nextLine = s.nextLine();
RoomData roomData = new RoomData();
Create an instance of that class, split and parse each value into the corresponding variable in the instance of RoomData you have created.
String[] values = nextLine.split(" ") // split by space
// lets say you have "0 false David 0 false"
// values[0] would be "0"
// values[1] would be "false"
// values[2] would be "David"
// values[3] would be "0"
// values[4] would be "false"
All the values in values would be of type String you will need to convert those from String to the type you have defined in RoomData, for int you can use Integer.parseInt(String s), for boolean there is a similar method (Boolean.parseBoolean(String s))[http://docs.oracle.com/javase/8/docs/api/java/lang/Boolean.html#parseBoolean-java.lang.String-], string values can be set directly.
Add that instance to the arraylist.
list.add(roomData);
} // end of while
Add a getter method to return that list for use in other classes.
public List<RoomData> getRoomDataList() {
return list;
}
I wanted to pass the "result" of "You Chose : abc" to a return type, so I can then pass it into my serialized method, so that I can then serialize that chosen team. I know how to return an array, but how would I return an array -1 ?
Code snippets are as follows :
public class Display{
public String[] printGreeting(int choice, String[] clubName) {
result = clubName;
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (choice >= 1 && choice <= 20) {
System.out.println("You chose: " + clubName[choice - 1]); // return the clubName -1
}
return result; // how to declare return statement ?
}
}
Here is my serialize code, not sure how I would pass the array, via an alias or use object ?
public class Serialize
{
public void Serialize() // receive return type from printGreeting();
{
// how to put object info into files, rather than declare here ?
try
{
FileOutputStream fileOut = new FileOutputStream("/home/cg/root/club.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(club);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in C:/tmp/club.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}
Any help with this would be greatly appreciated :)
Here you declare to return an array of String[]:
public String[] printGreeting(int choice, String[] clubName) {
// ↑ here you say this method MUST return an array if Strings
What you need is
assign the user's choice to returned variable
return just ONE String
public String printGreeting(int choice, String[] clubName) {
result = clubName;
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (choice >= 1 && choice <= 20) {
// assign choice to result
result = clubName[choice - 1];
// print choice
System.out.println("You chose: " + result); // return the clubName -1
}
// return the chosen club name
return result;
}
Actually, I don't know why result is a class attibute (but i cannot see declaration), what does not make much sense if you want to return it, I will code the method as:
public String printGreeting(int choice, String[] clubName) {
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); // ??
if (choice >= 1 && choice <= 20) {
choice --; // if choice is valid, get the array position.
// print choice
System.out.println("You chose: " + clubName[choice]);
return clubName[choice];
}
// if the choice is not correct, return null or "" as you want
return null;
}
UPDATE
Could anyone advise how I would pass that returned String to my serialize method, I think I know how to serialize it, but not 100% sure on parameter passing.
I don't get exactly what you want to achieve, maybe would be better to rephrase question with your target clear, and your tries.
Serialize (shortly), in Java is make an object's attributes convertible to Strings, then, a String either an String[] array does not need to be serialized.
As long as Display methods are not static, you must create an instance of Display to execute as follow:
public class Main {
public static void main(String [] args) {
// create an instance of Display class
Display d = new Display();
// get the needed values to pass to printGreeting method:
String[] clubs = {"club one", "club two" // put 20 clubs
// get the index from the user
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int choice = sc.nextInt();
// call the method and get the return:
String result = d.printGreeting(choice, clubs)
// then get a serializer and execute method:
Serialize s = new Serialize();
s.serialize(result);
}
}
change the method Serialize.serialize() to Serialize.serialize(String) as follows:
public class Serialize
{
public void serialize(String club)
// ↑ receive return type from printGreeting();
{
// your serialize code
}
}
What do you want to return? The club name (String) or the whole array?
It's not clear in your code if result is an array or a String, you simply say result = clubName. If it's an array it should be String[] result = clubName;, if you want to return a String it should be String result = clubName[choice -1];, in that case you have to change the method to public String printGreeting(int choice, String[] clubName) and you can return result;
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.
Full working now and code is complete Thanks for the help.
You can restrict user to enter another value by this: (This program is for if You are taking values from user). This will asks for number until you enter number within 0 to 9.
You can make your code according to this. (This is just for your reference, How can you restrict user to enter wrong thing)
Scanner scan=new Scanner(System.in);
int i=-1;
i=scan.nextInt();
while(i<=0 && i>=9){
i=scan.nextInt();
}
EDIT
As per your comment, In that case you need to change this as:
String s="";
while(!s.matches("^[0-9A-F]+$")){
s=scan.nextLine();
}
I would create a class to hold the RGB values and have it check that the correct values are entered. See the test code below.... you can expand as you need to handle more cases.
import java.util.*;
public class jtest
{
public static void main(String args[])
{
new jtest();
}
public jtest()
{
ArrayList<RGB> RGBarray = new ArrayList<RGB>();
try
{
RGBarray.add(new RGB("F"));
RGBarray.add(new RGB("J"));
}
catch(BadRGBValueException BRGBVE)
{
BRGBVE.printStackTrace();
}
}
class BadRGBValueException extends Exception
{
public BadRGBValueException(String message)
{
super(message);
}
}
class RGB
{
public RGB(String input) throws BadRGBValueException
{
if (!input.matches("^[0-9A-F]+$"))
{
throw new BadRGBValueException(input + " is not a valid RGB value");
}
value = input;
}
private String value = null;
}
}