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;
}
Related
Im new in java hope y'all doing great.
So i was trying to extract values from my text files and put into the array named tableauForfaits but i'm blocked can someone help me to see where's my error because when i try to split it doesn't work.
private static final String FIC_FORFAITS = "Forfaits.txt";
// Déclaration des variables
private static Forfait tableauForfaits[] = new Forfait[6];
* Read data from different packages (id | description | price)
* in the "Forfaits.txt" file. The first line in this file is the
* description of other lines and it should be ignored when
* reading. The other lines of this file are each composed of the identifier,
* of the description, and the price separated from each other by a vertical bar.
* Each of these lines must be read and cut to create an object of type
* Package, and this item should be added in the package table above
* defined (see Forfaits.txt file for more details)
*
public static void lireFichierForfaits() throws IOException,FileNotFoundException {
try (BufferedReader reader = new BufferedReader (new FileReader(FIC_FORFAITS))) {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
tableauForfaits = line.split("\\|");
for (String part : tableauForfaits) {
System.out.println(part);
}
System.out.println();
}
reader.close();
}
}
/ The Class Forfait :
private String identifiant;
private String description;
private float prix;
public Forfait (String identifiant, String description, float prix) {
this.identifiant = identifiant;
this.description = description;
this.prix = prix;
}
public String getIdentifiant () {
return identifiant;
}
public void setIdentifiant (String identifiant) {
this.identifiant = identifiant;
}
public String getDescription () {
return description;
}
public void setDescription (String description) {
this.description = description;
}
public float getPrix () {
return prix;
}
public void setPrix (float prix) {
this.prix = prix;
}
This:
tableauForfaits = line.split("\\|");
won't work because String#split(...) returns an array of String, and you're trying to force this into an array of a different type, a Forfait object.
Instead, that line should be
String[] tokens = line.split("\\|");
This will hopefully split the row from the text file into individual small String tokens that can be used to help you create a single Forfait object with the tokens. How you create the object completely depends on the structure of this class (one that we are currently unable to see), but you likely need to call its constructor, using the String tokens obtained, and then put the Forfaitobject created into the tableauForfaits array, perhaps something like,
Forfait forfait = new Forfait(token[0], token[1].....);
Note that you may need to parse numeric token Strings to a numeric value before doing this, such as
Forfait forfait = new Forfait(Integer.parseInt(token[0]), token[1], .....);
Again, it's impossible to say for sure, since we currently cannot see the Forfait class or the text file.
You will also need to create an int index variable before the while loop, increment it within the while loop, and use this as an index to the tableauForfaits array to help you decide which row of the array to put your newly create object into.
I want to check if a number in string is in a given range or not. if yes then add 100 to the number present in the string and return string.
For example channel has id name and start and end time
// created list of channel object
List<Channel> cList= Arrays.asList(
new Channel(1,"BBC","0300","0500"),
new Channel(2,"TR","0400","0509"),
new Channel(3,"NEWS","0700","0800"));
/*logic to identifyif the value is in between given rabge and add 100 to it.*/
List<Channel> cNewList=cList.forEach(
// perform operation to find if c.getstartTime() between
// range(100,500).then add 100 in it.
);
I know we can use Integer.parseInt(String) method to convert to integer value but I want the output back to a string.
Assuming that you class Channel has these member fields:
class Channel {
private int index;
private String name;
private String startTime;
private String endTime;
...
}
and in the Main class you define a static helper method:
public class Main {
private static Channel getNewStartTimeChannel(Channel c) {
// parse the string to int
int x = Integer.parseInt(c.getStartTime());
if (x > 100 && x < 500) {
return new Channel(
c.getIndex(),
c.getName(),
// update the int value of the startTime and transform it back to String
"" + (x + 100),
c.getEndTime());
}
return c;
}
you can easily transform the Channels in the original list into the new one:
public static void main(String[] args) {
List<Channel> cList = Arrays.asList(
new Channel(1, "BBC", "0300", "0500"),
new Channel(2, "TR", "0400", "0509"),
new Channel(3, "NEWS", "0700", "0800")
);
List<Channel> cNewList = cList.stream()
.map(Main::getNewStartTimeChannel)
.collect(Collectors.toList());
}
You have to parse the string to integer to do the comparison, so you're good with the parseInt.
Afterwards can always concat your integers with an empty string to get back a string (e.g. 1 + "" will give you a string).
I am trying to create a list of objects from a database but whenever I add another element to the end of the list it changes the values of the previous elements. I have seen similar questions on here but none seem to help my problem.
Here is the code for the class Deck
public static class Deck {
private static int deckid;
private static String deckName;
private static int deckCreatorID;
private static boolean isDeckPublic;
private static String deckDescription;
public Deck(int id, String name, int creator, boolean isPublic, String description){
deckid = id;
deckName = name;
deckCreatorID = creator;
isDeckPublic = isPublic;
deckDescription = description;
}
public String getDeckName(){
return deckName;
}
public String getDeckDescription(){
return deckDescription;
}
public int getDeckCreator(){
return deckCreatorID;
}
public int getDeckid() { return deckid; }
public boolean getDeckPublic() { return isDeckPublic; }
}
Here is the code to create and add the objects to the list:
public static List<marketplaceController.Deck> getAllCards(){
List<marketplaceController.Deck> deckList = new ArrayList<>();
List<Integer> idList = new ArrayList<>();
List<String> nameList = new ArrayList<>();
List<Integer> cIdList = new ArrayList<>();
List<Boolean> publicList = new ArrayList<>();
List<String> descList = new ArrayList<>();
try{ // This try-catch block is mainly from https://www.javatpoint.com/example-to-connect-to-the-mysql-database
Class.forName("com.mysql.cj.jdbc.Driver"); // Define the driver to use
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/users","root","UnlockDB.123"); // Connect to the local db
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from decks"); // Execute the query on the db
while(rs.next()) { // Runs while columns are to be store
idList.add(rs.getInt(1));
nameList.add(rs.getString(2));
cIdList.add(rs.getInt(3));
publicList.add(rs.getBoolean(4));
descList.add(rs.getString(5));
}
con.close();
}
catch(Exception e){
loginController.popup("An error occurred connecting to the database", "An error occurred");
}
for(int i = 0; i < idList.size(); ++i){ // This loop outputs the correct data
deckList.add(new marketplaceController.Deck(idList.get(i), nameList.get(i), cIdList.get(i), publicList.get(i), descList.get(i)));
System.out.println(deckList.get(i).getDeckid());
System.out.println(deckList.get(i).getDeckName());
System.out.println(deckList.get(i).getDeckCreator());
System.out.println(deckList.get(i).getDeckPublic());
System.out.println(deckList.get(i).getDeckDescription());
}
for(int i = 0; i < deckList.size(); ++i){ // This outputs the overwitten data
System.out.println(deckList.get(i).getDeckid());
System.out.println(deckList.get(i).getDeckName());
System.out.println(deckList.get(i).getDeckCreator());
System.out.println(deckList.get(i).getDeckPublic());
System.out.println(deckList.get(i).getDeckDescription());
}
return deckList;
}
When the elements of deckList are printed straight after they are created they show the correct elements e.g.
1
TESTDECK
1
true
""
2
TESTDECK2
1
true
""
However, when I iterate through the completed list and print the contents the following is printed:
2
TESTDECK2
1
true
""
2
TESTDECK2
1
true
""
This is probably a very stupiud question but I'm reltively new to Java and so any help is greatly appreciated
As #jhamon pointed out using static variables can be a very bad idea when you don't know what this means. Simply put a static field is shared among all instances of a class because it is a property of the class and not the instance. So when you have 10 instances of Deck all of them will return the same value for e.g. deckid.
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 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;