How to declare the size of x and y - java - java

so for an assignment I've had to create a building class i was given the bare bones of the code and I've got this far the part I'm struggling on is setting the size of the x and y coordinate which needs to be in setBuilding().
This is the desired output of the class:
Building size 11×11
Room from (0,0) to (5, 5) door at (3, 5)
Room from (6,0) to (10, 10) door at (6, 6)
Room from (0,5) to (5, 10) door at (2, 5)
The program displays everything apart from the "Building size 11×11", I'm not looking for someone to do the work for me just want to be pointed in the right direction.
Thanks for any help
import java.util.*;
public class Building {
private int xSize = 10; // size of building in x
private int ySize = 10; // and y
private ArrayList<Room> allRooms; // array of rooms
Building (String first) {
allRooms = new ArrayList<Room>();
setBuilding(first);
}
public void setBuilding(String bS) {
String[] Space;
allRooms.clear();
Space = bS.split(";");
allRooms.add(new Room(Space[1]));
allRooms.add(new Room(Space[2]));
allRooms.add(new Room(Space[3]));
}
public String toString() {
String s;
s = " ";
for (Room r : allRooms) {
s = s + r.toString();
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Buidling test\n");
Building b = new Building("11 11;0 0 5 5 3 5;6 0 10 10 6 6;0 5 5 10 2 5"); // Create
System.out.println("built building\n");
System.out.println(b.toString()); // And print
}
}

you didn't add any declaration to your toString for showing the building dimensions. I assume you want to use the xSize and ySize of the building. Also note that you're not extracting the building dimensions from the buidlString you pass to setBuilding.
Change your toString to the code below.
public String toString() {
String s = "Building size" + xSize + ", " + ySize;
for (Room r : allRooms) {
s += r.toString();
}
return s;
}
for defining your building size:
public void setBuilding(String bS) {
String[] Space;
allRooms.clear();
Space = bS.split(";");
//Here we'll update the requested building size
String[] buildingSize = Space[0].split(" "); //split the two integers
xSize = Integer.ParseInt(buildingSize[0]); //transform the string to int
ySize = Integer.ParseInt(buildingSize[1]); //transform the string to int
allRooms.add(new Room(Space[1]));
allRooms.add(new Room(Space[2]));
allRooms.add(new Room(Space[3]));
}

Related

Java - OOP array of objects and display them

I have created an array of objects(cups) which I have set a volume and capacity and colour too, all of this is displayed by calling .display() However I can get the display() to do this in this instance when trying to loop through the array of cups. I get no output to show the cups capacity and colour from the display() method, I have added the two bits of code, one in the cups class that contains the display method and the first one which shows me trying to create an array and display each cup. I would deeply appreciate any help as this is a part of a school assignment.
screenshot of current output
public static void main(String[] args)
{
//Makes Array of cups
Cup [] Cups = new Cup[4];
// Creates 4 Cups with 250 capacity and black colour
for(int i = 0 ; i > 4 ; i++)
{
Cups[i] = new Cup (250, ContainerColour.BLACK );
Cups[i].display();
}
//Teapot, Wash and then fill with tea
TeaCup myTeaCup = new TeaCup();
myTeaCup.Wash();
myTeaCup.Fill();
myTeaCup.display();
}
my cups oop code :
// ---------------------------------------------------------------------
// class variables
// ---------------------------------------------------------------------
private ContainerColour myColour;
private int iCapacity;
private int iVolume;
private int iTemp;
private int iFill;
private String SzMaterial;
private Boolean bEmpty;
// ---------------------------------------------------------------------
// Constructors
// ---------------------------------------------------------------------
public Cup()
{
super();
reset();
return;
}
public Cup (Cup original) {
iCapacity = original.getCapacity();
iVolume = original.getVolume();
SzMaterial = original.getMaterial();
}
public Cup(int size)
{
this();
super.setCapacity(size);
setColour(ContainerColour.NOT_SET);
return;
}
public Cup (int size , ContainerColour colour)
{
this (size);
setColour(colour);
return;
}
//setters
public void setColour(ContainerColour c)
{
myColour = c;
}
//getters
public ContainerColour getColour()
{
return(this.myColour) ;
}
//main
public void display()
{
System.out.println("Cup: \nCapacity = " + getCapacity());
System.out.println("Volume = " + getVolume());
System.out.println("Colour = " + getColour() );
if(iVolume == 0) {
bEmpty = true;
}
else {
bEmpty = false;
}
System.out.println("Empty = " + bEmpty );
return;
}
public static void main(String[] args) {
Cup myCup = new Cup();
myCup.setCapacity(250);
myCup.setColour(ContainerColour.WHITE);
myCup.Wash();
myCup.fill();
myCup.display();
}
public static void main(String[] args)
{
//Makes Array of cups
Cup [] Cups = new Cup[4];
// Creates 4 Cups with 250 capacity and black colour
for(int i = 0 ; i < 4 ; i++)
{
Cups[i] = new Cup (250, ContainerColour.BLACK );
Cups[i].display();
}
//Teapot, Wash and then fill with tea
TeaCup myTeaCup = new TeaCup();
myTeaCup.Wash();
myTeaCup.Fill();
myTeaCup.display();
}
So if of all you made mistake in coding loop it should be less than 4 and secondly array index start with zero it means when you reach 3 you will iterate all objects in array Cups.
Instead of hard-coding the 4, use the actual array itself to determine the length and use that in your for loop:
for(int i=0; i<Cups.length; i++) {
Cups[i] = new Cup (250, ContainerColour.BLACK );
Cups[i].display();
}

I have some problems with ArrayList (quiz of head first java)

I've just started learning java since last week. I'm using book called 'head first java' and i'm struggling with solving problems about ArrayList. Error says "The method setLocationCells(ArrayList) in the type DotCom is not applicable for the
arguments (int[])" and I haven't found the solution :( help me..!
enter image description here
This looks like a Locate & Conquer type game similar to the game named Battleship with the exception that this game is a single player game played with a single hidden ship in a single horizontal row of columnar characters. Rather simplistic but kind of fun to play I suppose. The hard part is to locate the hidden ship but once you've located it, conquering (sinking) it becomes relatively easy. I'm sure this isn't the games' intent since it is after all named "The Dot Com Game" but the analogy could be possibly helpful.
There are several issues with your code but there are two major ones that just can not be there for the game to work:
Issue #1: The call to the DotCom.setLocationCells() method:
The initial problem is located within the DotComGame class on code line 13 (as the Exception indicates) where the call is made to the DotCom.setLocationCells() method. As already mentioned in comments the wrong parameter type is passed to this method. You can not pass an int[] Array to the setLocationCell() method when this method contains a parameter signature that stipulates it requires an ArrayList object. The best solution in my opinion would be to satisfy the setLocationCells() method parameter requirement...supply an ArrayList to this method.
The reason I say this is because all methods within the DotCom class work with an established ArrayList and one of the tasks of one of these methods (the checkYourself() method) actually removes elements from the ArrayList which is easy to do from a collection but very cumbersome to do the same from an Array.
To fix this problem you will need to change the data type for the locations variable located within the DotComGame class. Instead of using:
int[] locations = {randomNum, randomNum + 1, randomNum + 2};
you should have:
ArrayList<Integer> locations = new ArrayList<>(
Arrays.asList(random, randomNum + 1, randomNum + 2));
or you could do it this way:
ArrayList<Integer> locations = new ArrayList<>();
locations.add(randomNum);
locations.add(randomNum + 1);
locations.add(randomNum + 2);
There are other ways but these will do for now. Now, when the call to the setLocationCells() method is made you ahouldn't get an exception this issue should now be resolved.
Issue #2: The call to the DotCom.checkYourself() method:
Again, this particular issue is located within the DotComGame class on code line 18 where the call is made to the DotCom.checkYourself() method. Yet another parameter data type mismatch. You are trying to pass a variable of type String (named guess) to this method whereas its signature stipulates that it requires an integer (int) value. That again is a no go.
To fix this problem you will need to convert the string numerical value held by the guess variable to an Integer (int) value. So instead of having this:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
String result = theDotCom.checkYourself(guess);
// ... The rest of your while loop code ...
}
you should have something like:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
/* Validate. Ensure guess holds a string representation
of a Integer numerical value. */
if (!guess.matches("\\d+")) {
System.err.println("Invalid Value (" + guess
+ ") Supplied! Try again...");
continue;
}
int guessNum = Integer.parseInt(guess);
String result = theDotCom.checkYourself(guessNum);
numOfGuesses++;
if (result.equals("kill")) {
isAlive = false;
System.out.println(numOfGuesses + " guesses!");
}
else if (result.equals("hit")) {
// Do Something If You Like
System.out.println("HIT!");
}
else {
System.out.println("Missed!");
}
}
Below is a game named Simple Battleship which I based off of your code images (please don't use images for code anymore - I hate using online OCR's ;)
BattleshipGame.java - The application start class:
import java.awt.Toolkit;
public class BattleshipGame {
public static int gameLineLength = 10;
public static void main(String[] args) {
GameHelper helper = new GameHelper();
Battleship theDotCom = new Battleship();
int score = 0; // For keeping an overall score
// Display About the game...
System.out.println("Simple Battleship Game");
System.out.println("======================");
System.out.println("In this game you will be displayed a line of dashes.");
System.out.println("Each dash has the potential to hide a section of a");
System.out.println("hidden Battleship. The size of this ship is randomly");
System.out.println("chosen by the game engine and can be from 1 to 5 sections");
System.out.println("(characters) in length. The score for each battle is based");
System.out.println("on the length of the game line that will be displayed to");
System.out.println("you (default is a minimum of 10 charaters). You now have");
System.out.println("the option to supply the game line length you want to play");
System.out.println("with. If you want to use the default then just hit ENTER:");
System.out.println();
// Get the desire game line length
String length = helper.getUserInput("Desired Game Line Length: --> ", "Integer", true, 10, 10000);
if (!length.isEmpty()) {
gameLineLength = Integer.parseInt(length);
}
System.out.println();
// Loop to allow for continuous play...
boolean alwaysReplay = true;
while (alwaysReplay) {
int numOfGuesses = 0;
/* Create a random ship size to hide within the line.
It could be a size from 1 to 5 characters in length. */
int shipSize = new java.util.Random().nextInt((5 - 1) + 1) + 1;
int randomNum = (int) (Math.random() * (gameLineLength - (shipSize - 1)));
int[] locations = new int[shipSize];
for (int i = 0; i < locations.length; i++) {
locations[i] = randomNum + i;
}
System.out.println("Destroy the " + shipSize + " character ship hidden in the");
System.out.println("displayed line below:");
System.out.println();
String gameLine = String.join("", java.util.Collections.nCopies(gameLineLength, "-"));
theDotCom.setLocationCells(locations);
// Play current round...
boolean isAlive = true;
while (isAlive == true) {
System.out.println(gameLine);
String guess = helper.getUserInput("Enter a number from 1 to " + gameLineLength
+ " (0 to quit): --> ", "Integer", 1, gameLineLength);
int idx = Integer.parseInt(guess);
if (idx == 0) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
alwaysReplay = false;
break;
}
idx = idx - 1;
String result = theDotCom.checkYourself(idx);
numOfGuesses++;
System.out.println(result);
if (result.equalsIgnoreCase("kill")) {
Toolkit.getDefaultToolkit().beep();
isAlive = false;
/* Tally the score dependent upon the gameLineLength... */
if (gameLineLength <= 10) { score += 5; }
else if (gameLineLength > 10 && gameLineLength <= 20) { score += 10; }
else if (gameLineLength > 20 && gameLineLength <= 30) { score += 15; }
else if (gameLineLength > 30 && gameLineLength <= 40) { score += 20; }
else { score += 25; }
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
System.out.println(gameLine);
System.out.println(numOfGuesses + " guesses were made to sink the hidden ship.");
System.out.println("Your overall score is: " + (score < 0 ? 0 : score));
}
else if (result.equalsIgnoreCase("hit")) {
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
}
if (result.equalsIgnoreCase("miss")) {
score -= 1;
}
System.out.println();
}
// Play Again? [but only if 'alwaysReplay' holds true]
if (alwaysReplay) {
String res = helper.getAnything("<< Press ENTER to play again >>\n"
+ "<< or enter 'q' to quit >>");
if (res.equalsIgnoreCase("q")) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
break;
}
System.out.println();
}
}
}
}
GameHelper.java - The GameHelper class:
import java.util.Scanner;
public class GameHelper {
private final Scanner in = new Scanner(System.in);
public String getUserInput(String prompt, String responseType, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getUserInput(String prompt, String responseType, boolean allowNothing, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (response.isEmpty() && allowNothing) {
return "";
}
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getAnything(String prompt) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
return in.nextLine().trim();
}
}
Battleship.java - The Battleship class:
import java.util.ArrayList;
public class Battleship {
private ArrayList<Integer> locationCells;
public void setLocationCells(java.util.ArrayList<Integer> loc) {
locationCells = loc;
}
// Overload Method (Java8+)
public void setLocationCells(int[] loc) {
locationCells = java.util.stream.IntStream.of(loc)
.boxed()
.collect(java.util.stream.Collectors
.toCollection(java.util.ArrayList::new));
}
/*
// Overload Method (Before Java8)
public void setLocationCells(int[] loc) {
// Clear the ArrayList in case it was previously loaded.
locationCells.clear();
// Fill the ArrayList with integer elements from the loc int[] Array
for (int i = 0; i < loc.length; i++) {
locationCells.add(loc[i]);
}
}
*/
/**
* Completely removes one supplied Integer value from all elements
* within the supplied Integer Array if it exist.<br><br>
*
* <b>Example Usage:</b><pre>
*
* {#code int[] a = {103, 104, 100, 10023, 10, 140, 2065};
* a = removeFromArray(a, 104);
* System.out.println(Arrays.toString(a);
*
* // Output will be: [103, 100, 10023, 10, 140, 2065]}</pre>
*
* #param srcArray (Integer Array) The Integer Array to remove elemental
* Integers from.<br>
*
* #param intToDelete (int) The Integer to remove from elements within the
* supplied Integer Array.<br>
*
* #return A Integer Array with the desired elemental Integers removed.
*/
public static int[] removeFromArray(int[] srcArray, int intToDelete) {
int[] arr = {};
int cnt = 0;
boolean deleteIt = false;
for (int i = 0; i < srcArray.length; i++) {
if (srcArray[i] != intToDelete) {
arr[cnt] = srcArray[i];
cnt++;
}
}
return arr;
}
public String checkYourself(int userInput) {
String result = "MISS";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "KILL";
}
else {
result = "HIT";
}
}
return result;
}
}

Making a football standings from infinite match list input

I have an assignment which I have to program that creates a standings table from match list input. I used the word "infinite" because input size is unknown so I have to create a program that works until there's no matches left. I created a football class for this(input contains 2 other sports and their own matches and teams indicating the sports type with first letter of the sport with "F, B, V" for example, they're only different in scoring part, so I though if I can make football work, I can make anything else work) that contains everything required in standings table, and methods for match results which looks like this:
public class Football {
private int scoredGoals;
private int receivedGoals;
private String teamName;
private int Score;
private int wins;
private int losses;
private int MatchCount;
private int draws;
public void teamValues(String teamName, int Sgoals, int Rgoals) {
this.teamName = teamName;
this.scoredGoals = Sgoals;
this.receivedGoals = Rgoals;
}
public void matched() {
MatchCount++;
}
public void winner() {
wins++;
}
public void draw() {
draws++;
}
public void loser() {
losses++;
}
public void winScore() {
Score += 3;
}
public void drawScore() {
Score += 1;
}
public String showTeams() {
return (teamName + " " + MatchCount + " " + wins + " " + draws + " " + losses + " " + scoredGoals+":"+receivedGoals + " " + Score);
}
}
And in main class I'm calling methods in if blocks to calculate wins, score, matches count etc. And main looks like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner scan = new Scanner(file);
String fileString = "";
Football teams[] = new Football[2];
HashSet<String> teamsArray = new HashSet<String>();
while(scan.hasNextLine()) {
fileString = scan.nextLine();
String[] match = fileString.split("\\t|:");
if(match[0].equals("F")) {
int team1score = Integer.valueOf(match[3].trim());
int team2score = Integer.valueOf(match[4].trim());
teams[0] = new Football();
teams[0].teamValues(match[1], team1score, team2score);
teams[1] = new Football();
teams[1].teamValues(match[2], team2score, team1score);
teams[0].matched();
teams[1].matched();
if(team1score>team2score) {
teams[0].winner();
teams[1].loser();
teams[0].winScore();
}
if(team1score==team2score) {
teams[0].draw();
teams[1].draw();
teams[0].drawScore();
teams[1].drawScore();
}
if(team1score<team2score) {
teams[1].winner();
teams[0].loser();
teams[1].winScore();
}
String team0 = teams[0].showTeams();
String team1 = teams[1].showTeams();
teamsArray.add(team0);
teamsArray.add(team1);
}
}
scan.close();
}
}
Since the input is static, I used arrays to work around. My problem with my code is I cant find a way to store my teams without duplicates and the variables that comes within and update whenever that team has another match.
I tried;
Storing them in a 2D string array but since the amount of teams is unknown I think it won't be a healthy way to approach to the problem.
Storing them in a String[] array list, which ended up storing the adresses instead of the values of the teams.
Set which I still use to check if at least the methods are working as intended.
It feels like I hit the wall with this program and I need to start over, so any kind of advice is appreciated.
Here's an example of input and output:
Input:
Home Team Guest Team H : G
F Manchester U. Chelsea 2 : 2
F Liverpool Manchester City 3 : 2
F Leicester City Everton 1 : 3
V Team A Team B 3 : 0
F Tottenham Liverpool 3 : 1
B Team B Team A 90 : 96
F West Ham Manchester U. 2 : 1
F Arsenal Manchester City 0 : 2
F Chelsea Arsenal 3 : 3
Output:
Name Matches Wins Draw Lose Scored:Received Score
1. Manchester U. 10 6 2 2 27:22 20
2. Arsenal 10 6 2 2 25:24 20
3. Chelsea 10 5 3 2 28:20 18
4. Liverpool 10 4 4 2 22:19 16
5. Tottenham 10 4 4 2 22:21 16
There are teams with same scores, because calculating average of scored and received goals is another way to sort the teams.
First some changes to the Football class:
Override equals to be able to search the list
Override compareTo for sorting
Override toString instead of showTeams
Create a constructor
Combine most functions into teamValues
import java.util.Formatter;
public class Football implements Comparable<Football> {
private int scoredGoals;
private int receivedGoals;
private String teamName;
private int score;
private int wins;
private int losses;
private int draws;
private int matchCount;
public int compareTo(Football f) {
return score - f.score;
}
public boolean equals(Object o) {
if (o == null) {
return false;
}
else if (o instanceof Football) {
return teamName.equals(((Football)o).teamName);
}
else if (o instanceof String) {
return teamName.equals((String)o);
}
return false;
}
public Football(String teamName) {
this.teamName = teamName;
}
public void teamValues(int scoredGoals, int receivedGoals) {
this.scoredGoals += scoredGoals;
this.receivedGoals += receivedGoals;
matchCount++;
if (scoredGoals < receivedGoals) {
losses++;
}
else if (scoredGoals > receivedGoals) {
wins++;
score += 3;
}
else {
draws++;
score += 1;
}
}
public String toString() {
return new Formatter().format("%-20s %3d %3d %3d %3d %3d:%-3d %d",
teamName, matchCount, wins, draws, losses, scoredGoals, receivedGoals, score)
.toString();
}
}
For the main program, you don't want to create a new team every time - only when a team is first encountered in the file. Put all the teams in a List. When parsing a new game, first try to find the team in the list. If it is not in there, add it.
List<Football> teamsArray = new ArrayList<>();
while (scan.hasNextLine()) {
fileString = scan.nextLine();
String[]match = fileString.split("\\t|:");
if (match.length == 5 && match[0].equals("F")) {
int team1score = Integer.valueOf(match[3].trim());
int team2score = Integer.valueOf(match[4].trim());
// Create a temp team to search the List
Football team1 = new Football(match[1]);
// Search the list
if (!teamsArray.contains(team1)) {
// Not in the list already. Add it
teamsArray.add(team1);
}
else {
// Already in the List. Use that one.
team1 = teamsArray.get(teamsArray.indexOf(team1));
}
// Repeat for team 2
Football team2 = new Football(match[2]);
if (!teamsArray.contains(team2)) {
teamsArray.add(team2);
}
else {
team2 = teamsArray.get(teamsArray.indexOf(team2));
}
team1.teamValues(team1score, team2score);
team2.teamValues(team2score, team1score);
}
}
System.out.println("Name M W D L S:R S");
// Sort and print
teamsArray
.stream()
.sorted(Comparator.reverseOrder())
.forEach(t -> System.out.println(t));

Arrary list while creating a buildin

package uk.ac.reading.Nischal.buidlingconsole;
import java.util.ArrayList;
public class Building {
private int xSize = 10; // size of building in x
private int ySize = 10; // and y
private static String test;
StringSplitter bigBox;
private static ArrayList<Room> allRooms; // array of rooms
public Building(String build) {
setBuilding(build);
}
public void setBuilding(String bS) {
// allRooms.clear();
allRooms= new ArrayList<Room>();
bigBox = new StringSplitter(bS, ";");
String first = (bigBox.getNth(0, ""));
StringSplitter sizeXY = new StringSplitter(first, " ");
xSize = Integer.parseInt(sizeXY.getNth(0, ""));
ySize = Integer.parseInt(sizeXY.getNth(1, ""));
//test = bigBox.getNth(3, "");
for(int i = 0; i < bigBox.numElement(); i++){
String r = (bigBox.getNth(i, ""));
allRooms.add(new Room(r));
}
}
public String toString(){
String res = "Building size " + xSize + "," + ySize + "\n" ;
String s = "";
for (Room r : allRooms)
s = s + r.toString() + "\n";
return res + s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Building b = new Building("11 11;0 0 5 5 3 5;6 0 10 10 6 6;0 5 5 10 2 5"); // create
System.out.println(b.toString());
System.out.println(test);
}
}
i'm trying to create a building by passing a string of the form,
11 11;0 0 5 5 3 5;6 0 10 10 6 6;0 5 5 10 2 5 but i'm getting unknown errors
i'm told I have to use array list and here I've tried to do so yet I get weird errors.
I hope i'm getting this right, that this StringSplitter does nearly the same like the split-method from String.
Due the condition, that the 0th-Element of the bigBox, contains the xSize and ySize, i think your loop should start with 1 and not with 0.
for(int i = 1; i < bigBox.numElement(); i++){
String r = (bigBox.getNth(i, ""));
allRooms.add(new Room(r));
}
It would be helpful if you can show as the error-logs.

Product of index with multiple elements on a linked list

I read a text file using a linked list.
20 10 8
4.5 8.45 12.2
8.0 2.5 4.0
1.0 15.0 18.0
3.5 3.5 3.5
6.0 5.0 10.0
Each column represents, Length, Width and Height respectively.
When I read the text file, each row is treated as a single node.
I'm trying to see if there's a way to find the product of each row, the volume?
If it's not possible, then I need to find a way to call on the values read, individually(l,w,h) from another class in which I've created a method to getVolume().
Well here's my code so far: As always thank you in advance for all your help!
import java.util.LinkedList;
import java.util.*;
import java.io.*;
public class Runtime2 {
public static void main(String args[])throws Exception {
String content = new String();
int count=0;
File file = new File("dims.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
list.add(content);
}
sc.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println();
}
Iterator i = list.iterator();
while (i.hasNext()) {
System.out.print("Node " + count++ + ": ");
System.out.println(i.next());
}
public class Box {
double length;
double width;
double height;
Box(double l, double w, double h ) {
length=l;
width=w;
height=h;
}
double getVolume() {
double vol=length*width*height;
return vol;
}
boolean isCube() {
if(length==width && width==height) {
System.out.println("The box is a cube.");
}
else
System.out.println("The box is not a cube.");
return true;
}
}
private static double getVol(String line)
// line = "2 3 4.5"
String[] nums = line.split(" ");
int len = nums.length;
double vol = 1;
for (int i = 0 ; i < len; i++){
vol*=Double.parseDouble(nums[i]);
}
return vol;
Use nextDouble thrice for each line/row: Demo
double a, b, c;
while(sc.hasNextLine()){
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
Box box = new Box(a, b, c); //System.out.println(a + " " + b + " " + c + "\n");
System.out.println("Volm of box with dimension {" + a + "," + b + "," + c + "} is :" +
box.getVolume() + "\n");
}
You've done a good job of defining your Box class to encode each row of your file so far. The piece that you're missing is mapping from each line of your file to a Box object.
You can create a new Box object using the new operator: new Box(l, w, h).
The next step is to get the length, width, and height from a line within your file. You've already figured out how to get the line into a String variable. The next step is to use the String's split method to extract the values. For example:
String string = "a b c";
String[] values = string.split(" ");
// values[0] now contains "a";
// values[1] now contains "b";
// values[2] now contains "c";
Finally, use the List add method to append the new `Box to your list. I recommend structuring your code so that the file reading is encapsulated within its own method, so you might try something like this:
public class Runtime2 {
public static void main(String args[]) throws Exception {
List<Box> boxes = readBoxesFromFile(new File("dims.txt"));
for (int i = 0; i < boxes.size(); i++) {
System.out.println("Box " + i + " volume: "
+ boxes.get(i).getVolume());
}
}
private static List<Box> readBoxesFromFile(File file) {
List<Box> boxes = new LinkedList<Box>();
/*
* - Create File object
* - Create Scanner for File
* - For each line in the file
* Split the line into a string array
* Create a 'Box' instance
* Add the Box to your list
*/
return boxes;
}
}
I've omitted the imports, and the definition of the Box class for Brevity, but you've already got those defined within your question.
With that in mind, try putting these pieces together to construct your method for converting your file into a List of Box objects.

Categories

Resources