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.
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 1 year ago.
Improve this question
I have a Time class which has a comparison method called lessThan
public boolean lessThan(Time t1, Time t2) {
if (t1.getHours() > t2.getHours()) {
return false;
} else if (t1.getHours() == t2.getHours()) {
if (t1.getMinutes() >= t2.getMinutes()) {
return true;
} else
return true;
} else
return true;
}
I want to use this method inside my main class to compare to Time objects passed to sort my Time objects.
public static void sortAppointments(ArrayList < Time > appointments) {
Time val;
for (int i = 0; i < appointments.size(); i++) {
if (!lessThan(appointments.get(i), appointments.get(i + 1))) {
val = appointments.get(i + 1);
appointments.set(i + 1, appointments.get(i));
appointments.set(i, val);
}
}
}
But I get a cannot find symbol error when I compile. What am I doing wrong? How can I use my own method inside main class?
You write,
I have a Time class which has a comparison method called lessThan
and
I want to use this method inside my main class
, where apparently you attempt to realize the latter with
if( !lessThan( appointments.get( i ), appointments.get( i + 1 ) ) ) {
But that invocation of lessThan(), appearing as it does in a static method of the main class, will resolve method name lessThan against the main class. The method you want is not there, but rather in the Time class.
Moreover, you have implemented Time.lessThan(Time, Time) as an instance method, so it needs to be invoked on an instance of Time, yet it does not appear to make any use of that instance. It would make more sense as an instance method of class Time if it accepted only one argument, and evaluated whether the instance it is invoked on is less than the argument. As it presently stands, the method would be more useful if it were static.
The smallest set of changes that would resolve this issue would be to
Make the method static:
// In class Time
public static boolean lessThan( Time t1, Time t2 ) { // ...
AND
invoke it as such in your main class:
if( !Time.lessThan( appointments.get( i ), appointments.get( i + 1 ) ) ) {
Either make your method a static helper function and call it in a static fashion or change the signature of your method to utilise the instance of Time that the method exists in using this i.e.
public boolean lessThan( Time other ) {
if (this.getHours() > other.getHours()) {
return false;
}
}
then utilise the instance method in your test class
boolean less = appointments.get(i).lessThan(appointments.get( i + 1 ));
Also for sorting a list, an easier way is to make your Time implement Comparable<Time> and then use Collections.sort(list)
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 3 years ago.
Improve this question
I'm trying to write a matrix calculator for decomposition. However, there are some cases in the matrix calculator where I don't want the system to return anything, but just print out an error message.
I have tried to do this by replacing the return call with a throw new Exception method, but it clearly doesn't seem to be working because: 1. there needs to be some sort of catch/throws implemented and 2. there is still a need for a return statement.
public double[][] multiply(Matrix other) {
if(getCols() == other.getRows()) {
double[][] mult = new double[getRows()][other.getCols()];
for(int r = 0; r < mult.length; r++) {
for(int c = 0; c < mult[0].length; c++) {
mult[r][c] = mult(m1[r],findCol(other,c));
}
}
return mult;
}
else {
throw new MatrixException("Multiply");
}
}
So as can be seen by the else statement, in place of a return statement, it is replaced with throw new MatrixException("Multiply"). This simply returns a String statement, but the code will not compile. Is there any way to use a try-catch method to throw the Exception without needing to implement a return? Also, yes this is the first time I'm asking a question, so I'm still not fully familiar with the question formatting techniques.
You could inform the caller of multiply that an exception can be thrown by changing your method like this:
public double[][] multiply(Matrix other)throws MatrixException{}
So the method now would be:
public double[][] multiply(Matrix other) throws MatrixException { // tells the method throws an exception
if(getCols() == other.getRows()) {
// ...
return <your_valid_return_here>
}
throw new MatrixException("Multiply"); // inform the caller there is an exception if the previous condition is not met
}
Also, bear in mind what type of exception is MatrixException (checked or unchecked) in order to follow this approach. If checked, the caller will be forced to handle it in the calling code (or report its code can throw the exception), not being like this if it is unchecked.
Additional reading:
When to choose checked and unchecked exceptions
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 9 years ago.
Improve this question
I have this class:
public class Attributes {
List text = new ArrayList();
List angle = new ArrayList();
public Attributes() {
}
public int getHowManyNodes() {
int howMany = 0;
howMany += text.isEmpty() ? 0 : text.size();
howMany += angle.isEmpty() ? 0 : angle.size();
return howMany;
}
}
And when I do:
Attributes attributes = new Attributes();
System.out.print(attributes.getHowManyNodes());
It gives Exception in thread "main" java.lang.NullPointerException
Weirdly tho, it only gives an error on "angle.isEmpty()" not on "text.isEmpty()"
Why does it say it is null when I initialize it with:
List angle = new ArrayList();
Edit1:
Full error:
Exception in thread "main" java.lang.NullPointerException
at projectmerger1.Attributes.getHowManyNodes(Attributes.java:55)
at projectmerger1.Project.listGameVariables(Project.java:235)
at projectmerger1.ProjectMerger1.main(ProjectMerger1.java:289)
Java Result: 1
Minor edit:
Line 55 in Attributes Class is
howMany += angle.isEmpty() ? 0 : angle.size();
Edit2:
public class Project {
Game game;
public void listGameVariables() {
System.out.print(game.attributes.getHowManyNodes());
}
}
public class Game {
Attributes attributes = new Attributes();
}
This is my whole setup.
Based on your comments (and your code) one (or both) of your List(s) must be null. I would add a null check like this
howMany += text == null ? 0 : text.size();
howMany += angle == null ? 0 : angle.size();
It's possible you have another method that is "nulling" those fields.
I've compiled and run this code, it prints out 0 with no NullPointerException. There is no way to get this error with the code you provided.
public class Attributes {
List text = new ArrayList();
List angle = new ArrayList();
public Attributes() {
}
public int getHowManyNodes() {
int howMany = 0;
howMany += text.isEmpty() ? 0 : text.size();
howMany += angle.isEmpty() ? 0 : angle.size();
return howMany;
}
public static void main(String[] args) {
Attributes attributes = new Attributes();
System.out.print(attributes.getHowManyNodes());
}
}
The only possible way that this could be happening is if:
angle is being accessed somewhere else and set to null before you call getHowManyNodes().
angle is being "shadowed" by another variable of the same name that you are not showing in your code example.
Ways to debug this:
Make your variables private and final, and see what code they break so you can see if they're being set to null elsewhere.
Put System.out.println(angle) in a block of code under your instantiation of angle, and also in your constructor.
Ways to avoid this bug in the future:
Encapsulate your variables.
Make your methods null-safe.
Set a BreakPoint in the first source code line of your getHowManyNodes() method, start your program in debug mode and try to figure out where the error comes from by using the short cut keys (Eclipse) F5 -> StepInto and F6 -> StepOver. Your source provided looks fine and shouldn't cause any problems. By debugging your application via Eclipse or any other IDE, you should easily find such errors.
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.
I have the following code:
public void actionPerformed(ActionEvent e) {
String userInput = commandInput.getText();
if (currentLevel == 0) {
if (userInput.equals(answers.getIntroAnswers().get(0)) || userInput.equals(answers.getIntroAnswers().get(1))) {
messageDisplay.append("\n \n" + userInput + "\n");
commandInput.setText("");
messageDisplay.append("\n" + messages.getNextMessage());
currentLevel++;
getCurrentLevel();
} else {
messageDisplay.append(notValid());
}
} else if (currentLevel == 1) {
// do the same as above but with the next set of answers
}
}
What I'd like to do is somehow separate this action into it's own class and call the method /constructor within that class to do this checking else I will be stuck using nested if's and it will become very messy and hard to understand. Would I be right in thinking a method to take parameters of currentLevel and userInput in order to test the userInput against the corresponding answers based on the currentLevel? Below is a link to the rest of the classes involved:
https://github.com/addrum/TextGame.git
Would I be right in thinking a method to take parameters of currentLevel and userInput in order to test the userInput against the corresponding answers based on the currentLevel?
No. In fact, you probably want to avoid passing the current level as an explicit parameter. If you've got the level as a parameter, you will probably end up just pushing the "multiple nested ifs" into another class.
I think you need to write it like this:
InputChecker[] levelChecker = ... create an array of checker instances
....
levelChecker[currentLevel].check(userInput);
Then you need to create a class (possibly anonymous) to implement the checking for each level. Note that if you needed to you could supply the level number to a checker class via a constructor parameter and have it save it in a private instance variable.
You could expand/generalize the InputChecker interface to include other level-specific behaviour. Or indeed make this part of a Level interface.
"Is this taking the currentLevel and comparing the userInput to the current level?"
No. In my example code above it is calling a method on the InputChecker instance to do the checking. Since there are different InputChecker instances for each level, they can check different answers ... or whatever.
But if the only difference between the "input check" behaviours for each level is that they check against a different set of answers then:
levelAnswers = answers.getAnswersForLevel(currentLevel);
for (String answer : levelAnswers) {
if (userInput.equals(answer)) {
// blah blah blah
}
}
Why not create the method in the same class rather than having a different class to do that, considering other variables that method uses such as,
messageDisplay.append("\n \n" + userInput + "\n");
commandInput.setText("");
messageDisplay.append("\n" + messages.getNextMessage());
currentLevel++;
So I'd suggest creating the method in same then call it from actionPerformed
public void checks()
{
String userInput = commandInput.getText();
if (currentLevel == 0) {
if (userInput.equals(answers.getIntroAnswers().get(0)) || userInput.equals(answers.getIntroAnswers().get(1))) {
messageDisplay.append("\n \n" + userInput + "\n");
commandInput.setText("");
messageDisplay.append("\n" + messages.getNextMessage());
currentLevel++;
getCurrentLevel();
} else {
messageDisplay.append(notValid());
}
} else if (currentLevel == 1) {
// do the same as above but with the next set of answers
}
}
Then call it from actionPerformed
public void actionPerformed(ActionEvent e)
{
check():
}
So now you if's are handle in a seperate method.
To my eyes, since you are talking about levels so much, you probably should have a class that represents a level. Actually, since you obviously have more than one level, which acts slightly differently, you have two approaches.
Have a Level interface, and then make a class per level.
or
Have a Level class, with a constructor that hides the level number within the class.
After that, you can switch polymorphicly instead of nested if statements (or if's cousin, the switch statement).
Level level = currentLevel;
while (level != null) {
level.doStuff;
level = level.getNextLevel();
}