Ok, so I have tried everything even hard coding unicode into my program, but my conditional statement won't read that a √- was matched in the TextArea. I'm writing a calculator program and I want Java to read it as NaN. It only skips over my else if statement when I'm using the TextArea itself. I tested it without the TextArea and I get NaN, but returns the number used in the TextArea.
For Example:
Test Program (without GUI) --> Runs perfectly fine outputs NaN
String Text = "√-25";
System.out.println(Text);
ArrayList<String> OP = new ArrayList();
ArrayList<Float> NUM = new ArrayList();
Scanner OPscan = new Scanner(Text).useDelimiter("[[.][0-9]]+");
Scanner NUMscan = new Scanner(Text).useDelimiter("[-+*/√]+");
int iOP = 0;
int iNUM = 0;
float Root = 0;
while (OPscan.hasNext()) {
OP.add(OPscan.next());
}
OPscan.close();
System.out.println(OP + "OP Size: " + OP.size());
while (NUMscan.hasNextFloat()) {
if (OP.get(iOP).equals("-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "+");
} else if (OP.get(iOP).equals("--")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "-");
} else if (OP.get(iOP).equals("+-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "+");
} else if (OP.get(iOP).equals("*-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "*");
} else if (OP.get(iOP).equals("/-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "/");
} else if (OP.get(iOP).equals("√-")) {
NUM.add(-NUMscan.nextFloat());
OP.set(iOP, "√");
} else {
NUM.add(NUMscan.nextFloat());
}
iOP++;
}
System.out.println(NUM + "NUM Size: " + NUM.size());
System.out.println(OP + "NUM Size: " + NUM.size());
while (OP.contains("√")) {
try {
if (OP.get(iOP).equals("√")) {
Root = (float) Math.sqrt(NUM.get(iNUM));
NUM.set(iNUM, Root);
OP.remove(iOP);
System.out.println(Root + " Root!");
}
if (OP.get(0).matches("[+-*/]+")) {
iOP++;
iNUM++;
}
} catch (IndexOutOfBoundsException IndexOutOfBoundsException) {
System.out.println("Index Error Bypassed! " + "INDEX: " + "iOP:" + iOP + " iNUM:" + iNUM + " | Size: " + "iOP:" + OP.size() + " iNUM:" + NUM.size());
iOP = 0;
iNUM = 0;
}
}
Program with GUI & TextArea outputs --> just 25
Use the Unicode representation of √
\u221A
e.g.
public static void main(String[] args) {
System.out.println("Encoding: " + System.getProperty("file.encoding"));
JTextArea area = new JTextArea(10, 30);
JScrollPane pane = new JScrollPane(area);
JOptionPane.showMessageDialog(null, pane);
String text = area.getText();
char sqrt = '\u221A';
if (text.contains(Character.toString (sqrt))) {
System.out.println("YES for " + text);
} else {
System.out.println("NO for " + text);
}
}
Related
Appreciate the help. I am using Java and I want to write a text in the file. I am not sure what is wrong with my code. Is below code sufficient since it is a snippets of the program? I am trying to write a text in the file and there is no error. When I tried opening the file, the file is blank.
PharmacyReceipt = is the file where the system will read it and compute the total price
PharmacyInvoice = if the money exceeds the total price, the system will write an invoice and delete the receipt file
Thank you
double change = 0;
grandTotal = 0;
try {
BufferedReader pharmacyFile = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
BufferedWriter write1 = new BufferedWriter(new FileWriter("pharmacyInvoice.txt", true));
String input_1;
System.out.printf("%-16s %-50.30s %-20s %-20s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = pharmacyFile.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
System.out.printf("%-16s %-50.30s %-20.2f %-20.2f %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
grandTotal += netAmount;
}
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
pharmacyFile.close();
System.out.print("Do you want to proceed to print the receipt? ");
choice_3 = sc.nextLine();
choice_3 = choice_3.toUpperCase();
if (choice_3.equals("YES") || choice_3.equals("Y")) {
System.out.print("\nHow much is the money? ");
double money = sc.nextDouble();
if (grandTotal <= money) {
BufferedReader groceryFile1 = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
System.out.printf("%-16s %-50.30s %-20s %-15s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = groceryFile1.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
write1.write(adminObject.getProductCode() + "," + adminObject.getName() + "," + adminObject.getPrice() + "," + adminObject.getQuantity() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "\n");
System.out.printf("%-16s %-50.30s %.2f\t\t %.2f\t\t %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
}
write1.write("___________________________________________________");
write1.write("\nGrand Total = PHP %.2f\n\n" + grandTotal);
write1.write("Money: " + money + "\n");
write1.write("Change: " + (change = money - grandTotal) + "\n");
write1.write("___________________________________________________\n");
System.out.println("___________________________________________________\n");
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
System.out.println("Money: " + money + "\n");
System.out.println("Change: " + (change = money - grandTotal) + "\n");
System.out.println("___________________________________________________\n");
}
} else {
System.out.println("___________________________________________________\n");
System.out.println("***Money exceeds the amount.***");
System.out.println("___________________________________________________\n");
}
pharmacyFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found" + e);
} catch (IOException e) {
System.out.println("File Not Found");
} catch (NumberFormatException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
break;
You have to close the writer at the end via writer1.close(). Because you have a BufferedWriter, it is not writing to the file always immediately. If then your program for example exits before it can write, your content to the file, it will remain blank.
Also you should just in general always close this kind of resources at the end as they might cause memory leaks and other problems. You can do it via:
try (FileWriter writer1 = new FileWriter(new File("blablub")) {
// ... do your stuff with the writer
}
This is called a try-with-resources clause and will close the Resource in the end automatically. The more explicit version is:
FileWriter writer1 = new FileWriter(newFile("blablub"));
try {
// ... do your stuff with the writer
} catch (Exception ex) {
...
} finally {
writer1.close();
}
Edit: It might be, that you are thinking that you are closing the writer1 as I've now seen, but actually you have two calls to pharmacyFile.close(). Maybe this is your issue.
I am trying to understand time complexity calculation of a function but i am stuck at this point. Unlike for loop this while loop shown in the code below will depend on the input String length. How to calculate Time complexity for such cases?
The function Does this
Blockquote
Input Data: 4Gopi7Krishna3Msc5India
Output Data: {"4":"Gopi","7":"Krishna","3":"Msc","5":"India"}
Input data and length may vary each and every time.
public static String SplitData(String input) {
try {
String outputJSON = "{";
boolean run = true;
while (run) {
String firstChar = String.valueOf(input.charAt(0));
int length = Integer.parseInt(firstChar);
if (length > 0) {
String data = input.substring(1, (length + 1));
outputJSON = outputJSON + "\"" + String.valueOf(length) + "\":\"" + data + "\"";
if (length + 1 == input.length()) {
run = false;
outputJSON = outputJSON + "}";
System.out.println("TAG " + length + " LENGTH " + length + " DATA " + data + " INPUT " + input);
} else {
outputJSON = outputJSON + ",";
input = input.substring(length + 1, input.length());
System.out.println("TAG " + length + " LENGTH " + length + " DATA " + data + " INPUT " + input);
}
} else //IF INPUT IS NOT VALID MAKE THE RETURN JSON NULL
{
run = false;
outputJSON = "Invalid Input";
}
}
return outputJSON;
} catch (Exception e) {
e.printStackTrace();
return "Invalid Input";
}
}
complexity depends on the number of the possible operations before the execution ends, a for loop wouldn't be faster if you don't change what is done inside.
this function could be much simpler and faster by just using String manipulation functions
public static void main(String args[]){
String s = "4Gopi7Krishna3Msc5India";
String res = "";
String sp[] = s.split("[0-9]+");
res += "{";
for (int i = 0; i<sp.length; i++){
String sss = sp[i];
if(sss.length()==0)
continue;
res += "\""+sss+"\":\""+Integer.toString(sss.length())+"\"" ;
res += (i == (sp.length - 1))?"":",";
}
res+="}";
System.out.println(res);
}
I am having some problem reading the value ba,fr,lit and mid. May I know how should I resolve it. I tried declaring them as global variables but it was to no avail. Kindly help thanks, below is the code, the error occurs on this line ( fileout.println(m + " , " + l + " , " + s + " , " + u + " , " + ba + " , " + " , " + fr + " , " + lit + " , " + mid );)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String m = model.getText();
String l = line.getText();
String s = shift.getText();
String u = unitno.getText();
String ba;
String fr;
String lit;
String mid;
try{
Double b = Double.parseDouble(back.getText());
if(b<350 || b>625){
back.setForeground(Color.BLUE);
back.setBackground(Color.YELLOW);
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "The value that you have entered is not within the range of 350 to 625. Press yes to save anyway and cancel to edit.", "Error", dialogButton);
if(dialogResult ==0){
ba = back.getText();
}
}
else{
ba = back.getText();
back.setForeground(Color.BLACK);
back.setBackground(Color.WHITE);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please ensure that it is in integer.");
back.setForeground(Color.BLUE);
back.setBackground(Color.YELLOW);
}
try{
Double f = Double.parseDouble(front.getText());
if(f<350 || f>625){
front.setForeground(Color.BLUE);
front.setBackground(Color.YELLOW);
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "The value that you have entered is not within the range of 350 to 625. Press yes to save anyway and cancel to edit.", "Error", dialogButton);
if(dialogResult ==0){
fr = front.getText();
}
}
else{
fr = front.getText();
front.setForeground(Color.BLACK);
front.setBackground(Color.WHITE);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please ensure that it is in integer.");
front.setForeground(Color.BLUE);
front.setBackground(Color.YELLOW);
}
try{
Double li = Double.parseDouble(little.getText());
if(li<0.8 || li>3.4){
little.setForeground(Color.BLUE);
little.setBackground(Color.YELLOW);
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "The value that you have entered is not within the range of 0.8 to 3.4. Press yes to save anyway and cancel to edit.", "Error", dialogButton);
if(dialogResult ==0){
lit = little.getText();
}
}
else{
lit = little.getText();
little.setForeground(Color.BLACK);
little.setBackground(Color.WHITE);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please ensure that it is in integer.");
little.setForeground(Color.BLUE);
little.setBackground(Color.YELLOW);
}
try{
Double mi = Double.parseDouble(middle.getText());
if(mi<0.8 || mi>3.4){
middle.setForeground(Color.BLUE);
middle.setBackground(Color.YELLOW);
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "The value that you have entered is not within the range of 0.8 to 3.4. Press yes to save anyway and cancel to edit.", "Error", dialogButton);
if(dialogResult ==0){
mid = middle.getText();
}
}
else{
mid = middle.getText();
middle.setForeground(Color.BLACK);
middle.setBackground(Color.WHITE);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please ensure that it is in integer.");
middle.setForeground(Color.BLUE);
middle.setBackground(Color.YELLOW);
}
BufferedWriter output = null;
FileInputStream fs = null;
FileWriter fout = null;
try {
// TODO add your handling code here:
File myFile = new File("C:/Users/kai/Desktop/capforce.txt");
if(!myFile.exists()) {
myFile.createNewFile();
}
fs = new FileInputStream("C:/Users/kai/Desktop/capforce.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
output = new BufferedWriter(new FileWriter(myFile,true));
PrintWriter fileout = new PrintWriter(output,true);
if (br.readLine() == null) {
fileout.println("Model" + " " + "Date" + " " + " " + "Line" + " " + "Shift" + " " + "Unit Number" + " "+ "Capped Force - Capped Z1 (Back)" + " " + "Capped Force - Capped Z1 (front)" + " " +"Wiper to pen interference Z(Little man)" + " " + "Wiper to pen interference Z(Middle man)" );
}
for(int i = 1; i<100; ++i){
String line = br.readLine();
if(line==null){
fileout.println(m + " , " + l + " , " + s + " , " + u + " , " + ba + " , " + " , " + fr + " , " + lit + " , " + mid );
break;
}
}
} catch (IOException ex) {
Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
output.close();
} catch (IOException ex) {
Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
}
}
this.dispose();
}
Initialize all variables:
String ba = null;
String fr = null;
String lit = null;
String mid = null;
I made a code for my system which would update a record in my text file database but I cant seem to make it work. The code doesnt have any error. its just not doing what I intend it to do
public static void Update() throws Exception {
File tempfile2 = new File("temp.txt");
tempfile2.createNewFile();
FileInputStream tempFStream = new FileInputStream(tempfile2);
BufferedReader read = new BufferedReader(new InputStreamReader(tempFStream));
System.out.print("Product Number: ");
String searchnum = br.readLine();
try {
LoadFile();
boolean found = false;
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (!searchnum.equals(record[0])) {
found = true;
FileWriter fw = new FileWriter(tempfile2, true);
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
fw.close();
}
}
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (searchnum.equals(record[0])) {
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
System.out.print("\t\t\tAre you sure you want to replace the records?<Y/N>: ");
String del = br.readLine();
if (del.equals("Y") || del.equals("y")) {
LoadFile();
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\n\t\t\t------Update Record Form------");
System.out.print("\n\n\t\t\tProduct Number : ");
int prodnum = Integer.parseInt(br.readLine());
System.out.print("\t\t\tCategory : ");
String cat = br.readLine();
System.out.print("\t\t\tProduct Name :");
String prodname = br.readLine();
System.out.print("\t\t\tPrice: ");
String price = br.readLine();
System.out.print("\t\t\tQuantity : ");
String quan = br.readLine();
read.close();
database.delete();
boolean rename = false;
if (rename = tempfile2.renameTo(database)) {
InsertRecords(prodnum, cat, prodname, price, quan);
System.out.println("\t\t\tSuccessfully Edited!");
exiting();
} else {
System.out.print("Edit Failed!");
}
} else if (del.equals("N") || del.equals("n")) {
MainMenu();
}
}
if (!searchnum.equals(record[1])) {
System.out.println("\n\t\t\tNo Record Found.");
Thread.sleep(2000);
exiting();
}
}
} catch (Exception e) {
System.out.print("File Empty!");
}
}
public static void LoadFile()throws Exception
{
list.clear();
FileInputStream fis = new FileInputStream(database);
BufferedReader read = new BufferedReader(new InputStreamReader(fis));
row = 0;
while(read.ready())
{
list.add(read.readLine());
row++;
}
read.close();
}
Everytime I run this... it would work until Product Number: User input and after entering a number it would directly display File is empty which is at the end of the program. its as if the try/catch is ignored. I definitely did something wrong but I dont know what I did wrong. Anyone shed me some light? Thanks
and with the e.printStackTrace(); here's what displayed after entering a product number...
java.lang.ArrayIndexOutofBoundException:5
at SnackTimeInventorySystem.Update<SnackTimeInventorySystem.java:525>
at SnackTimeInventorySystem.MainMenu<SnackTimeInventorySystem.java:66>
at SnackTimeInventorySystem.Login<SnackTimeInventorySystem.java:369>
at SnackTimeInventorySystem.main<SnackTimeInventorySystem.java:14>
Turns out I only had 5 entries on my array but declared 6 entries to be written
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
So I just had to delete record[5] and fixed the problem thanks to Tom
I am writing a program to print the area and perimeter of a rectangle when a user provides the length and width. The user is asked to input how many rectangles he/she wants and then I use a for loop to ask for the length and width, which loops based on the number of rectangles the user inputed.
It prints and works like I want it to ... however, when the user chooses to continue and create more rectangles, the program will print the results of the old data plus the new data instead of just printing the new data.
I am very new to programming in Java and am stuck on how to fix this. It would be great if someone could help me out. Thanks!
This is my code:
import javax.swing.*;
public class RectangleProgram {
public static void main(String[] args) {
String defaultRectangleOutput = "";
String newRectangleOutput = "";
String finalOutput = "";
int option = JOptionPane.YES_OPTION;
while (option == JOptionPane.YES_OPTION) {
String rectangleNumberString = JOptionPane.showInputDialog(null,
"How many rectangles would you like to create? ",
"Number of Rectangles", JOptionPane.QUESTION_MESSAGE);
if (rectangleNumberString == null) return;
while (rectangleNumberString.equals("")) {
rectangleNumberString = JOptionPane.showInputDialog(
"You have entered nothing.\n" +
"Please try again: ");
}
int rectangleNumber = Integer.parseInt(rectangleNumberString);
while (rectangleNumber <= 0) {
rectangleNumberString = JOptionPane.showInputDialog(
"Entry cannot be 0 or negative.\n" +
"Please try again: ");
if (rectangleNumberString == null) return;
rectangleNumber = Integer.parseInt(rectangleNumberString);
}
for (int i = 0; i < rectangleNumber; i++) {
String lengthString = JOptionPane.showInputDialog(null,
"Enter Length for rectangle: ",
"Getting Length", JOptionPane.QUESTION_MESSAGE);
if (lengthString == null) return;
while (lengthString.equals("")) {
lengthString = JOptionPane.showInputDialog(
"You have entered nothing.\n" +
"Please try again: ");
}
double length = Double.parseDouble(lengthString);
while (length < 0) {
lengthString = JOptionPane.showInputDialog(
"Negative numbers are not allowed.\n" +
"Please try again: ");
if (lengthString == null) return;
length = Double.parseDouble(lengthString);
}
String widthString = JOptionPane.showInputDialog(null,
"Enter Width for rectangle: ",
"Getting Length", JOptionPane.QUESTION_MESSAGE);
if (widthString == null) return;
while (widthString.equals("")) {
widthString = JOptionPane.showInputDialog(
"You have entered nothing.\n" +
"Please try again: ");
}
double width = Double.parseDouble(widthString);
while (width < 0) {
widthString = JOptionPane.showInputDialog(
"Negative numbers are not allowed.\n" +
"Please try again: ");
if (widthString == null) return;
width = Double.parseDouble(widthString);
}
SimpleRectangle newRectangle = new SimpleRectangle(width, length);
newRectangleOutput += "Rect-" + i + " (" + newRectangle.width +
", " + newRectangle.length + ")\n" +
"Area = " + newRectangle.getArea() + "\n" +
"Perimeter = " + newRectangle.getPerimeter() + "\n";
}
SimpleRectangle defaultRectangle = new SimpleRectangle();
defaultRectangleOutput = "Default (" + defaultRectangle.width +
", " + defaultRectangle.length + ")\n" +
"Area = " + defaultRectangle.getArea() + "\n" +
"Perimeter = " + defaultRectangle.getPerimeter() + "\n";
JOptionPane.showMessageDialog(null, defaultRectangleOutput + "\n"
+ newRectangleOutput, "Final Results",
JOptionPane.PLAIN_MESSAGE);
option = JOptionPane.showConfirmDialog(
null, "Would you like to create another rectangle?");
}
}
}
class SimpleRectangle {
double length;
double width;
SimpleRectangle() {
length = 1;
width = 1;
}
SimpleRectangle(double newLength, double newWidth) {
length = newLength;
width = newWidth;
}
double getArea() {
return length * width;
}
double getPerimeter() {
return (2 * (length + width));
}
void setLengthWidth(double newLength, double newWidth) {
length = newLength;
width = newWidth;
}
}
You call
newRectangleOutput += "Rect-" + ...
which is equivalent to
newRectangleOutput = newRectangleOutput + "Rect-" + ...
So you add the output of the new rectangle the the old ones. Replace += by =, that is what you want.
You are appending your new rectangles to the same string. Add newRectangleOutput = ""; in the while loop before your for loop for all rectangles
while (option == JOptionPane.YES_OPTION) {
.
.
newRectangleOutput = "";
for (int i = 0; i < rectangleNumber; i++) {
.
.
}
}
check out what you did here...
newRectangleOutput += "Rect-" + i + " (" + newRectangle.width +
", " + newRectangle.length + ")\n" +
"Area = " + newRectangle.getArea() + "\n" +
"Perimeter = " + newRectangle.getPerimeter() + "\n";
you added the newRectangleOutput to the string again..that's why u re seeing the previous value...
to fix it...before you start with the next rectangle i.e end of each loop... make sure you set newRactangleOutput = "";