Java counting method? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I need to write some code that will count the amount of times someone has borrowed a CD. I tried doing some but just failed and don't have a clue any more.
Like I said, stuck again on something that is probably simple to do:
public void borrower(String nameOfBorrower)
/**
*
*/
{
borrower = nameOfBorrower;
borrowed = true;
inStock = false;
}
public void returned()
/**
*
*/
{
borrower = "";
borrowed = false;
inStock = true;
}
public boolean isBorrowed()
/**
*
*/
{
return borrowed;
}
public void reportInStock()
/**
*
*/
{
if(inStock == false)
{
System.out.println("This CD has been borrowed;" + personName);
}
else
{
System.out.println("This CD is available");
}
}

do you want to get how many times a CD was borrowed? or who borrowed how many times?
to check how many times the CD was borrowed
in your
public void borrower(String nameOfBorrower)
{
borrower = nameOfBorrower;
borrowed = true;
inStock = false;
times++;
}
public int GetTimes()
{
return times;
}

That depend and the case what you want to analysis, the exact CD o just title of it.
For Title we have a many to many relation you should try to design a class that could represent that state.
new BorrowTransaction(Person).borrow(CD);
The borrow method should persist the data about who borrow what.
Then you your CD class you could have object called CDStats that contain information about borrows and etc.
For unique CD case is quite simple. You should add a field to the class that will store the value and increment it each time by one when a borrower is assigned to it.

Related

Is something wrong with the method? [closed]

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 last year.
Improve this question
So that's my method and i got Main class from my teacher that uses this method and it should return only 1 Suspect but it returns the same one for 8 times or something i am really close on my deadline please help
public ArrayList<Suspect> getCommonPartners(Suspect aSuspect) {
ArrayList<Suspect> commonpartners = new ArrayList<>() ;
for(Suspect s: partners) {
for(Suspect sus: aSuspect.getPartners()) {
if(s.getCodename().equals(sus.getCodename())) {
commonpartners.add(s);
}
}
}
return (commonpartners);
}
Where is 'partners' coming from? You're running a for loop on it. Did you mean aSuspect?
If you are getting multiple of the same value. Do a check on the arraylist before adding it.
public ArrayList<Suspect> getCommonPartners(Suspect aSuspect) {
ArrayList<Suspect> commonpartners = new ArrayList<>() ;
for(Suspect s: partners) {
for(Suspect sus: aSuspect.getPartners()) {
if(s.getCodename().equals(sus.getCodename())) {
if(!commonpartners.contains(s)) {
commonpartners.add(s);
}
}
}
}
return (commonpartners);
}

Stack of Plates: Cracking the coding interview , Personal Solution [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Stack of Plates: Imagine a (literal) stack of plates. If the stack gets too high, it might topple.
Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity.
SetOfStacks. push () and SetOfStacks. pop() should behave identically to a single stack (that is, pop ( ) should return the same values as it would if there were just a single stack).
I've implemented a solution with a HashMap.
I'd like to know if this is a good implementation (in space and complexity) and if it can be improve. Moreover, I've used correctly this.index ?
public class SetOfStacks {
private final int LIMIT= 5;
private HashMap<Integer,Stack<Integer>> setOfStack;
private int index;
public SetOfStacks(){
this.setOfStack= new HashMap<>();
this.index = 0;
}
public void addStack(){
this.index++;
if(!setOfStack.containsKey(index))
this.setOfStack.put(index, new Stack<Integer>());
}
public void pushElement(int value){
if (isFull())
addStack();
setOfStack.get(index).push(value);
}
public boolean isFull(){
return setOfStack.get(index).size() == LIMIT;
}
public void popElement(){
if(setOfStack.get(index).isEmpty())
index--;
setOfStack.get(index).pop();
}
public int peekElement(){
return setOfStack.get(index).peek();
}
}
FOLLOW UP
Implement a function popAt (int index) which performs a pop operation on a specific substack.
I didn't write the solution for it, but i think that his implementation should be easy. I only need to pass the parameter and just manage the push/pop, in case i need to refull that stack or not.
What do you think about maintenance of my code if you need to implement the follow up?
It's good but you have some mistake,
you never initialize the first stack,
also what happens if I initialize the SetOfStacks and call the pop?(assuming you fixed the first mistake)

I got an unexpected token in while loops [closed]

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 2 years ago.
Improve this question
For some reason the program claims that while(n == true) is an unexpected token
boolean n = true;
while(n == true){
if(autopark.searchItems(searchInput) == 1){
System.out.println("There is a matching item available in our inventory\n" + "Enter a string to search: ");
}
if(autopark.searchItems(searchInput) == 2){
System.out.println("No such item is available in our inventory.\n" + "Enter a string to search: ");
}
if(autopark.searchItems(searchInput) == 0){
n = false;
}
}
You've put your code directly into a class. That's not where code goes.
At the 'top level' (at the start of your source file, for example), the only thing that you can write (other than comments, which are always okay) are import statements, package statements, and type declarations. Such as class X {} or #interface Y{} or even enum Foo{}.
Within a type declaration, various things are legal and it depends on the type declaration we're in to know. For basic classes, the only legal constructs within a class are type declarations (you can put types in types), methods, constructors, initializers and field declarations.
You cannot put code directly inside your class.
boolean n = true; is valid, in that it is a field declaration. But while is none of those things.
Try this:
public class MyFirstJava {
public static void main(String[] args) throws Exception {
new MyFirstJava().go();
}
public void go() throws Exception {
// start writing code here.
}
}

Conditional Logic to Determine Correct Status String [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
There is a status variable in a Java application that can be set to one of many statutes, depending on many conditions. The status field is a String. When a condition is met, the status should be returned immediately, as follows:
e.g
String status = "";
if (condition1) {
return "STATUS_1";
} else if (condition2) {
return "STATUS_2";
} else if (condition3) {
return "STATUS_3";
} else if (condition4) {
return "STATUS_4";
}
...
else if (condition10) {
return "STATUS_10";
}
I've considered which pattern would be best to make this code more SOLID... e.g. if a new condition is required then this class would need to edited to add the new condition, which would break the open / closed SOLID principle
I've looked at the Strategy Pattern, in particular "Replace Conditional Logic with Strategy", however that seems more appropriate when you want to decide on just one calculation / operation to use... My scenario does not seem to fit the Strategy Pattern as my logic determines the status, rather than determining which individual operation to execute - I need to run all the conditions until one is true
I wondered if the following pattern could work...
Have an interface as follows
public interace StatusCondition {
boolean condition(Context context);
String getStatus();
}
With an implementation as follows:
public class StatusAStatusCondition implements StatusCondition {
boolean condition(Context context){
return context.getValue1() == 0 && context.getValue2().equals("A");
}
String getStatus(){
return "STATUS_A";
}
}
This would allow a list of StatusCondition classes to be executed in order and return the status of the first StatusCondition where the condition() method returns true. e.g:
public String getStatus(List<StatusCondition> statusConditions) {
for (StatusCondition statusCondition : statusConditions) {
if (statusCondition.condition()) {
return statusCondition.getStatus();
}
}
return "";
}
usage:
List<StatusCondition> statusConditions = new ArrayList<>();
statusConditions.add(statusAStatusCondition);
statusConditions.add(statusBStatusCondition);
statusConditions.add(statusCStatusCondition);
statusConditions.add(statusDStatusCondition);
statusConditions.add(statusEStatusCondition);
statusConditions.add(statusFStatusCondition);
...
String status = getStatus(statusConditions);
To me this solves the open closed principle issue and also ensures the implementations are single responsibility... My question is, how could this pattern i've suggested be improved, or is there a pattern better suited to my scenario?
First, you are absolutely correct that the original if/else ladder violates the Open/Closed Principle. Second, converting the status value to an interface is exactly the right step to take, to move away from stringly-typed programming. Third, your solution is essentially the Chain of Responsibility Pattern. It's an excellent solution to this problem. In summary, your instincts are spot on.

Pass boolean value to another class [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
In my main class I want to check if there was a change by using a boolean variable:
public class Main {
private boolean change = false;
public boolean getChange() {
return change;
}
public void setChange(boolean change) {
this.change = change;
}
private void method1() {
// some command
setChange(true);
method1();
}
If I want to get this boolean value in my second class, I always get returned "false", no matter if my method1 ran or not.
public class BoolTest {
Main m = new Main();
System.out.println(m.getChange()); // returns "false"
}
You must have two instances of Main. Use the same one. Example:
Main m = new Main();
System.out.println(m.getChange());
m.setChange(true);
System.out.println(m.getChange());
You probably want to share the same instance over multiple classes. Pass the instance to the other classes and use them as expected.

Categories

Resources