Removing all occurrences of a key only removes one - java

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.

Related

Is it possible to shorten this code?

I'm not exactly a beginner in Java, but I'm also not an expert. Is there any way to shorten this code so that it takes up less space and possibly fewer lines?
JOptionPane.showMessageDialog(null, "The student's names are: "
+ roster[0][0] + " " + roster[1][0] + ", "
+ roster[0][1] + " " + roster[1][1] + ", "
+ roster[0][2] + " " + roster[1][2] + ", and "
+ roster[0][3] + " " + roster[1][3] + ".");
Let's refactoring the code step by step
introduce variables to remove duplication.
T[] col1 = roster[0];
T[] col2 = roster[1];
String content = col1[0] + " " + col2[0] + ", "
+ col1[1] + " " + col2[1] + ", "
+ col1[2] + " " + col2[2] + ", and "
+ col1[3] + " " + col2[3] + ".";
JOptionPane.showMessageDialog(null,"The student's names are: " + content);
separate string concatenation into multi-assignments, then all assignments are the same except the last one.
int i = 0;
String content = "";
content += col1[i] + " " + col2[i] + ", ";i++;
content += col1[i] + " " + col2[i] + ", ";i++;
content += col1[i] + " " + col2[i] + ", ";i++;
content += "and " + col1[i] + " " + col2[i] + ".";i++;
make the multi-assignments consistent by using ternary operator.
int i = 0;
String content = "";
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", "); i++;
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", "); i++;
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", "); i++;
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", "); i++;
using while-loop to remove duplication.
int i = 0;
String content = "";
while(i<=3) {
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", ");
i++;
}
replacing while-loop with for-loop.
String content = "";
for (int i = 0; i <= 3; i++) {
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", ");
}
introduce variables to make the code more readable.
String content = "";
for (int i = 0; i <= 3; i++) {
String prefix = i == 3 ? "and " : "";
String current = col1[i] + " " + col2[i];
String suffix = i == 3 ? "." : ", ";
content += prefix + current + suffix;
}
inline the variables col1 & col2 that is used only once:
String content = "";
for (int i = 0; i <= 3; i++) {
String prefix = i == 3 ? "and " : "";
String current = roster[0][i] + " " + roster[1][i];
String suffix = i == 3 ? "." : ", ";
content += prefix + current + suffix;
}
replace magic number 3 with constant and the final code is below:
final int last = 3;
String content = "";
for (int i = 0; i <= last; i++) {
String prefix = i == last ? "and " : "";
String suffix = i == last ? "." : ", ";
String current = roster[0][i] + " " + roster[1][i];
content += prefix + current + suffix;
}
JOptionPane.showMessageDialog(null, "The student's names are: " + content);
StringBuilder message = new StringBuilder("The student's names are: ");
for (int i = 0; i < roster[0].length; i++) {
message
.append(roster[0][i])
.append(" ")
.append(roster[1][i]);
if (i < roster[0].length - 1)
message.append(", ");
if (i == roster[0].length - 2)
message.append("and ")
}
message.append(".");
JOptionPane.showMessageDialog(null, message.toString());
Possibly something like that. As you can see, you don't really save any lines, but obviously the code is more flexible as it can account for a variable length roster.
You can do the following: Initially assign the normal statement that you do not want repeated. Then loop through roster.
String rosterString= "The student's names are: ";
for(int i=0;i<= roster.length;i++){
for(int j=0;j<= roster[i].length;j++){
rosterString += (roster[i][j] + " ");
if (i == 1 && j < 2) {
rosterString += ", ";
}
else if (i == 1 && j == 2) {
rosterString += ", and";
}
else if (i == 1 && j == 3) {
rosterString += ".";
}
else {
rosterString += " ";
}
}
}
And then pass rosterString to your method.
String rosterString = "";
for(int i = 0; i < roster[0].length; i++) {
rosterString += roster[0][i] + " " + roster[1][i] + ", ";
}
That code will create a string with the names and commas. You could then add in if statements to check if it is near the end to change the , to an and or .

Working with BigIntegers

I creating a program where it takes a base unit in the metric system. (Say grams.) And then when you select a prefix changes it to the equivalent amount. (Such as 1000 grams when you select Kilo would change it to 1 Kilogram.)
Problem is when I run the code it'll always end up as zero, which makes me think I'm manipulating the BigIntegers wrong. (I'm using VERY large numbers due to some prefixes being very small or very large beyond the usual long number.)
Here is the code:
import java.util.Scanner;
import java.math.BigInteger;
public class BaseMetricUnits {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello, World!");
float meter = 1;
float kilogram = 1;
float second = 1;
float ampere = 1;
float kelvin = 1;
float mole = 1;
float candela = 1;
PrefixConverter();
}
public static void PrefixConverter()
{
BigInteger Yocto = BigInteger.valueOf((long) 0.00000000000000000000000);
BigInteger Zepto = BigInteger.valueOf((long) 0.000000000000000000001);
BigInteger Atto = BigInteger.valueOf((long) 0.000000000000000001);
BigInteger Femto = BigInteger.valueOf((long) 0.000000000000001);
BigInteger Pico = BigInteger.valueOf((long)0.000000000001);
BigInteger Nano = BigInteger.valueOf((long)0.000000001);
BigInteger Micro = BigInteger.valueOf((long)0.000001);
BigInteger Milli = BigInteger.valueOf((long)0.001);
BigInteger Centi = BigInteger.valueOf((long)0.01);
BigInteger Deci = BigInteger.valueOf((long)0.1);
BigInteger Deca = BigInteger.valueOf((long)10);
BigInteger Hecto = BigInteger.valueOf((long)100);
BigInteger Kilo = BigInteger.valueOf((long)1000);
BigInteger Mega = BigInteger.valueOf((long)1000000);
BigInteger Giga = BigInteger.valueOf((long)1000000000);
BigInteger Tera = new BigInteger("1000000000000");
BigInteger Peta = new BigInteger("1000000000000000");
BigInteger Exa = new BigInteger("1000000000000000000");
BigInteger Zetta = new BigInteger("1000000000000000000000");
BigInteger Yotta = new BigInteger("1000000000000000000000000");
long Amount;
double Prefix;
String Units = "";
BigInteger translatedResult;
BigInteger Result;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter the type of unit to be used. (meters, grams, etc.) >> ");
Units = inputDevice.next();
System.out.print("Please enter an amount to be translated >> ");
Amount = inputDevice.nextLong();
System.out.print("Please choose one of the following Prefixes to translate to. ");
System.out.print(" 1 - Yocto ");
System.out.print(" 2 - Zepto ");
System.out.print(" 3 - Atto ");
System.out.print(" 4 - Femto ");
System.out.print(" 5 - Pico ");
System.out.print(" 6 - Nano ");
System.out.print(" 7 - Micro ");
System.out.print(" 8 - Milli ");
System.out.print(" 9 - Centi ");
System.out.print(" 10 - Deci ");
System.out.print(" 11 - Deca ");
System.out.print(" 12 - Hecto ");
System.out.print(" 13 - Kilo ");
System.out.print(" 14 - Mega ");
System.out.print(" 15 - Giga ");
System.out.print(" 16 - Tera ");
System.out.print(" 17 - Peta ");
System.out.print(" 18 - Exa ");
System.out.print(" 19 - Zetta ");
System.out.print(" 20 - Yotta ") ;
Prefix = inputDevice.nextDouble();
if(Prefix == 1)
{
Result = Yocto.multiply(BigInteger.valueOf(Amount));
translatedResult = Yocto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Yocto" + Units + ".");
}
if(Prefix == 2)
{
Result = Zepto.multiply(BigInteger.valueOf(Amount));
translatedResult = Zepto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Zepto" + Units + ".");
}
if(Prefix == 3)
{
Result = Atto.multiply(BigInteger.valueOf(Amount));
translatedResult = Atto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Atto" + Units + ".");
}
if(Prefix == 4)
{
Result = Femto.multiply(BigInteger.valueOf(Amount));
translatedResult = Femto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Femto" + Units + ".");
}
if(Prefix == 5)
{
Result = Pico.multiply(BigInteger.valueOf(Amount));
translatedResult = Pico.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Pico" + Units + ".");
}
if(Prefix == 6)
{
Result = Nano.multiply(BigInteger.valueOf(Amount));
translatedResult = Nano.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Nano" + Units + ".");
}
if(Prefix == 7)
{
Result = Micro.multiply(BigInteger.valueOf(Amount));
translatedResult = Micro.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Micro" + Units + ".");
}
if(Prefix == 8)
{
Result = Milli.multiply(BigInteger.valueOf(Amount));
translatedResult = Milli.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Milli" + Units + ".");
}
if(Prefix == 9)
{
Result = Centi.multiply(BigInteger.valueOf(Amount));
translatedResult = Centi.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Centi" + Units + ".");
}
if(Prefix == 10)
{
Result = Deci.multiply(BigInteger.valueOf(Amount));
translatedResult = Deci.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Deci" + Units + ".");
}
if(Prefix == 11)
{
Result = Deca.multiply(BigInteger.valueOf(Amount));
translatedResult = Deca.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Deca" + Units + ".");
}
if(Prefix == 12)
{
Result = Hecto.multiply(BigInteger.valueOf(Amount));
translatedResult = Hecto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Hecto" + Units + ".");
}
if(Prefix == 13)
{
Result = Kilo.multiply(BigInteger.valueOf(Amount));
translatedResult = Kilo.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Kilo" + Units + ".");
}
if(Prefix == 14)
{
Result = Mega.multiply(BigInteger.valueOf(Amount));
translatedResult = Mega.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Mega" + Units + ".");
}
if(Prefix == 15)
{
Result = Giga.multiply(BigInteger.valueOf(Amount));
translatedResult = Giga.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Giga" + Units + ".");
}
if(Prefix == 16)
{
Result = Tera.multiply(BigInteger.valueOf(Amount));
translatedResult = Tera.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Tera" + Units + ".");
}
if(Prefix == 17)
{
Result = Peta.multiply(BigInteger.valueOf(Amount));
translatedResult = Peta.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Peta" + Units + ".");
}
if(Prefix == 18)
{
Result = Exa.multiply(BigInteger.valueOf(Amount));
translatedResult = Exa.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Exa" + Units + ".");
}
if(Prefix == 19)
{
Result = Zetta.multiply(BigInteger.valueOf(Amount));
translatedResult = Zetta.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Zetta" + Units + ".");
}
if(Prefix == 20)
{
Result = Yotta.multiply(BigInteger.valueOf(Amount));
translatedResult = Yotta.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Yotta" + Units + ".");
}
else
{
System.out.println("Not a valid input.");
}
}
}
Thanks for your help.
BigInteger can only store integers, and so is not a suitable data type for this application. I strongly recommend replacing it with BigDecimal.
You should also use string representations of the fractions to initialize:
BigDecimal Zepto = new BigDecimal("0.000000000000000000001");
BigDecimal Atto = new BigDecimal("0.000000000000000001");
BigDecimal Femto = new BigDecimal("0.000000000000001");
BigDecimal Pico = new BigDecimal("0.000000000001");
BigDecimal Nano = new BigDecimal("0.000000001");
Comments on this answer and on the question indicate a concern with using BigDecimal to store the larger numbers. This program illustrates the fact that it is not an issue:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
BigDecimal googol = new BigDecimal("1e100");
System.out.println(googol);
System.out.println(googol.add(BigDecimal.ONE));
}
}
Output:
1E+100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001

Is there any possibility to get the currentStockLevel from this method?

I need the currentStockLevel for another void Method in java, is there any possibility to get it?
I think no, because of void right?
public void receive (int currentStock)
{
String outLine;
if (currentStockLevel > 0)
outLine = productCode;
{
outLine = ". Current Stock: " + currentStockLevel;
outLine += " Current Stock changed from " + currentStockLevel;
currentStockLevel += currentStock;
outLine += " to " + currentStockLevel;
int storeCost = wholeSalePrice * currentStockLevel;
System.out.println (productCode + ":" + " Received " + currentStockLevel + "." + " Store Cost " + "$" + storeCost + "." + " New stock level: " + currentStockLevel);
}

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.

Storing part of method as another method?

Basically, I have code that uses the same few lines in different scenarios, and it makes the code a bit messy (especially since I probably overcomplicated what I made, but that's another issue). What I wanted to do is store that piece of code as another function and calling it in the longer one. WHich should work as far as I know, except, the longer function has variables that aren't set in the shorter one, and if they were, I'm pretty sure it would change the final result of the function.
Here is the longer code:
public static void combat(Character a,Character b){
int battleturn = 1;
int maxTurns=20;
int draw1 = 0;
//stop after 20 turns, or stop when one player has 0 HP.
while (a.health > 0 && b.health > 0 && maxTurns > 0){
/* run a round of combat*/
if (b.health < 0.25 * b.maxHealth){
if (b.getFlee(a)){
System.out.println(">>>>>>>>>>The enemy has fled successfully<<<<<<<<<<");
break;
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + "health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}
}
As you can see there is a part of code that is repeated, and that is.
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
It won't compile if I set that chunk of code as a method, because it doesn't have the variables battleturn, maxturns, draw1, but if I put them in there, the amount of battle turns messes up.
Any ideas?
Java applications should be modular: each class fulfilling its own function, each method generally performing a single operation.
In a method you can use either class variables or its own local variables.
If you need several methods work with the same data, it should either be part of a class (instance and/or static variables) or passed to each method as parameters.
Make sure that you do not define class variables in a method. This will create local variables that will shadow class variables.
This might help you accomplish what you're trying to do.
private static void reportDamage(Character a,
Character b) {
System.out.println(a.name + " dealt "
+ a.combatRound(b) + " damage to " + b.name
+ "." + " Enemy has " + b.getHealth() + "/"
+ b.getMaxHealth() + " health.");
}
I suggest changing your combat method like this.
int battleturn = 0;
int maxTurns = 20;
// stop after 20 turns, or stop when one player has 0
// HP.
Scanner input = new Scanner(System.in);
try {
while (a.health > 0 && b.health > 0
&& battleturn < maxturn) {
battleturn++;
/* run a round of combat */
if (b.getFlee(a)) {
System.out.println(">>>>>>>>>>"
+ "The enemy has fled successfully"
+ "<<<<<<<<<<");
break;
} else {
System.out.println("Battle turn "
+ battleturn + ", <attack> or <flee>?");
boolean isFlee = false;
boolean isAttack = false;
String move = input.next();
for (;;) {
isAttack = "attack".equalsIgnoreCase(move);
isFlee = "flee".equalsIgnoreCase(move);
if (isFlee || isAttack) {
break;
}
System.out.println("Error: "
+ "Please input <attack> or <flee>.");
move = input.next();
}
if (isAttack) {
reportDamage(a, b);
reportDamage(b, a);
} else { // isFlee
if (a.getFlee(b)) {
System.out.println(">>>>>>>>>>"
+ "You have fled successfully"
+ "<<<<<<<<<<");
break;
} else {
// b is fleeing.
// reportDamage(a, b);
reportDamage(b, a);
}
}
}
}
} finally {
input.close();
}

Categories

Resources