Do not print "not found" when something is found - java

I am trying to do this project and for some reason I am having an issue that for the life of me I can not solve.
public static void printlist(String n){
for(int i=0; i< roomlist.size(); i++){
if(roomlist.get(i).name.equals(n)){
System.out.println("Room Name: " + roomlist.get(i).name + " state: " + roomlist.get(i).state);
System.out.println("Description: " + roomlist.get(i).desc);
System.out.println("Creatures in Room: " + roomlist.get(i).Fred());
if(roomlist.get(i).north != null){
System.out.println("North Neighbor: " + roomlist.get(i).north.name);
}
if (roomlist.get(i).south !=null){
System.out.println("South Neighbor: " + roomlist.get(i).south.name);
}
if (roomlist.get(i).east !=null){
System.out.println("East Neighbor: " + roomlist.get(i).east.name);
}
if (roomlist.get(i).west !=null){
System.out.println("West Neighbor: " + roomlist.get(i).west.name);
}
}
}
System.out.println("Room " + n + " does not exist!");
}
Right now even if it finds the Room object in the ArrayList it still prints "Room " + n + " does not exist!" I need it to only print that if the room is not found in the ArrayList

The reason it happens is because the Not found message is the last statement of your method. You should instead return from the method as soon as you found your element and you printed your wanted messages.
For example assuming each room has a unique name:
...
if (roomlist.get(i).name.equals(n)) {
...
if (roomlist.get(i).west != null) {
System.out.println("West Neighbor: " + roomlist.get(i).west.name);
}
return;
}
...

Basically, System.out.println("Room " + n + " does not exist!"); will always be executed, because there is nothing stopping it
Assuming that there can be more then one neighboring room, it might be easier to use a simple flag to indicate if any rooms where found
public static void printlist(String n){
boolean foundRoom = false;
for(int i=0; i< roomlist.size(); i++){
if(roomlist.get(i).name.equals(n)){
foundRoom = true;
System.out.println("Room Name: " + roomlist.get(i).name + " state: " + roomlist.get(i).state);
System.out.println("Description: " + roomlist.get(i).desc);
System.out.println("Creatures in Room: " + roomlist.get(i).Fred());
if(roomlist.get(i).north != null){
System.out.println("North Neighbor: " + roomlist.get(i).north.name);
}
if (roomlist.get(i).south !=null){
System.out.println("South Neighbor: " + roomlist.get(i).south.name);
}
if (roomlist.get(i).east !=null){
System.out.println("East Neighbor: " + roomlist.get(i).east.name);
}
if (roomlist.get(i).west !=null){
System.out.println("West Neighbor: " + roomlist.get(i).west.name);
}
}
}
if (!foundRoom) {
System.out.println("Room " + n + " does not exist!");
}
}
You could probably optimise it by using a List of some kind to store the neighboring rooms in and checking the size at the end, but the basic idea remains the same...

Related

How can I print something based on the result of a boolean method?

I have two methods
*`public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}`*
validateMarks(): Used to validate qualifying exam marks - qualifying marks is in the range of 65 to 100(both inclusive)
validateCourseId(): Used to validate the course entered, based on the courseId - given in the table above
calculateCourseFee(): Used to calculate the course fee after applying the discount.
So when is less than 65 print print "not elegible, you've failed" and when the course is not valid "course is not correct, please try again with the correct number of the course"
and this is my calculateCourseFee method
***if(this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("Wroog for course");
}
***
I make two different ifs for the two requirements, but everytime I run it, it prints the else statement to, even if marks is greather than 65... am I missing something?
Reviewing my code and tell me what am I missing or what am I doing wrong
The portion of the code you have shown here seems to be working as expected.
public class Driver {
public static void main(String args[]) {
Eligible e1 = new Eligible();
e1.calculateCourseFee();
}
}
class Eligible{
int qualifyingMarks = 66;
int courseId = 1002;
public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}
public void calculateCourseFee(){
if(this.validateMarks()) {
System.out.println("works for marks");
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
System.out.println("works for course");
}else {
System.out.println("Wroog for course");
}
}
}
output:
works for marks
works for course
Maybe the issues is with how you set the values for the qualifyingMarks and courseId variables?
I wish I could give you a like or thumbs up, I finally did it, thanks to all of your answers you gave me, and I just combined the two ifs into one. here's the code:
if(this.validateCourseId() && this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else if(!this.validateCourseId()) {
System.out.println("Wrong course");
}
else if(!this.validateMarks()) {
System.out.println("You've failed");
}
Thanks everyone!!
maybe qualifyingMarks is zero or another value, print qualifyingMarks in method "validateMarks",u will get the reason of your problem.

How do I fix an if statement that uses "parseInt()" so that the else portion is activated and my program doesn't fail?

I wrote a program that asks for user input (numbers), then tells the user which of the two numbers they put in are bigger after making sure both values are numbers. This is looped. The problem is, when the user enters something that isn't valid, the program shuts down instead of referring to my else statements. I think this is because text values in strings cannot be processed using parseInt() so instead of the program realizing that a text value isn't a valid number, it just fails. I am using BlueJ to make this program if that helps anyone solve the problem. I am also open to people telling me how to make my program more efficient/easier to code (I am a beginner).
import java.util.Scanner;
public class TemperatureDriver {
public static void main(String[] args) {
while (true) {
Scanner keyInput = new Scanner(System.in);
System.out.print("Enter a number"+ "\n");
String number_one = keyInput.next();
if (Integer.parseInt(number_one) <=0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if(Integer.parseInt(number_two) <=0 || Integer.parseInt(number_two) > 0){
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) < Integer.parseInt(number_two)){
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) == Integer.parseInt(number_two)){
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
}
}
}
Your code where you call parseInt should be embedded in a try block, which should be followed by a catch block to catch the NumberFormatException.
try {
if (Integer.parseInt(number_one) <= 0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if (Integer.parseInt(number_two) <= 0 || Integer.parseInt(number_two) > 0) {
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) < Integer.parseInt(number_two)) {
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) == Integer.parseInt(number_two)) {
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} catch (NumberFormatException e) {
System.out.println("Not a valid number");
}

Driver.java:55: error: 'else' without 'if'

So basically I'm just trying to get this bit of code to work. It used to run when I had the "else" below the two "if" statements. However, when I move it above it gives me the following error:
Driver.java:55: error: 'else' without 'if'
I'd really appreciate some help solving this issue so it'll run again.
{
synchronized(someObject)
{
someObject.wait();
System.out.println(ID + " has been notified.");
Customer customer = null;
if(Dispatcher.customerRequiresPickUp() && (customer = Dispatcher.queue.poll()) != null && (rideCount >= workFinished))
System.out.println("Customer has been picked up by driver #" + ID);
try
{
Thread.sleep(rn.nextInt(5000) + 1000);
System.out.println("Driver #" + ID + " has dropped off " + customer.getName() + " at " + customer.getEndLocation() + ".");
}
catch(InterruptedException e)
{
}
else
System.out.println("Driver #" + ID + " will continue to wait for a customer.");
if(rideCount >= workFinished)
onDuty(false);
}
}
if(Dispatcher.customerRequiresPickUp() && (customer = Dispatcher.queue.poll()) != null && (rideCount >= workFinished))
{
System.out.println("Customer has been picked up by driver #" + ID);
try
{
Thread.sleep(rn.nextInt(5000) + 1000);
System.out.println("Driver #" + ID + " has dropped off " + customer.getName() + " at " + customer.getEndLocation() + ".");
}
catch(InterruptedException e)
{
}
}
else
{
System.out.println("Driver #" + ID + " will continue to wait for a customer.");
}
You need curly brackets {} if an the body of an if statement is more than one line. Like so ^.

Removing all occurrences of a key only removes one

I have the following:
ArrayList<GregorianCalendar> toRemove = new ArrayList<GregorianCalendar>();
SortedSet<GregorianCalendar> copyKeys = new TreeSet<GregorianCalendar>(MyCalendarTester.myCal.getMyCalHash().keySet());
for(GregorianCalendar remove: toRemove){
copyKeys.removeAll(Collections.singleton(remove));
}
And I am trying to remove every occurrence of the key "remove" in my TreeSet copyKeys. But it only seems to remove one of them. Could someone please tell me what I'm doing wrong? Please let me know if you need more information.
EDIT:
For the sake of it, here is my entire mess of a method (I know it has a few more issues that just the question that I am asking), but here is goes:
public void eventList(){
int year = -1;
GregorianCalendar tempKey = null;
ArrayList<Event> tempArr = new ArrayList<Event>();
ArrayList<GregorianCalendar> toRemove = new ArrayList<GregorianCalendar>();
int countEnd = 0;
if(MyCalendarTester.myCal.getMyCalHash().equals(null)){
System.out.println("Your calendar is empty!");
}
else{
System.out.println("Here are your events: ");
SortedSet<GregorianCalendar> keys = new TreeSet<GregorianCalendar>(MyCalendarTester.myCal.getMyCalHash().keySet());
SortedSet<GregorianCalendar> copyKeys = new TreeSet<GregorianCalendar>(MyCalendarTester.myCal.getMyCalHash().keySet());
tempKey = keys.first();
int countTotal = keys.size();
for(GregorianCalendar key : copyKeys){
GregorianCalendar copyKey = key;
Event value = MyCalendarTester.myCal.getMyCalHash().get(key);
// System.out.println(" key.get(Calendar.MONTH) = " + key.get(Calendar.MONTH));
// System.out.println("(tempKey.get(Calendar.MONTH)) = " + (tempKey.get(Calendar.MONTH)));
// System.out.println(" key.get(Calendar.DATE) = " + key.get(Calendar.DATE));
// System.out.println(" tempKey.get(Calendar.DATE) = " + (tempKey.get(Calendar.DATE)));
tempArr.add(value);
countEnd++;
if(key.get(Calendar.MONTH) == (tempKey.get(Calendar.MONTH))
&& key.get(Calendar.DATE) == (tempKey.get(Calendar.DATE))
&& key.get(Calendar.YEAR) == tempKey.get(Calendar.YEAR)){
// tempArr.add(value);
if(key.get(Calendar.YEAR) != year){
System.out.println(key.get(Calendar.YEAR));
year = key.get(Calendar.YEAR);
System.out.println(MyCalendarTester.arrayOfDays[key.get(Calendar.DAY_OF_WEEK) - 1] + ", " + MyCalendarTester.arrayOfMonths[key.get(Calendar.MONTH) - 1] + " "
+ key.get(Calendar.DATE) + " ");
}
toRemove.add(copyKey);
// toRemove.add(copyKey);
//keys.remove(copyKey);
}else{
//if(count <= 1){
//if(tempArr.size() == 1){
if(countEnd == countTotal){
tempArr.remove(tempArr.size() - 1);
}else{
if(tempArr.size() > 1){
tempArr.remove(tempArr.size() - 2);
}else{
tempArr.remove(tempArr.size() - 1);
}
if(toRemove.size() > 0){
toRemove.remove(toRemove.size() - 1);
}
}
// }
// else{
// tempArr.remove(tempArr.size() - 2);
// toRemove.remove(toRemove.size() - 1);
// }
//
// count = 0; //reset matches
//}
}
tempKey = key;
}
Collections.sort(tempArr);
for(Event e: tempArr){
if(e.endTime != null){
System.out.println(" " + e.eventName + " " + e.startTime.get(Calendar.HOUR_OF_DAY) + ":" +
e.startTime.get(Calendar.MINUTE) + " " + e.endTime.get(Calendar.HOUR_OF_DAY)
+ ":" + e.endTime.get(Calendar.MINUTE));
//tempKey = key;
// year = key.get(Calendar.YEAR);
//keys.remove(key);
}
else{
System.out.println(" " + e.eventName + " " + e.startTime.get(Calendar.HOUR_OF_DAY) + ":" +
e.startTime.get(Calendar.MINUTE));
// tempKey = key;
// year = key.get(Calendar.YEAR);
//keys.remove(key);
}
}
tempArr.clear();
//break;
for(GregorianCalendar remove: toRemove){
copyKeys.removeAll(Collections.singleton(remove));
}
for(GregorianCalendar key : copyKeys){
Event value = MyCalendarTester.myCal.getMyCalHash().get(key);
if(tempArr.size() == 0){
if(value.endTime != null){
if(key.get(Calendar.YEAR) == year){
System.out.println(MyCalendarTester.arrayOfDays[key.get(Calendar.DAY_OF_WEEK) - 1] + ", " + MyCalendarTester.arrayOfMonths[key.get(Calendar.MONTH) - 1] + " "
+ key.get(Calendar.DATE) + " " + value.startTime.get(Calendar.HOUR_OF_DAY) + ":" + value.startTime.get(Calendar.MINUTE) + " - " + value.endTime.get(Calendar.HOUR_OF_DAY)
+ ":" + value.endTime.get(Calendar.MINUTE) + " " + value.eventName);
// tempKey = key;
}else{
System.out.println(key.get(Calendar.YEAR));
System.out.println(MyCalendarTester.arrayOfDays[key.get(Calendar.DAY_OF_WEEK) - 1] + ", " + MyCalendarTester.arrayOfMonths[key.get(Calendar.MONTH) - 1] + " "
+ key.get(Calendar.DATE) + " " + value.startTime.get(Calendar.HOUR_OF_DAY) + ":" + value.startTime.get(Calendar.MINUTE) + " - " + value.endTime.get(Calendar.HOUR_OF_DAY)
+ ":" + value.endTime.get(Calendar.MINUTE) + " " + value.eventName );
year = key.get(Calendar.YEAR);
tempKey = key;
}
}else{
if(key.get(Calendar.YEAR) == year){
System.out.println(MyCalendarTester.arrayOfDays[key.get(Calendar.DAY_OF_WEEK) - 1] + ", " + MyCalendarTester.arrayOfMonths[key.get(Calendar.MONTH) - 1] + " "
+ key.get(Calendar.DATE) + " " + value.startTime.get(Calendar.HOUR_OF_DAY) + ":" + value.startTime.get(Calendar.MINUTE) + " " + value.eventName);
tempKey = key;
}else{
System.out.println(key.get(Calendar.YEAR));
System.out.println(MyCalendarTester.arrayOfDays[key.get(Calendar.DAY_OF_WEEK) - 1] + ", " + MyCalendarTester.arrayOfMonths[key.get(Calendar.MONTH) - 1] + " "
+ key.get(Calendar.DATE) + " " + value.startTime.get(Calendar.HOUR_OF_DAY) + ":" + value.startTime.get(Calendar.MINUTE) + " " + value.eventName);
System.out.println();
year = key.get(Calendar.YEAR);
tempKey = key;
}
}
}
}
}
}
I originally have it sorted by the keys (dates) in ascending order. From there, I am looking for any identical dates and sorting them by the time (values). Then, since I've already sorted and printed those days by the time, I don't want to reprint them later. I've been tweaking this for hours to try to get it to cooperate, so perhaps I'm over thinking it at this point. Anyway, if anyone is nice enough to look at this and make a few suggestions, I'd greatly appreciate it. Otherwise, just skip over because this is a long and convoluted one.
There will only be one occurrence of any given object in a Set and that is why only one is being removed.
Sets do not allow duplicates. If you want to allow duplicates, use another data structure such as an ArrayList.

clearing a JLabel not working [closed]

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 9 years ago.
Improve this question
I have read several posts suggesting to clear a JLabel (displayEntered) on a panel (display) with text by using the setText(" "). However, I have tried this and the outcome is it is just posting the array entered twice and does not clear the first set. I have an action shown below when a button is pressed both times; the first is to enter the data entered (I have the same code 4 times for the 4 different possible objects to enter but just put in the one since it's basically the same), which works fine and the second is to remove a specific one shown. My code is long, so am just putting that in. If someone wants something else please let me know. Thanks, I'd appreciate any input!
//adds the Herb data to the Array and list
enterHerbData.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Enter")){
Name = NameTxt.getText();
Colors = ColorTxt.getText();
ID = (int) IDCmbo.getSelectedItem();
Flavor = FlavorTxt.getText();
if(((String) MedicinalCmbo.getSelectedItem()).equals("Yes"))
Medicinal = true;
else
Medicinal = false;
if(((String) SeasonalCmbo.getSelectedItem()).equals("Yes"))
Seasonal = true;
else
Seasonal = false;
plants[count] = new Herb(Name, ID, Colors, Flavor, Medicinal, Seasonal);
String displayArraytemp = " ";
if(plants[count] != null){
if(plants[count] instanceof Flower){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Flower)plants[count]).getColor() + ", " + ((Flower)plants[count]).getSmell() + ", Thorny: " + ((Flower)plants[count]).getThorns() + "\n");
}
else if(plants[count] instanceof Fungus){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Fungus)plants[count]).getColor() + ", Poisonous: " + ((Fungus)plants[count]).getPoisonous() + "\n");
}
else if(plants[count] instanceof Weed){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Weed)plants[count]).getColor() + ", Edible: " + ((Weed)plants[count]).getEdible() + ", Medicinal: " + ((Weed)plants[count]).getMedicinal() + ", Poisonous: " + ((Weed)plants[count]).getPoisonous() + "\n");
}
else if(plants[count] instanceof Herb){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Herb)plants[count]).getColor() + ", " + ((Herb)plants[count]).getFlavor() + ", Medicinal: " + ((Herb)plants[count]).getMedicinal() + ", Poisonous: " + ((Herb)plants[count]).getSeasonal() + "\n");
}
sb.append("<html>" + displayArraytemp).
append("<br> ");
displayArray = sb.toString();
}
displayEntered.setText(displayArray);
count++;
frameB.setVisible(false);
}
}
});
//removes the data to the Array and panel
ActionListener RemoveAction = new ActionListener(){
#Override
public void actionPerformed(ActionEvent RemoveAction){
if(RemoveAction.getActionCommand().equals("Enter")){
if((Btn1).isSelected()){
String displayArraytemp2 = " ";
if(count >= 1){
for(int n = 0; n < count; n++){
plants[n] = plants[n+1];
}
count--;
frameB.setVisible(false);
displayEntered.setOpaque(true);
for(int n = 0; n < 25; n++){
if(plants[n] != null){
if(plants[n] instanceof Flower){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Flower)plants[n]).getColor() + ", " + ((Flower)plants[n]).getSmell() + ", Thorny: " + ((Flower)plants[n]).getThorns() + "\n");
}
else if(plants[n] instanceof Fungus){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Fungus)plants[n]).getColor() + ", Poisonous: " + ((Fungus)plants[n]).getPoisonous() + "\n");
}
else if(plants[n] instanceof Weed){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Weed)plants[n]).getColor() + ", Edible: " + ((Weed)plants[n]).getEdible() + ", Medicinal: " + ((Weed)plants[n]).getMedicinal() + ", Poisonous: " + ((Weed)plants[n]).getPoisonous() + "\n");
}
else if(plants[n] instanceof Herb){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Herb)plants[n]).getColor() + ", " + ((Herb)plants[n]).getFlavor() + ", Medicinal: " + ((Herb)plants[n]).getMedicinal() + ", Poisonous: " + ((Herb)plants[n]).getSeasonal() + "\n");
}
sb.append("<html>" + displayArraytemp2).
append("<br> ");
displayArray = sb.toString();
}
}
}
displayEntered.setText(" ");
displayEntered.setText(displayArray);
}
}
}};
Your real problem is that you are re-using sb without clearing it.

Categories

Resources