Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
/**File class */
public class File {
// The File name.
private String name;
// The date file created.
private String date ;
// The type of file - audio, image, video, doc.
private String type;
// The size of the file - 2MB, 2KB etc.
private String size;
/**
* Create a file
*/
public File(String Filename)
{
name = Filename;
date = ("MM/dd/yyyy");
type = ();
size = ();
}
/**
* Return the name of a File.
*/
public String getName()
{
return name;
}
/**
* Update system number when called to the output terminal
*/
public void Systemnumber ()
name.increment();
if(name.Filename() == 0) { // it jus rolled over !
i.increment();
}
updateDisplay();
}
/**
* Print File description to the output terminal
*/
public void updateDisplay ()
public String s = String.format ("%02d", i); // gives you "001"
for (int i = 001; i < 1000; i++) {String sequence = String.format("%02d", i); }
{
return (i + "", '$this.Name + " " + $this.date + " " + $this.type + " " +$this.size; }
/**
* This method is called everytime Increment the return value one, rolling over to zeor if the limit is reached
*/
public void updateDisplay ()
{ displayString = name.
(
value = (value +1) % limit;
)
}
Seeing as you're using BlueJ, I'll assume it's homework, so I won't answer the question as such, just give some pointers.
You need to store a counter in the File object, but, that counter needs to be shared between instances of the object. This counter can be used at construction time to get the number for each individual instance of File, which can then be stored for the instance in question.
What you are missing in your new update is the sequence number. You should store this in a static variable (so that it is shared between all instances of File) and then assign its current value to a member variable in the constructor, before incrementing the static variable for the next instantiation.
You will need to add a private static integer, which you can call it whatever you want. I will call it numberOfFileInstances. In your constructor you will need to increment numberOfFileInstances by one.
Here is my example:
public class File {
private static int numberOfFileInstances = 0;
public File() {
File.numberOfFileInstances++;
}
}
Since your using BlueJ you'll be easily able to see that each time you create a new file object the numberOfFileInstance will be incremented by one. In BlueJ initialize 2 (or any number you would like grater than 1) File objects and double click on the object to bring up the inspector. Click on the "Show static fields" button and you should see private int numberOfFileInstance and the count of however many object you initialized.
If you need a sequence counter, you might want to consider using a static integer which you increment for every file added.
I'm not sure I understand what you want but it sounds simple:
public String toString() {
return this.Name + " " + this.date + " " + this.type + " " +this.size;
}
Related
This question already has an answer here:
How to use single Servlet with different URL pattern?
(1 answer)
Closed 3 years ago.
I am currently using /Main as the default url-pattern.
It is possible to replace this with /Main2 or another word, but I would like to add one directory such as /Project/Main.
/Project path is not really present, but just want /Main and /Project/Main to work the same way.
In other words, it is hoped that the described routes will invoke one servlet. Is there a way?
ex) 172.0.0.1/Project/Main = 172.0.0.1/Main
=> result : Main_servlet
To my knowledge, you can only pass to the main knowledge in String format. This is because things passed to the main method come from System.in, either through random user input or things like piping, whereby you pass Strings from one Java program to another.
That being said, what you could do is that you create a method in your object class to parse a String form of that object to recreate the original version of that object.
For example:
public class myRectangle
{
private int length;
private int width;
public myRectangle(int inLength, int inWidth)
{
this.length = inLength;
this.width = inWidth;
}
// the rest of your class
public String toString()
{
return "[" + length + ", " + width + "]";
}
public static Rectangle parseString(String input)
{
int firstBracketIndex;
int commaIndex;
int lastBracketIndex;
firstBracketIndex = 0;
commaIndex = input.indexOf(",");
lastBracketIndex = input.length() - 1;
String aWidth = input.substring(firstBracketIndex, (commaIndex - 1));
String aLength = input.substring((commaIndex + 2), lastBracketIndex);
return new Rectangle(Integer.parseInt(aWidth), Integer.parseInt(aLength));
}
}
Something like this could solve your problem. (There may be some off by one errors in my code and I wrote it out really long so it would be clear, but you get the idea!)
The point is, that you create a parsing method that is the inverse of your toString method, so that you can take copies of your class off the command line.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
(At time of posting, I do not have access to code, will add later)
I have an array of Employee objects, which hold a name, availability, and preferred hours. And I sort the objects by Alphabetical order, according to the employees name.
When the program starts, it checks the files, and if they are empty, it asks you how many employees, and then you proceed to fill in the data. And it sorts properly A-Z.
This issue comes that when I try to add a new employee, after resizing the array, it adds it to the end, even though the sort completes.
So it sorts the first time, but not again after re running the program. I will post the code when I get home, but wanted to see if anyone had any answers in the mean time. Thank you
static void employeeSort(Employee[] emply, int size)
{
int i;
Employee temp;
boolean flag = true;
while(flag)
{
flag = false;
for(i = 0; i < size; i++)
{
if (emply[i].getName().compareTo(emply[i+1].getName())>0)
{
System.out.println(emply[i].getName());
temp = emply[i];
emply[i] = emply[i+1];
emply[i+1] = temp;
flag = true;
}
}
}
}
On the first run through, it sorts everything correctly, but once the array is read from a file, the program terminates in the sort. I tried implementing the priority queue, but i needed to make the Class comparable, and its already implemented Serializable.
public class Employee implements Serializable
{
int prefHours;
String name;
String avail;
Employee( String nam, int hours, String aval )
{
name = nam;
prefHours = hours;
avail = aval;
}
void prnEmpl()
{
System.out.print("Name: " + name);
System.out.println();
System.out.print("Prefered hours: " + prefHours);
System.out.println();
System.out.print("Availability: " + avail);
System.out.println();
}
String getName()
{
return name;
}
String getAvail()
{
return avail;
}
}
Without your code it is hard to figure out what's the problem. As far as I understand I think you should use java.util.PriorityQueue instead of Array.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Good evening all!
The assignments are getting confusing! Again, not asking for a straight up answer but rather a pointer in the right direction so any help is appreciated.
Edit 2: Here is the exercise in question if it helps clear anything up:
I'm wondering how I can set the dailyFee variable in the CarRental.java file using the UseCarRental.java file. The if statements from CarRental.java don't seem to be working properly (inputting size doesn't set the dailyFee variable). Additionally, if I enter "l" for the size, it's not prompting to LuxuryCarRental.java. Here is the code:
CarRental.java
import javax.swing.JOptionPane;
public class CarRental
{
private String name;
private String zipCode;
private String size;
private double dailyFee;
private int rentalDays;
private double totalFee;
public CarRental(String name, String zipCode, String size, double dailyFee, int rentalDays, double totalFee)
{
this.name = name;
this.zipCode = zipCode;
this.size = size;
if (size == "e")
{
this.dailyFee = 29.99;
}
else if (size == "m")
{
this.dailyFee = 38.99;
}
else if (size == "f")
{
this.dailyFee = 43.50;
}
this.dailyFee = dailyFee;
this.rentalDays = rentalDays;
totalFee = dailyFee * rentalDays;
}
public CarRental(){}
public void display()
{
JOptionPane.showMessageDialog(null, "Luxury car for " + name + " from zip code " + zipCode + "\n"
+ "Type = " + size + "\n"
+ "Daily Fee = " + dailyFee + "\n"
+ "Days = " + rentalDays + "\n"
+ "Your rental is $" + totalFee);
}
//includes getters and setters but I didn't include them in this post
LuxuryCarRental.java
import javax.swing.JOptionPane;
public class LuxuryCarRental extends CarRental
{
public LuxuryCarRental(String name, String zipCode, String size, double dailyFee, int rentalDays, double totalFee, String includeChauffeur)
{
super(name, zipCode, size, dailyFee, rentalDays, totalFee);
if (size == "l")
{
dailyFee = 79.99;
includeChauffeur = JOptionPane.showInputDialog(null, "Include chauffeur? Y/N");
if (includeChauffeur == "Y")
{
totalFee = totalFee + 200;
}
}
}
}
UseCarRental.java (incomplete)
import javax.swing.JOptionPane;
public class UseCarRental
{
public static void main(String[] args)
{
CarRental userInfo = new CarRental();
userInfo.setName(JOptionPane.showInputDialog("Enter name"));
userInfo.setZipCode(JOptionPane.showInputDialog("Enter zip code"));
userInfo.setSize(JOptionPane.showInputDialog("Enter type of car" + "\n" + "e - economy" + "\n" + "m - midsize" + "\n" + "f - full" + "\n" + "l - luxury"));
userInfo.setRentalDays(Integer.parseInt(JOptionPane.showInputDialog("Enter days to rent")));
System.out.println(userInfo.getDailyFee());
userInfo.display();
}
}
As you can see, I'm completely stumped as to how I can use setDailyFee in UseCarRental.java to set the dailyFee variable, which is need to make the totalFee calculation.
Edit: Being asked to explain why this is not a duplicate question. I fixed the string comparison issue (not updated here yet) but the core issue is still setters and inheritance.
Edit 3: Well I guess the question of the century (for clarity's sake) is: how do I set dailyFee value? I thought that it would be set by the if statement in CarRental.java once size is entered?
You have a few problems here:
You're using == to compare strings.
In your CarRental constructor, you're setting this.dailyFee based on the size and then overwriting it with the parameter's value. You should either eliminate the parameter or not have that logic in the constructor.
The dailyFee field is private to CarRental, meaning it's not available for direct access in LuxuryCarRental. LuxuryCarRental should use this.setDailyFee() instead.
It's Bad Code to put interactions such as a dialog box in a constructor. It'll work for this assignment, but don't use it in Real Code. Separate the interface and the data classes.
You seem to be misunderstanding how inheritance works. You create a CarRental object in your main, but the code for handling l only exists in LuxuryCarRental. You would need to either unconditionally create a LuxuryCarRental (which you could still assign to the CarRental variable) or input the rental type and create a CarRental or LuxuryCarRental based on what it is. Note that while you have a default (no-argument) constructor for CarRental, you do not have one for LuxuryCarRental.
My overall recommendation, besides fixing the string comparison: Move all of the questions into your main method, and assign their values to local variables. Use those values in a call to new LuxuryCarRental(name, zipCode, size, rentalDays, includeChauffeur) (note that dailyFee is calculated based on the size, and the totalFee is calculated based on the daily fee, days, and chauffeur). Instead of having totalFee as a variable on your CarRental, make getTotalFee() a method that performs your calculations when called, since the fee will change whenever you change any of the other parameters.
(And learn about enums when you can; the size shouldn't be a string in the first place.)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a command line input as 0 1 2 and the main code can be seen below.
public class AppleStoreRunner {
public static void main(String [] args) {
//maximum size of queue
int qCapacity = Integer.parseInt(args[0]);
//number of simulation hours
int simHours = Integer.parseInt(args[1]);
//average number of customers per hour
int custPerHour = Integer.parseInt(args[2]);
AppleStore myStore = new AppleStore(qCapacity, simHours, custPerHour);
//Run simulation
myStore.simulation();
myStore.displayAcceptedCustomers();
myStore.displayServedCustomers();
myStore.displayWaitingCustomers();
myStore.displayTurnAwayCustomers();
}
}
How can I call the inputed command line arguments in the following class so that I may use the inputs in a seperate extended class? The code below is the class I am trying to create variables for the 3 inputed numbers.
public class AppleStore {
int qCapacity;
int simHours;
int custPerHour;
/** Constructor
* #param qCapacity The initial capacity of the queue to be used.
* #param simHours The number of hours that the simulation should run.
* #param custPerHour expected number of customers to arrive per hour.
*/
public AppleStore(int qCapacity, int simHours, int custPerHour)
{
qCapacity = AppleStoreRunner.main(args);
}
/**
* This methods performs a simulation of a store operation using a queue and prints the statistics.
* For every minute, the simulator 1) checks if there are new customers arriving; 2) adds the new customer into the waiting line or else records the customer who chooses to leave; 3) continues to help the current customer if the current customer is not finished yet, or else get the next person in the waiting line. The simulator starts at minute 0, and repeats every minute until it finishes the requested simulation time.
*/
public void simulation( )
{
System.out.println( "Average Waiting Time" + );
System.out.println( "Average Line Length" + );
/**
* print the info of all accepted customers
*/
}
public void displayAcceptedCustomers()
{
System.out.println("Customers accepted" + );
/**
* print the info of all served customers
*/
}
public void displayServedCustomers()
/**
* print the info of all waiting customers
*/
public void displayWaitingCustomers()
/**
* print the info of all turned away customers
*/
public void displayTurnAwayCustomers()
}
Because you did AppleStore myStore = new AppleStore(qCapacity, simHours, custPerHour); in your main method, all you need to do is to define a proper constructor.
public AppleStore(int qCapacity, int simHours, int custPerHour)
{
this.qCapacity = qCapacity;
this.simHours = simHours;
this.custPerHour = custPerHour;
}
As you declared the three instance variables as package-private, the subclasses will automatically see the existence of the three variables.
However, if you make the subclasses somehow immune to the changes to the superclass (I mean, the AppleStore), I recommend to add some getters for the three variables than can be called from the subclasses such as:
int getQueueCapacity() {
return this.qCapacity;
}
and to change the access levels of the three variables into private.
I'm trying some Java recently and look for some review of my style. If You like to look at this exercise placed in the image, and tell me if my style is good enought? Or maybe it is not good enought, so You can tell me on what aspect I should work more, so You can help me to improve it?
exercise for my question
/*
* File: MathQuiz.java
*
* This program produces Math Quiz.
*/
import acm.program.*;
import acm.util.*;
public class MathQuiz extends ConsoleProgram {
/* Class constants for Quiz settings. */
private static final int CHANCES = 3;
private static final int QUESTIONS = 5;
private static final int MIN = 0;
private static final int MAX = 20;
/* Start program. Number of questions to ask is assigned here. */
public void run() {
println("Welcome to Math Quiz");
while(answered != QUESTIONS) {
produceNumbers();
askForAnswer();
}
println("End of program.");
}
/* Ask for answer, and check them. Number of chances includes
* first one, where user is asked for reply. */
private void askForAnswer() {
int answer = -1;
if(type)
answer = readInt("What is " + x + "+" + y + "?");
else
answer = readInt("What is " + x + "-" + y + "?");
for(int i = 1; i < CHANCES+1; i++) {
if(answer != solution) {
if(i == CHANCES) {
println("No. The answer is " + solution + ".");
break;
}
answer = readInt("That's incorrect - try a different answer: ");
} else {
println("That's the answer!");
break;
}
}
answered++;
}
/* Produces type and two numbers until they qualify. */
private void produceNumbers() {
produceType();
produceFirst();
produceSecond();
if(type)
while(x+y >= MAX) {
produceFirst();
produceSecond();
}
else
while(x-y <= MIN) {
produceFirst();
produceSecond();
}
calculateSolution();
}
/* Calculates equation solution. */
private void calculateSolution() {
if(type) solution = x + y;
else solution = x - y;
}
/* Type of the equation. True is from plus, false is for minus. */
private void produceType() {
type = rgen.nextBoolean();
}
/* Produces first number. */
private void produceFirst() {
x = rgen.nextInt(0, 20);
}
/* Produces second number. */
private void produceSecond() {
y = rgen.nextInt(0, 20);
}
/* Class variables for numbers and type of the equation. */
private static boolean type;
private static int x;
private static int y;
/* Class variables for equation solution. */
private static int solution;
/* Class variable counting number of answered equations,
* so if it reaches number of provided questions, it ends */
private static int answered = 0;
/* Random generator constructor. */
RandomGenerator rgen = new RandomGenerator();
}
One thing I noticed was that all of your methods take no parameters and return void.
I think it would be clearer if you use method parameters and return values to show the flow of data through your program instead of using the object's state to store everything.
There are a few things you should do differently, and a couple you could do differently.
The things you should do differently:
Keep all fields together.
static fields should always be in THIS_FORM
you've used the static modifier for what clearly look like instance fields. (type,x,y,solution, answered). This means you can only ever run one MathsQuiz at a time per JVM. Not a big deal in this case, but will cause problems for more complex programs.
produceFirst and produceSecond use hardcoded parameters to nextInt rather than using MAX and MIN as provided by the class
There is no apparent need for answered to be a field. It could easily be a local variable in run.
Things you should do differently:
There is a small possibility (however tiny), that produceNumbers might not end. Instead of producing two random numbers and hoping they work. Produce one random number and then constrain the second so that a solution will always be formed. eg. say we are doing and addition and x is 6 and max is 20. We know that y cannot be larger than 14. So instead of trying nextInt(0,20), you could do nextInt(0,14) and be assured that you would get a feasible question.
For loop isn't really the right construct for askForAnswer as the desired behaviour is to ask for an answer CHANCES number of times or until a correct answer is received, whichever comes first. A for loop is usually used when you wish to do something a set number of times. Indeed the while loop in run is a good candidate for a for loop. A sample while loop might look like:
int i = 1;
boolean correct = (solution == readInt("What is " + x + "+" + y + "?"));
while (i < CHANCES && !correct) {
correct = (solution == readInt("Wrong, try again."));
i++;
}
if (correct) {
println("Well done!");
} else {
println("Nope, the answer is: "+solution);
}
Looks like a very clean program style. I would move all variables to the top instead of having some at the bottom, but other than that it is very readable.
Here is something I'd improve: the boolean type that is used to indicate whether we have an addition or subtraction:
private void produceType() {
type = rgen.nextBoolean();
}
produceType tells, that something is generated and I'd expect something to be returned. And I'd define enums to represent the type of the quiz. Here's my suggestion:
private QuizType produceType() {
boolean type = rgen.nextBoolean();
if (type == true)
return QuizType.PLUS;
else
return QuizType.MINUS;
}
The enum is defined like this:
public enum QuizType { PLUS, MINUS }
Almost good I have only a few improvements:
variables moves to the top
Inside produceNumbers and your while you have small repeat. I recommend refactor this
Small advice: Code should be like books - easy readable - in your run() method firstly you call produceNumber and then askForAnswer. So it will be better if in your code you will have the same order in definitions, so implementation askForAnswer before produceNumber. But it isn't necessary
Pay attention to have small methods. A method shouldn't have much to do - I think that askForAnswer you could split to two methods