How to Set Java jsp Arrays to my Index.html Table - java

I am an engineering student. I have just started Java with the school. We have an exam next week. I have some questions about our preparing project.
I'd be very happy IF you could patiently reply to them.
Create a Java class called Lane with three fields:
o days: a read-only string collection containing the names of days [ How to make a read-only string ]
How to put into my index file? ( Normally I learned like <% between those %> but get some error messages..
How do I make reservation Array?
reservations: a collection to store the reservations (e.g. a twodimensional string array or a
list of string lists), where the number
of rows equals the number of days, and the number of columns
equals the number of times. The i. row - j. column cell’s value is
„available” if the i-th day’s j-th time interval is still available, or
the username of the reserving person otherwise.
Last Question ; How to Make such as below the picture.
Reserved text if the lane is already reserved by someone else for
that day and time (different username than the user’s),
o a Reserve link if the lane is available,
o a Cancel link if the lane is reserved by this user.

If I understand correctly you are stuck on creating the reservations table?
This is the class I came up with that is pretty close to yours.
I'm not sure what you mean by read-only string, I just used constants (final keyword)
We create a 2d array the same way we would a normal array (using []), except we do it twice. When using 2d arrays in Java the first value refers to rows an the second one to columns (new String[number_of_rows][number_of_columns]).
We than set up 3 possible values for ReservedState
We populate our array in the constructor
We also set up 3 methods we can use to change values in the table.
import java.util.Arrays;
public class Lane {
final String[] days = {"Monday", "Tuesday", "..."};
final String[] times = {"5-6 PM", "6-7 PM"};
//this is where we create our reservations table
String[][] reservations = new String[days.length][times.length];
enum ReservedState {
RESERVED("Reserved"),
RESERVE("Reserve"),
CANCEL("Cancel");
private String name;
ReservedState(final String name){
this.name = name;
}
}
//constructor
public Lane(){
//Fill the table with default values
for (String[] row: reservations)
Arrays.fill(row, ReservedState.RESERVE.name);
}
public void SetReservationToReserved(int dayIndex, int timeIndex){
reservations[dayIndex][timeIndex] = ReservedState.RESERVED.name;
}
public void SetReservationToCancel(int dayIndex, int timeIndex){
reservations[dayIndex][timeIndex] = ReservedState.CANCEL.name;
}
public void SetReservationToReserve(int dayIndex, int timeIndex){
reservations[dayIndex][timeIndex] = ReservedState.RESERVE.name;
}
}
About Including your code in the index,
It would be very useful if you could show us the error you are getting. I think you just forgot to instantiate your class before using it.
<%
Lane lane = new Lane();
//lane.SetReservationToReserved(1,1); Call this to set a reservation
//lane.SetReservationToCancel(row number, column number); Call this to cancel a reservation
//lane.SetReservationToReserve(1,1);...
%>
As for rendering the table with html and jsp I would recommend this resource. It has several good examples on the topic.
https://www3.ntu.edu.sg/home/ehchua/programming/java/JSPByExample.html

Related

JAVA seperate class method not incrementing a variable in my main class method

so this is the main code for my text-based game.
import java.util.Scanner;
public class D_M_RPG {
public static void main(String[] args) {
//Creating the class to call on my toolbox
D_M_RPGtoolbox toolbox = new D_M_RPGtoolbox();
//Creating the scanner class for user input
Scanner input = new Scanner(System.in);
//Initiating variables and final variables aswell as arrays
//token variable to validate open spots in an array
int slotCounter = 0;
int inventoryExpander = 11;
//First initiated will be the character creation variables
String hairColor = "";
String eyeColor = "";
String skinColor = "";
String gender = "";
//Initiating the arrays for character inventory slots
String[] weaponSlots = new String[10];
//initiating the arrays for the character creation
String[] hairColorARR = {"black","Green","Yellow","Brown","Blue","Blonde","Grey","White"};
String[] eyeColorARR = {"Green","Brown","Blue","Grey",};
String[] skinColorARR = {"White","brown","Black",};
String[] genderARR = {"Male","Female"};
//Creating the introduction title and introduction
System.out.println("Welcome to, COLD OMEN.");
System.out.println("\nNOVEMBER 12th, 2150: ONTARIO, CANADA");
System.out.println("\nYou hear loud shouts and gun fire all around you but can't pinpoint the location of anything, you feel a bit dazed until someone grabs you and you open your eyes and snap out of it.");
System.out.println("\nUnknown: 'Get up, its time to move out. Take this.'");
System.out.println("\nUnknown hands you a 'M4-A4 RIFLE'");
System.out.println("\nyou manage to catch a small glimpse of him before you get up.");
//Character creation screen
System.out.println();
//ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "M4-A4 RIFLE");
System.out.println("\n" + weaponSlots[0]);
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "ak47");
System.out.println(weaponSlots[0]);
}
}
so I have this method I made to basically add an "item" to the weaponSlots array (the inventory) but whenever I run it it will add to the first element in the array [0] but it wont incremement the slotcounter which should go up by one every time the method is used so that I dont replace any items in the array It should just add items until its full which is checked using the inventoryExpander variable. at the moment I have it printing the element at 0 and 0 for the array but i have checked 1 aswell and 1 is just null no item added it only just replaces the element at 0. heres the code for the method to increment etc:
public class D_M_RPGtoolbox {
//method for random number generating to be used for crit hits, turns, loot generation etc
public int randomGen(){
int x = (int) (Math.random()*((20-0)+1)+0);
return x;
}
//method for inserting into an array ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER FIX
public void insert(String[] a, int b, int d , String c) {
if(b < d) {
a[b] = c;
b++;
}//end of if statement
}//end of method
}
What you are actually performing the ++ operation on in b is a copy of the value in slotCounter.
The variable slotCounter is passed into insert "by-value".
This unlike what you probably imagine, that it is passed "by-reference".
One solution would be to do the slotCounter++ from the call row instead; and another would be to let the toolbox own the slotCounter variable completely.
This question uses the image of passing a copy of document content (by value) where changes to the document would not be seen by the sender; or as a link to a shared document (by reference), where changes could be made to the same page that the sender sees.
Its always going to be zero since you are passing zero and incrementing the local variable b.
Try calling the method as below with post increment ++ to slotCounter and see if it works for you,
toolbox.insert(weaponSlots, slotCounter++, inventoryExpander, "M4-A4 RIFLE");

Sorting, finding average, comparing and much more in 2D Object array

I need to store information, including string ,int and double and to perform some actions with it. So, I made an 2D array Object arr [][] = new Object [100][5]; The columns are -              String String int(may be double/float) Double(may be float) Date User have to insert all info by his own, so let's imagine we have smth like this:
name author nr price date
yyy aaa 1 10.0 10.02.2013
zzz bbb 2 20.0 11.03.2014
xxx aaa 3 30.0 12.04.2015
So, I try to do following things: (I would really appreciate any piece of help to any of those!)
User has to insert author name (column 2) and program should give him average price of all goods by this author (from column 4). Here's my code:
double count=0;
double s=0;
System.out.println("Type author");
scan.next();
String auth = scan.nextLine();
for(int i=0; i<arr.length; i++) {
if(arr[i][1].equals(auth)){
count++;
s = s+(double) arr [i][3];
}
}
double average = 0;
average = s/count;
System.out.println("Average:" + average);
However, it gets NaN in result. As far as I understand the problem is that my array is an object, but I need to get numbers. One thing I can think of - is to make additional array of these numbers and then count average in it, but it doesn't sound good.
Second problem - I need to do two types of this 2D array sorting - by name (column 1) and price (column 4). Actually, I don't have an idea how to to this and don't know if it is even possible. I have read about 2D column sorting in different topics, but they were about pure string or pure int arrays. Had an idea to divide it to different arrays, but don't know if it worth it. I would appreciate any help in solving this question.
And last one - how do I implement date to my array? I mean, is there a way to add it, that it would look like 20.02.2013, not smth like Sat Jan 02 00:00:00 GMT 2010. I could make it a simple string, but I need to have the ability to compare dates later (user inserts date, but program shows all rows after it). Right now I have made date like an ordinary double type number and have comparing code like:
System.out.println("Insert date");
double date1 = scan.nextDouble();
for (int i=0; i<arr.length; i++){
if (arr[i][4]!=null) {
if((double)arr[i][4]>date1)
System.out.println(arr[i][0]);
}
}
Works fine, but would smth like that work for actual dates?
Thanks in advance, I will appreciate any help in solving any of those problems. Or maybe my life can be easier, if I change my Object array to something else?
You should use a list of rows as data structure. One particular row should be some kind of tuple type (you may want to write a class for this).
Then you can implement selection by iterating over the list of rows and retaining any row matching a specific predicate (use java 8 for this).
Sorting is trivial since you can just use the (row) list's sort method by using some custom Comparator instance.
You can implement column projection by iterating over the list of rows and inserting the values of a column into a special list per column. Then you can do average, sumation, whatever on these lists.
For representing dates you should use the classes provided by the standard library. You may want to use a SimpleDateFormat instance for formatting the date as you prefer.
You should really try using objects. Start by making a class to represent your data model:
public class Book {
private String name;
private String author;
private int nr;
private double price;
private Date date;
public Book(String name, String author, int nr, double price, Date date) {
this.name = name;
this.author = author;
this.nr = nr;
this.price = price;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// repeat for other getters/ setters.
}
Now that you have a class you can start taking advantage of java's built in libraries. Start off by using a List to hold your data:
List<Book> books = new ArrayList<Book>();
The list can be thought of as the outer array, and the fields in each Book object can be thought of as the columns. You can now add entries like this:
books.add(new Book("yyy", "aaa", 1, 10.0, new Date(10, 02, 2013)));
books.add(new Book("zzz", "bbb", 2, 20.0, new Date(11, 03, 2014)));
books.add(new Book("xxx", "aaa", 3, 30.0, new Date(12, 04, 2015)));
Lets do some examples:
User has to insert author name (column 2) and program should give him average price of all goods by this author (from column 4).
final String auth = scan.nextLine();
final double average = books.stream()
.filter(book -> book.getAuthor().equals(auth))
.mapToDouble(Book::getPrice)
.average();
I need to do two types of this 2D array sorting - by name (column 1) and price (column 4)
books = books.stream()
.sorted(Comparator.comparing(Book::getName)
.thenComparing(Book::getPrice))
.collect(Collectors.toList());

Deleting and Inserting Elements in Array [duplicate]

This question already has answers here:
How to remove specific element from an array [duplicate]
(6 answers)
Closed 8 years ago.
public class Example {
public static void main(String [] args) {
String [] wombology;
wombology = new String[3];
wombology[0] = "History of Wombology";
wombology[1] = "Why Wombology";
wombology[2] = "Wombology and Me";
Random book = new Random(System.currentTimeMillis());
Scanner choice = new Scanner(System.in);
String yourChoice;
do {
System.out.println("Press enter for random book");
yourChoice = choice.nextLine();
if(yourChoice.equals("")) {
System.out.println(wombology[randomizer.nextInt(3)]);
System.out.println();
}
if(yourChoice == "EXIT") {
break;
}
} while(!yourChoice.equals("EXIT"));
}
}
How could I take out a "book" from the array once chosen randomly?
How could I put back in said "book" later back into the array?
Example: "History of Wombology" is randomly chosen and is taken out.
The next random selection should NOT include "History of Wombology" until it is put back in.
Meaning only "Why Wombology" and "Wombology and Me" should be the only possible choices.
I'm assuming that this is homework and an ArrayList is not possible. And I don't want to give a full, detailed answer.
One option might be to create a parallel array, boolean isCheckedOut[], and track your books there.
You need to manage the array yourself. That means you need to know the real size of the array and the filled size. This is because once the array is created the size cannot change.
If you delete an object from the array you need to shift the adjacent elements towards that position.
For example, your array looks like this:
[A|B|C|D|E|F]
allocatedArraySize = 6
currentSize = 6
If you delete C which is at position 2 then you must shift D, E, F to the left. You could also make the last position null.
[A|B|D|E|F|null]
allocatedArraySize = 6
currentSize = 5
To insert, simply use this:
// Check Array is not full.
if(currentSize != allocatedArraySize)
{
// Then add your object to the last position in the array.
array[currentSize] = obj;
// Increment the index.
currentSize++;
}
else
{
// Don't allow insertion.
// Or create a new-bigger-array;
// then copy all elements of the full array into it.
}
You have to "define" an action for "taking out a book" on the technical level. I can image two possibilities for this
setting the array content at the specific position to null
setting the array content at the specific position to an empty string
As the title of most books consists of one or more letters, the empty string-proposal seems also to be valid.
The second task (putting a book back into the array) can be handled in a similar way. Here you have to find an empty place (an array position with an empty string/null as content) and assign the name of the book to it.
Concerning the randomizer and not allowing already removed books: you can use the aforementioned condition to rerun the randomizer, i.e until an non-empty string/not-null element is found in the array. If you found one, it is a valid choice. But beware, if you removed all books, the randomizer would never stop running (because it finds only invalid choices and hence never returns). Here you can use an additional check condition: if the array only consists of empty strings/ null values, it is not required to run the randomizer.
Hope that helps...

Trying to get a random element from an array so that I can mark it as "booked"

This is what I have in my method to randomly select a element in my array, however I'm not sure why it isn't working, I feel like I have tried every way of writing it, any ideas.
public static Seat BookSeat(Seat[][] x){
Seat[][] book = new Seat[12][23];
if (x != null){
book = x[(Math.random()*x.length)];
}
return book;
}
The way you explain things makes me think a couple of concepts somehow got crosswired. I am assuming that book is some (2 dimensional) array of Seat objects from which you want to pick a random one. In order to do so, you need to specify a random choice for each dimension of the array:
// this should be declared elsewhere because if it's local to bookSeat it will be lost
// and reinitialized upon each call to bookSeat
Seat[][] book = new Seat[12][23];
// and this is how, after previous declaration, the function will be called
Seat theBookedSeat = bookSeat(book);
// Okay, now we have selected a random seat, mark it as booked, assuming Seat has a
// method called book:
theBookedSeat.book();
// and this is the modified function. Note also that function in Java by convention
// start with a lowercase letter.
public static Seat bookSeat(Seat[][] x){
if (x != null){
// using Random as shown by chm052
Random r = new Random();
// need to pick a random one in each dimension
book = x[r.nextInt(x.length)][r.nextInt(x[0].length)];
}
return book;
}
You should also integrate a test to check whether the selected seat was already booked and repeat the selection:
do {
// need to pick a random one in each dimension
book = x[r.nextInt(x.length)][r.nextInt(x[0].length)];
while (book.isBooked()); // assuming a getter for a boolean indicating
// whether the seat is booked or not
But a full-random selection like this has a couple of disadvantages:
the selection being random, you can repeatedly fall on already booked seats, and the chances that happens increase with the number of already booked seats. But even with few booked seats you could be really unlucky and see the loop spin around tens of times before it hits an unbooked seat.
you should absolutely test whether there are still unbooked seats left before entering the loop or it will spin indefinitely.
Therefore it might be a good idea to implement a smarter selection routine, eg by randomly picking a row and a seat and start searching from there until the first free seat is encountered, but for first steps this one should do just fine.
I hope this is what you wanted to achieve, if not feel free to comment and allow me to correct and adapt.
Floor the number returned by the (Math.random()*x.length) expression.
Math.floor(Math.random()*x.length);
At the moment, you're trying to subscript the array with a floating point number.
The other answer will totally work, but here is another way of doing it using Random.nextInt() if you don't want to have to do all the mathing around:
Random r = new Random();
book = x[r.nextInt(x.length)];
It uses java.util.Random, so make sure you import that if you do this.

Read txt file into array then find min max and average of salaries

Looks like this is the week for this type of question. And after reading through all of the new ones and several old ones, I'm no less confused!
I have a text file with 5 employees, each having 10 salary values listed beneath their name. I am to read in this file, find and display the employee Name, minimum salary, maximum salary and the average salary for each person. I must have 3 loops: One to control reading the file, one to lad the data into the array, and one to do the calculations. I have to print the information for each person on one line, and i must allow decimals rounded to 2 decimal places apparently using Math.round which I've never heard of!
I am embarrassed to show you the mess of code I have because it's not much, but I don't know after reading all that I have if I've even started correctly. I do not know if I have even the right idea of how to proceed. Your help is appreciated.
UPDATED CODE: AGAIN!
import javax.swing.*;
import java.io.*;
public class MinMaxSalary3
{
public static void main(String args[])throws Exception
{
// Declare input file to be opened.
FileReader fr = new FileReader ("salary.dat");
BufferedReader br = new BufferedReader (fr);
//General Declarations
final String TITLE = "Employee's Salary Report";
String employeeName, salaryString;
double avgSalary=0.0;
double totalSalary = 0.0;
double sum = 0.0;
// Declare Named Constant for Array.
final int MAX_SAL = 10;
// Declare array here.
int salary[] = new int[MAX_SAL];
System.out.println (TITLE);
while ((employeeName = br.readLine()) != null)
{
System.out.print ("" + employeeName);
// Use this integer variable as your loop index.
int loopIndex;
// Assign the first element in the array to be the minimum and the maximum.
double minSalary = salary[1];
double maxSalary = salary[1];
// Start out your total with the value of the first element in the array.
sum = salary[1];
// Write a loop here to access array values starting with number[1]
for (loopIndex = 1; loopIndex < MAX_SAL ;loopIndex++)
// Within the loop test for minimum and maximum salaries.
{
if (salary[loopIndex] < minSalary)
{
minSalary = salary[loopIndex];
if (salary[loopIndex] > maxSalary)
maxSalary = salary[loopIndex];
}
{
// Also accumulate a total of all salaries.
sum += sum;
// Calculate the average of the 10 salaries.
avgSalary = sum/MAX_SAL;
}
// I know I need to close the files, and end the while loop and any other loops. I just can't think that far right now.
}
{
// Print the maximum salary, minimum salary, and average salary.
System.out.println ("Max Salary" + maxSalary);
System.out.println ("Min Salary" + minSalary);
System.out.println ("Avg Salary" + avgSalary);
}
System.exit(0);
}
}
}
I must have 3 loops: One to control reading the file, one to lad the
data into the array, and one to do the calculations.
What I've written below might just be more gobbledygook to you now, but if you ever get past this class it might be useful to know.
Another way to look at this would be more object-oriented and better decomposition to boot: You need an object to hold the data, to perform the calculations, and render output. How you get that data is immaterial. It's files today; next time it might be HTTP requests.
Start with an Employee object. I deliberately left out a lot of detail that you'll have to fill in and figure out:
package model;
public class Employee {
private String name;
private double [] salaries;
public Employee(String name, int numSalaries) {
this.name = name;
this.salaries = new double[numSalaries];
}
public double getMinSalary() {
double minSalary = Double.MAX_VALUE;
// you fill this in.
return minSalary;
};
public double getMaxSalary() {
double maxSalary = Double.MIN_VALUE;
// you fill this in.
return maxSalary;
}
public double getAveSalary() {
public aveSalary = 0.0;
if (this.salaries.length > 0) {
// you fill this in.
}
return aveSalary;
}
}
The beauty of this approach is that you can test it separately, without worrying about all the nonsense about file I/O. Get this object right, put it aside, and then tackle the next piece. Eventually you'll have a clean solution when you assemble all these smaller pieces together.
Test it without file I/O using JUnit:
package model;
public class EmployeeTest {
#Test
public void testGetters() {
double [] salaries = { 10000.0, 20000.0, 30000.0, 40000.0 };
Employee testEmployee = new Employee("John Q. Test", salaries);
Assert.assertEquals("John Q. Test", testEmployee.getName());
Assert.assertEquals(10000.0, testEmployee.getMinSalary(), 1.0e-3);
Assert.assertEquals(40000.0, testEmployee.getMaxSalary(), 1.0e-3);
Assert.assertEquals(25000.0, testEmployee.getMinSalary(), 1.0e-3);
}
}
The approach you would want to espouse in this situation is an object-oriented approach. Bear in mind that objects are a representation of related data. Consider that an Employee may have information about their salary, name, and what department they work in (as an example).
But that's just one Employee. You may have hundreds.
Consider creating a model of an Employee. Define what is most pertinent to one of them. For example, they all have to have a name, and have to have a salary.
One would then elect to handle the logic of finding information about the collection of Employees - including min, max, and average salaries - outside of the scope of the generic Employee object.
The idea is this:
An Employee knows everything about itself.
The onus is on the developer to tie multiple Employees together.
It's possible that I don't know enough about what your problem is specifically looking for - I'm not even sure that you can use objects, which would really suck - but this is definitely a start.
As for your compilation errors:
salary is a double[]. An array holds many different values of type double inside of it, but a double[] isn't directly a double. Assigning a non-array type to an array type doesn't work, from both a technical stance, and a semantic stance - you're taking something that can hold many values and trying to assign it to a container that can hold one value.
From your code sample, you want to use a loop (with a loop variable i) to iterate over all elements in salary, and assign them some value. Using just salary[0] only modifies the first element.

Categories