We have a practical test on Java about an IceCream shop. We need to handle exceptions in case no more stock. The code from the app below works fine. Exceptions are properly managed.
public class IceCreamApp2 {
public static void main(String[] args) {
Prijslijst priceList2 = new Prijslijst(2, 5, 8);
Stock stock = new Stock(1, 8, 2, 1);
IceCreamCar iceCar = new IceCreamCar(priceList2, stock);
try {
Eatable[] eatCar = {
iceCar.orderCone(new Cone.Flavor[]{Cone.Flavor.CHOCOLATE, Cone.Flavor.BANANA, Cone.Flavor.VANILLA}),
iceCar.orderCone(new Cone.Flavor[]{Cone.Flavor.VANILLA, Cone.Flavor.VANILLA}),
iceCar.orderMagnum(Magnum.MagnumType.ROMANTICSTRAWBERRIES),
iceCar.orderMagnum(Magnum.MagnumType.ALPINENUTS),
iceCar.orderIceRocket()
};
for (int i = 0; i < eatCar.length; i++) {
eatCar[i].eat();
}
System.out.println(iceCar.getProfit());
} catch (NoMoreIceCreamException noMoreIce) {
System.out.println("No More Ice To sell... Beat it!!");
System.out.println("Message: " + noMoreIce.getMessage());
System.out.println("Cause: " + noMoreIce.getCause());
}
System.out.println(iceCar.getProfit());
}
}
However this logic is flawded, since it stops counting the rest of order when an exception appears. Therefore Magnums and Icerockets, despite they 're in stock, are not counted in profit.
To do this, we know we need to loop through the table "Eatable". But it doesn't work and exit code 1 with the exception:
public class IceCreamApp2 {
public static void main(String[] args) {
Prijslijst priceList2 = new Prijslijst(2, 5, 8);
Stock stock = new Stock(1, 8, 2, 1);
IceCreamCar iceCar = new IceCreamCar(priceList2, stock);
Eatable[] eatCar = {
iceCar.orderCone(new Cone.Flavor[]{Cone.Flavor.CHOCOLATE, Cone.Flavor.BANANA, Cone.Flavor.VANILLA}),
iceCar.orderCone(new Cone.Flavor[]{Cone.Flavor.VANILLA, Cone.Flavor.VANILLA}),
iceCar.orderMagnum(Magnum.MagnumType.ROMANTICSTRAWBERRIES),
iceCar.orderMagnum(Magnum.MagnumType.ALPINENUTS),
iceCar.orderIceRocket()
};
for (int i = 0; i < eatCar.length; i++) {
try {
eatCar[i].eat();
} catch (NoMoreIceCreamException noMoreIce) {
System.out.println("No More Ice To sell... Beat it!!");
System.out.println("Message: " + noMoreIce.getMessage());
System.out.println("Cause: " + noMoreIce.getCause());
}
}
System.out.println(iceCar.getProfit());
}
}
Any clue what can be wrong ?
Here is the stack trace :
Preparing your Balls on a cone
Exception in thread "main" Seller.NoMoreIceCreamException: No more Balls or Cones
at Seller.IceCreamCar.prepareCone(IceCreamCar.java:39)
at Seller.IceCreamCar.orderCone(IceCreamCar.java:30)
at App.IceCreamApp2.main(IceCreamApp2.java:18)
Process finished with exit code 1
#Andrew S the condition is already handled in the class “IceCreamCar”. In short:
public class IceCreamCar implements IceCreamSeller {
// Instance Variables
Prijslijst priceList;
Stock stock;
private double profit;
// Constructor
public IceCreamCar() {
}
public IceCreamCar(Prijslijst priceList, Stock stock) {
this.priceList = priceList;
this.stock = stock;
}
// Methods
// Order Cone
#Override
public Cone orderCone(Cone.Flavor[] balls) {
this.prepareCone(balls);
return new Cone(balls);
}
// // Prepare Cone
private Cone prepareCone(Cone.Flavor[] balls) {
int countCones = 1;
if (stock.getCones() < 0 || stock.getBalls() < 0) {
throw new NoMoreIceCreamException("No more Balls or Cones");
} else {
for (int i = 0; i < balls.length; i++) {
stock.setBalls(stock.getBalls() - balls.length);
profit += priceList.getBallPrice();
}
System.out.println("Preparing your Balls on a cone");
countCones++;
stock.setCones(stock.getCones() - countCones);
}
return new Cone(balls);
}
thanks to both of you for your answer :)
Ok, so problem solved. Actually the solution is to put the try and catch in each of the orderCone, orderMagnum, etc...
That was exceptions are handled properly.
Related
I'm working on this project and I'm in the process of creating the searchStore() method in User class but I can't think of any way to access the cost of the candies in a certain store.
When the user searches for a store, the program should print the stores that is nearby the landmarks, so if the user visits the lm 4 and lm1, Lolli's and Guccini's store would print. I need to access the cost of the candies in the store to check if the money of the user is enough to buy a candy. If the money is sufficient, then it should print that the user can buy a candy in the store, else it should prompt that the money is not enough to buy a candy.
I tried to create an instance inside the method but that's not correct because if I am to make a new instance, I'm not accessing the cost of the store that I want, but the cost of the instance that I created.
I also tried the getter method in the CandyStore class but it says that I should make the attribute cost static but that is not possible because the cost varies in different stores.
Can someone help me to implement the searchStore method in User class?
MAIN CLASS
package testing;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World");
User user1 = new User("Mylah", 1, 20f);
User user2 = new User("Meg", 2, 50f);
User user3 = new User("Marga", 3, 25f);
Landmark lm1 = new Landmark("Vista Mall", 1);
Landmark lm2 = new Landmark("Vista Residences", 2);
Landmark lm3 = new Landmark("Vista Park", 3);
Landmark lm4 = new Landmark("Crystal Mall", 4);
Landmark lm5 = new Landmark("Crystal Residences", 5);
Landmark lm6 = new Landmark("Crystal Park", 6);
CandyStore c1 = new CandyStore("Lolli's Store", 1, 15);
CandyStore c2 = new CandyStore("Mary's Store", 2, 25);
CandyStore c3 = new CandyStore("Guccini's Store", 3, 10);
c1.addLandmark(lm4);
c1.addLandmark(lm6);
c2.addLandmark(lm2);
c2.addLandmark(lm3);
c3.addLandmark(lm1);
c3.addLandmark(lm5);
user1.visits(lm4);
user1.visits(lm1);
user1.searchStore();
user1.viewState();
}
}
USER CLASS
package testing;
public class User {
String name;
int StudentId;
float money;
Landmark[] lm;
int lmCounter;
static int MAX_LM = 3;
User(String n, int id, float m) {
this.name = n;
this.StudentId = id;
this.money = m;
this.lm = new Landmark[User.MAX_LM];
}
void visits(Landmark l) {
if(this.lmCounter < MAX_LM) {
this.lm[this.lmCounter++] = l;
} else {
System.out.println("Please go home, you visited too many places already!\n");
}
}
void searchStore() {
//insert code here
}
void viewState() {
System.out.println("\n======== VIEW STATE ========");
System.out.println("Student ID: " + this.StudentId);
System.out.println("Student Name: " + this.name);
System.out.println("Student's Money: " + this.money);
if(this.lmCounter == 0) {
System.out.println(this.name + " is still in school!\n");
} else {
System.out.println(this.name + " visited :");
for (int i = 0; i < lmCounter; i++) {
Landmark L = lm[i];
int j = i+1;
System.out.println(j + ". " + L.name);
}
}
}
}
CANDYSTORE CLASS
package testing;
public class CandyStore {
String name;
int StoreId;
float cost; // cost of candies inside the store
int sales;
Landmark[] LM;
int lmCounter;
static int MAX_LM = 3;
CandyStore(String n, int id, float c) {
this.name = n;
this.StoreId = id;
this.cost = c;
this.sales = 0;
this.LM = new Landmark[CandyStore.MAX_LM];
}
void addLandmark(Landmark lm) {
if(this.lmCounter < MAX_LM) {
this.LM[this.lmCounter++] = lm;
} else {
System.out.println("Can't add landmark\n");
}
}
void ViewState() {
System.out.println("\n======== VIEW STATE ========");
System.out.println("Store ID: " + this.StoreId);
System.out.println("Store Name: " + this.name);
System.out.println("Store Sales: " + this.sales);
System.out.println("Landmark nearby");
if(lmCounter == 0) {
System.out.println("The store doesn't have any recognizable landmark\n");
} else {
for(int i = 0; i < lmCounter; i++) {
Landmark l = LM[i];
int j = i+1;
System.out.println(j + ". " + l.name);
}
}
}
}
LANDMARK CLASS
package testing;
public class Landmark {
int LMid; // landmark number
String name;
Landmark (String n, int id) {
this.name = n;
this.LMid = id;
}
void viewState() {
System.out.println("\n======== VIEW STATE ========");
System.out.println("Landmark Number: " + this.LMid);
System.out.println("Landmark Name: " + this.name);
}
}
PS. Please show me how to do the code correctly, thank you.
The problem is void searchStore() needs some help finding the stores from the class that created the CandyStores.
Your stores are created in the Main class so that's where we need code to find the nearby stores and pass them along to the searchStore() method, which I suggest renaming to searchStores().
Consider the following example. I added comments throughout the added code to explain what it does, and some tips to improve.
MAIN CLASS
public class Main {
//class variable so that we can access candyStore list in other methods
public static List<CandyStore> candyStores;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World");
User user1 = new User("Mylah", 1, 20f);
User user2 = new User("Meg", 2, 50f);
User user3 = new User("Marga", 3, 25f);
Landmark lm1 = new Landmark("Vista Mall", 1);
Landmark lm2 = new Landmark("Vista Residences", 2);
Landmark lm3 = new Landmark("Vista Park", 3);
Landmark lm4 = new Landmark("Crystal Mall", 4);
Landmark lm5 = new Landmark("Crystal Residences", 5);
Landmark lm6 = new Landmark("Crystal Park", 6);
CandyStore c1 = new CandyStore("Lolli's Store", 1, 15);
CandyStore c2 = new CandyStore("Mary's Store", 2, 25);
CandyStore c3 = new CandyStore("Guccini's Store", 3, 10);
c1.addLandmark(lm4);
c1.addLandmark(lm6);
c2.addLandmark(lm2);
c2.addLandmark(lm3);
c3.addLandmark(lm1);
c3.addLandmark(lm5);
//Create a list of stores for easy lookup
candyStores = List.of(c1, c2, c3);
user1.visits(lm4);
user1.visits(lm1);
//Use the new method
List<CandyStore> nearbyStores = findNearbyStores(user1);
//Pass along the nearby stores
user1.searchStore(nearbyStores);
user1.viewState();
}
public static List<CandyStore> findNearbyStores(User user) { //Using a method to keep the program code organized
List<CandyStore> nearbyStores = new LinkedList<>(); //Make the candy store output list
Landmark userLandmark = user.lm[user.lmCounter]; //This was complicated, user should have a user.getLandmark() method instead.
for (CandyStore candyStore : candyStores) { //Look through the candystores
if (Arrays.asList(candyStore.LM).contains(userLandmark)) { //Have to convert LM array to list to use basic contains() method (better to just use lists instead of arrays to begin with unless you're building a very efficient server application
nearbyStores.add(candyStore); //Add the candy store to output list if its list of landmarks contains the user's current landmark.
}
}
return nearbyStores;
}
}
Finally, the searchStore() method in the User class can look like this:
void searchStore(List<CandyStore> nearbyStores) {
for (CandyStore candyStore : nearbyStores) { //Check each store
if (money >= candyStore.cost) { //Determine if they have enough money or not enough money
System.out.println("You have enough money to buy candy from " + candyStore.name);
} else {
System.out.println("You don't have enough money to buy candy from " + candyStore.name);
}
}
}
As you become a better Java programmer, you may come to realize that it's best to keep separate data classes, and the classes that manipulate and act upon the data. Data classes shouldn't be intelligent or have access to other data classes. And therefore if you are wanting to access an attribute in another class and can't, that code probably doesn't belong there.
This type of programming can prevent spaghetti code where a trail of code travels very deep throughout the program jumping from class to class rather than having all its cards laid out on the table in front of it.
Hereby a draft solution. However, for it to work, you need to modify existing code a bit (I marked new lines with ***):
LANDMARK
public class Landmark {
int LMid; // landmark number
String name;
// ***
CandyStore nearbyStore;
Landmark (String n, int id) {
this.name = n;
this.LMid = id;
}
void viewState() {
System.out.println("\n======== VIEW STATE ========");
System.out.println("Landmark Number: " + this.LMid);
System.out.println("Landmark Name: " + this.name);
}
// ***
CandyStore getNearbyStore() {
return nearbyStore;
}
// ***
void setNearbyStore(CandyStore candyStore) {
nearbyStore = candyStore;
}
}
CANDYSTORE
...
void addLandmark(Landmark lm) {
if(this.lmCounter < MAX_LM) {
this.LM[this.lmCounter++] = lm;
// ***
lm.setNearbyStore(this);
} else {
System.out.println("Can't add landmark\n");
}
}
...
// ***
float getCandyCost() {
return cost;
}
...
and finally the USER
...
void searchStore() {
// insert code here
System.out.println("Stores nearby visited landmarks:");
for (int i = 0; i < lmCounter; i++) {
Landmark visitedLandmark = lm[i];
CandyStore store = visitedLandmark.getNearbyStore();
store.ViewState();
if (store.getCandyCost() > money) {
System.out.println("The candies are too expensive here, bad luck :(");
} else {
System.out.println("Good news! You can buy a candy in this store!");
}
}
}
...
I'm trying to understand the benefits of multithreading much better. I have with me a serialised implementation of a parking lot simulation. I want to make it so that the program uses Executor services instead, how would I go about doing that?
Below is my parking-lot class, the implementation could definitely be refined, I just can't seem to figure out how to.
public class Parking {
public static void main(String[] args) throws InterruptedException {
Parking parkingObj = new Parking();
parkingObj.runSimulation();
}
public void runSimulation() throws InterruptedException{
int numOfRuns = 101;//100 runs
int currentRuns = 1;
securityGuard myGuard = new securityGuard();
//spot mySpot = new spot();
ArrayList<ticketClass> ticketArray = new ArrayList<>();
int bouncedCustomers = 1;
spot availableSpot = new spot();
//Random randomExit = new Random();
while (currentRuns < numOfRuns){
Random randomSleep = new Random();
//Car object instantiation
carClass vehicle = new carClass();
//ticketClass ticketObj = new ticketClass();
//Random time generator
Random randomTime = new Random();
//instantiation of the info geneatator class
infoGenerator info = new infoGenerator();
//Generaring random Car info
String plateNumber = info.plateGenerator();
String carModel = info.modelGenerator();
String color = info.colorGenerator();
if (availableSpot.getSpotNum() == 15 ){
System.out.println("Carpark full, No cars allowed unitl a space is free");
//Customers waiting for free space
Thread.sleep(9000);
System.out.println("Total Waiting customers: " + bouncedCustomers);
bouncedCustomers += 1;
}
else{
//System.out.println("Customer Exiting");
Thread.sleep(randomTime.nextInt(5000));
meterClass myMeter = new meterClass();
ticketClass myTicket = myGuard.ticketGenerator(vehicle, myMeter);
//ticketClass myTicket = new ticketClass();
myTicket.setmeter(myMeter);
myTicket.setCar(vehicle);
myTicket.getCar().plateSetter(plateNumber);
myTicket.getCar().colorSetter(color);
myTicket.getCar().modelSeter(carModel);
myTicket.getCar().minSetter(randomTime.nextInt(100));
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
myMeter.setPurchasedMinutes(randomTime.nextInt(72));
System.out.println("\n\nCar " + currentRuns + " has entered the car park");
System.out.println("\nCAR DETAILS:");
System.out.println(carModel);
System.out.println(plateNumber);
System.out.println(color);
int spotAvail = availableSpot.assignSpot();
myTicket.setSlotNum(spotAvail);
//Set the time the car entered
String timeIn = info.timeMonitor();
//myTicket.
ticketArray.add(myTicket);
System.out.println("\n\n===Total customers: " + ticketArray.size());
System.out.println(timeIn+"\n");
availableSpot.spotLog();
}
//Cars leaving at random times
for (int i= 0; i < ticketArray.size();i++ ){
meterClass meterOut = ticketArray.get(i).getMeter();
carClass ExitCar = ticketArray.get(i).getCar();
if(myGuard.checkParking(ExitCar,meterOut)){
System.out.println("\nCustomer " + ExitCar.plateGetter()+ " is exiting the carpark...");
double penaltyVal = ticketArray.get(i).getPenalty();
System.out.println("FINE: " + penaltyVal);
System.out.println("==================================================================");
Thread.sleep(randomTime.nextInt(4000));
ticketArray.remove(ticketArray.remove(i));
availableSpot.spotFree(i);
}
}
currentRuns += 1;
}
}
}
TLDR: I need to optimise the following code, both structure-wise and in terms of speed (Specifically using multithreading with Executor service)
As it currently is, it runs in an infinite loop, and the fine value is 0. The security guard class which is responsible for this calculation is as such;
public class securityGuard{
public String badgeNumber;
public String guardName;
securityGuard(){}
securityGuard(String badgeNumber, String guardName){
this.badgeNumber = badgeNumber;
this.guardName = guardName;
}
public void setBadgeNumber(String badgeNumber){
this.badgeNumber = badgeNumber;
}
public String getBadgeNumber(){
return badgeNumber;
}
public void setguardName(String guardName){
this.guardName = guardName;
}
public String getGuardName(){
return guardName;
}
public boolean checkParking(carClass car,meterClass meter){
return car.minGetter() > meter.getPurchasedMinutes();
}
public ticketClass ticketGenerator(carClass car, meterClass meterVar){
ticketClass myTicket = new ticketClass(car,this);
int timeRemaining = car.minGetter() - meterVar.getPurchasedMinutes();
if(checkParking(car,meterVar)){
if (timeRemaining < 60){
myTicket.penalty = 50;
}
else {
myTicket.penalty = 50 + (10 * (timeRemaining/60));
}
}
return myTicket;
}
}
Please let me know if you require any additional information regarding the other classes or if I left anything out .Thank you in advance
Working on a Pizza/Pizza order program in java and I keep getting 13 of the error: class, interface, or enum expected. I know the problem should be with the curly brackets, but I haven't been able to find it. I was hoping that a different set (or sets) of eyes would be able to spot the error(s).
public Pizza (String size, int cheese, int pepperoni, int ham) {
this.size = size;
if (cheese < 0) {
this.cheese = 0;
}
else {
this.cheese = cheese;
}
if (pepperoni < 0) {
this.pepperoni = 0;
}
else {
this.pepperoni = pepperoni;
}
if (ham < 0) {
this.ham = 0;
}
else {
this.ham = ham;
}
}
public double calcCost() {
if (size.equals("small")) {
return 10 + 2 * (ham + cheese + pepperoni);
}
else if (size.equals("medium")) {
return 12 + 2 * (ham + cheese + pepperoni);
}
else if (size.equals("large")) {
return 14 + 2 * (ham + cheese + pepperoni);
}
else {
System.out.println("Invalid size");
}
}
public class PizzaOrder {
private Pizza pizza1;
private Pizza pizza2;
private Pizza pizza3;
public PizzaOrder() {
numPizzas = 1;
pizza1 = new Pizza();
pizza2 = new Pizza();
pizza3 = null;
}
public PizzaOrder (int numPizzas, Pizza pizza1, Pizza pizza2, Pizza pizza3) {
this.numPizzas = numPizzas;
this.pizza1 = pizza1;
this.pizza2 = pizza2;
this.pizza3 = pizza3;
}
public void setNumPizzas (int numPizzas) {
if (numPizzas > 3) {
this.numPizzas = 3;
}
else if (numPizzas < 1) {
this.numPizzas = 0;
}
else {
this.numPizzas = NumPizzas;
}
}
public void setPizza1 (Pizza pizza1) {
this.pizza1 = pizza1;
}
public void setPizza2 (Pizza pizza2) {
this.pizza2 = pizza2;
}
public void setPizza3 (Pizza pizza3) {
this.pizza3 = pizza3;
}
public double calcTotal() {
double total = pizza1.calcCost();
if (numPizzas >= 2) {
total += pizza2.calcCost();
}
if (numPizzas == 3) {
total += pizza3.calcCost();
}
return total;
}
}
public class MainMethodClassName {
public static void main (String args[]) {
Pizza pizza1 = new Pizza("large", 1, 0, 1);
Pizza pizza2 = new Pizza("medium", 2, 2, 0);
PizzaOrder order = new PizzaOrder();
order.setNumPizzas(2);
order.setPizza1(pizza1);
order.setPizza2(pizza2);
double total = order.calcTotal;
System.out.println("First Pizza: ");
System.out.println(pizza1.getDescription());
System.out.println("Second Pizza: ");
System.out.println(pizza2.getDescription());
System.out.println("Total price: $" + total);
}
}
The errors are in lines 1, 4, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, and 36
Thank you for the help; I really appreciate it!
The brackets are not your only problem.
public double calcCost() {
if (size.equals("small")) {
return 10 + 2 * (ham + cheese + pepperoni);
}
else if (size.equals("medium")) {
return 12 + 2 * (ham + cheese + pepperoni);
}
else if (size.equals("large")) {
return 14 + 2 * (ham + cheese + pepperoni);
}
else {
System.out.println("Invalid size");
}
}
This won't compile as in the else you return nothing which is illegal when the return type is specified.
As for the brackets, since you give us line and suppose we should be able to count them correctly with the code you pasted. I believe you copied all this in one single file.
If that is true, then the problem is with the first two method which are not in a class, this is illegal in Java. Either put them in an other class, or add them to an already existing one if this is where they reside.
Also, you should not declare all classes in one single file even if this compile as this will be terrible to maintain.
Like he said.
When you build classes they should encapsulate an idea
Do
public class pizza{
public static pizzaSize(){
}
public static toppings(){
}
}
So on and so forth. If you don't make methods void then they have to have returns, also if you make them static then you can use them in main without instant katsina by calling "class.method()"
I have 200 students waiting to enter a room with 200 seats (25 rows and 8 columns). The door capacity is 4 people. When a student enter the room, he chooses random seat (row and column). If the chosen seat is at 9th row or less it takes 1 second to sit, on 18th and less it takes 2 seconds, and if its from 18 to 25 it takes 3 seconds.
When any of them take a seat another person must come in the room.
The problem is that when the first 4 people enter the room they take seat one by one and not at once. How can I fix that?
For example if 2 people choose a seat at 5th row they both need to sit for 1 seconds and two new students must enter the room.
public class Student
{
int row;
int column;
volatile static int mutex;
//Generating random numbers for row and column
public Student(Seats[][] seats)
{
this.row = (int) Math.ceil(Math.random() * 25);
this.column = (int) Math.ceil(Math.random() * 8);
if (!seats[row][column].isTaken)
{
seats[row][column].isTaken = true;
} else
{
do
{
this.row = (int) Math.ceil(Math.random() * 25);
this.column = (int) Math.ceil(Math.random() * 8);
} while (!seats[row][column].isTaken);
seats[row][column].isTaken = true;
}
}
/*Check if the mutex is 4 (4 people are in the room) then wait
if someone enter the room increment mutex*/
synchronized void add() throws InterruptedException
{
while (mutex > 4)
wait();
Student.mutex++;
notifyAll();
}
/* Check if mutex is 0 (no one is in the room) then wait
if the student has sit - decrement mutex and notify*/
synchronized void takeSeat() throws InterruptedException
{
while (mutex == 0)
wait();
Student.mutex--;
notifyAll();
}
}
class Seats
{
int seat;
boolean isTaken;
public Seats(int seat)
{
this.seat = seat;
this.isTaken = false;
}
}
class StudentThread extends Thread
{
Seats[][] seats = new Seats[25][8];
StudentThread(Seats[][] seats)
{
this.seats = seats;
}
public void run()
{
try
{
Student student = new Student(seats);
synchronized (seats)
{
System.out.println("Student enter the room");
/*call the synchronized method from student
that increment the mutex*/
student.add();
if (Student.mutex == 4)
{
if (student.row <= 9)
{
sleep(1000);
student.takeSeat();
System.out.println("Student take a seat at "
+ student.row + " " + student.column);
}
if (student.row <= 18 && student.row > 9)
{
sleep(2000);
student.takeSeat();
System.out.println("Student take a seat at "
+ student.row + " " + student.column);
}
if (student.row <= 25 && student.row > 18)
{
sleep(3000);
student.takeSeat();
System.out.println("Student take a seat at "
+ student.row + " " + student.column);
}
}
}
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class Main
{
public static void main(String[] args)
{
Seats[][] seats = new Seats[25][8];
//Initializing the seats
for (int i = 0; i < 25; i++)
for (int j = 0; j < 8; j++)
{
seats[i][j] = new Seats(i);
}
for (int i = 0; i < 200; i++)
{
StudentThread T1 = new StudentThread(seats);
T1.start();
}
}
}
Use a Semaphore, they are very practical for these kind of things.
To make the example a bit more realistic: imagine you need to do 200 HTTP get-requests, but the server will ban you if you run more than 4 requests at the same time. The example below shows how you can limit the number of requests running at the same time using a Semaphore.
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class ResourceUsageLimiter {
static ExecutorService executor = Executors.newCachedThreadPool();
static int requests = 20;
static int maxRequestsConcurrent = 4;
static int maxRequestTime = 1000;
static Random randomizer = new Random();
static Semaphore openSlots = new Semaphore(maxRequestsConcurrent);
static long startTime = System.currentTimeMillis();
public static void main(String[] args) {
try {
for (int i = 0; i < requests; i++) {
openSlots.acquire();
executor.execute(new RequestRunner(i));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
static long time() {
return System.currentTimeMillis() - startTime;
}
static class RequestRunner implements Runnable {
int sleepTime, reqId;
public RequestRunner(int reqId) {
this.reqId = reqId;
sleepTime = randomizer.nextInt(maxRequestTime);
}
#Override
public void run() {
try {
System.out.println(time() + " " + reqId + " sleeping " + sleepTime);
Thread.sleep(sleepTime);
System.out.println(time() + " " + reqId + " sleep done");
} catch (Exception e) {
e.printStackTrace();
} finally {
openSlots.release();
}
}
}
}
Ofcourse, another way to limit the maximum number of requests running at the same time in the example is to use a thread pool with a fixed size of 4.
I want to be able to use threads to run two loops at once within my program for a sort of game like program. However I'm not entirely sure how to use Threads and I am encountering errors I know nothing about. I will post code but ignore most of it, it's a somewhat hollow shell of what I want it to be I just need to get threads working to start cleaning it all up.
I'm getting the error "is not abstract and does not override" and it is highlighting the "class game implements runnable" section. This is the code:
public class game implements Runnable
{
#Override
public void run(int time){
try{
time = 1;
while (time<=10){
Thread.sleep(10);
System.out.print(time);
time++;
}
char clearer = (char)(12);
System.out.print(clearer);
System.out.println("You have ran out of time! Game over!");
System.exit(0);
}catch (Exception e){}
}
public static void main (String args[]) throws Exception{
System.out.println("Welcome to pseudo-Where's Wally, look for the lower cal l character.");
Thread.sleep(500);
System.out.println("You get 10 seconds to find it.");
Thread.sleep(500);
System.out.println("Ready?..");
char clear = (char)(12);
Thread.sleep(500);
System.out.print(clear);
boolean timer = false, col = false, guess = false;
int length = 5, time = 0, rowNum = 1, y = 0;
String manip = ("");
int x = (length*length);
Random gen = new Random();
int find = gen.nextInt(x)+1;
for (int collumn = 0; collumn<=length; collumn++){
for (int row = 0; row<=length; row++){
while (!col){
y++;
System.out.print(" "+y);
if (y-1 == length){
System.out.println();
System.out.println();
col = true;
}
}
System.out.print(" I");
manip = manip + (" I");
}
System.out.println("\t" + rowNum);
rowNum++;
manip = manip + (" I");
}
boolean contin = false;
do{
if (find%3==0){
contin = true;
find = find - 1;
} else if (find%3>0){
find = find - 1;
}
}while (!contin);
String newManip = manip.substring(0,find)+'l'+manip.substring(find+1);
String subOne = newManip.substring(0,18);
String subTwo = newManip.substring(18,36);
String subThree = newManip.substring(36,54);
String subFour = newManip.substring(54,72);
String subFive = newManip.substring(72,90);
String subSix = newManip.substring(90,108);
System.out.println(subOne);
System.out.println(subTwo);
System.out.println(subThree);
System.out.println(subFour);
System.out.println(subFive);
System.out.println(subSix);
Thread threadA = new ThreadA();
threadA.start();
while(guess != true){
System.out.print("Answer (Only one try): ");
int answer = sc.nextInt();
if (answer == finalAnswer){
guess = true;
}
}
}
}
Cheers for any help.
In order to implement Runnable you need to override the run() method (unless your class is abstract, which opens another discussion). What you have in your game class is run(int time), which won't count.
From the Runnable API:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.
Bold added by me.