Double Printing of Data - java

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 = "";

Related

How do i assign a new value?

I need to find a way where the user can enter decimal numbers not only whole numbers for the division part and I also need help to fix the multiplication part, it keeps displaying the wrong answer when I intentionally wrote the wrong answer, for me it kept saying "the correct answer is 140" when the question was 5 x 2, and when I write 10 it says its correct but if its the same question and I write 4, for example, is says wrong the correct answer is 140 to the 5 x 2 question please help? here's my full code, and please if you find any more mistakes I did please let me know.
public static void main(String[] args) {
String name = JOptionPane.showInputDialog(null, "Please enter your name");
JOptionPane.showMessageDialog(null, "Hello " + name + "\nWelcome to your Math Quiz (no calculators allowed) \nPlease answer the following questions");
int randVal1 = (int) (20 * Math.random()) + 1;
int randVal2 = (int) (20 * Math.random()) + 1;
int randomNumberAdd = randVal1 + randVal2;
int randomNumberMul = randVal1 * randVal2;
int randomNumberDiv = randVal1 / randVal2;
int correct = 0;
for (int i = 1; i < 10; i++) {
String userAnswer = JOptionPane.showInputDialog(null, randVal1 + " + " + randVal2 + " = ");
int answer = parseInt(userAnswer);
if (answer == randVal1 + randVal2) {
JOptionPane.showMessageDialog(null, "Correct!");
correct++;
} else if (answer != randVal1 + randVal2) {
JOptionPane.showMessageDialog(null, "Incorrect!");
JOptionPane.showMessageDialog(null, "The correct answer is " + randomNumberAdd);
}
{
randVal1 = (int)(20* Math.random()) + 1;
randVal2 = (int)(20*Math.random()) + 1;
String userAnswerMul = JOptionPane.showInputDialog(null, randVal1 + " x " + randVal2 + " = " );
int answer2 = parseInt (userAnswerMul);
if (answer2 == randVal1 * randVal2){
JOptionPane.showMessageDialog(null, "Correct");
correct++;
} else if (answer2 != randVal1 * randVal2){
JOptionPane.showMessageDialog(null, "Incorrect");
JOptionPane.showMessageDialog(null, "The correct answer is " + randomNumberMul);
}
{
randVal1 = (int) (10 * Math.random()) + 1;
randVal2 = (int) (10 * Math.random()) + 1;
String userAnswerDiv = JOptionPane.showInputDialog(null, randVal1 + " รท " + randVal2 + " = ");
int answer3 = parseInt(userAnswerDiv);
if (answer3 == randVal1 / randVal2) {
JOptionPane.showMessageDialog(null, "Correct!");
correct++;
} else if (answer3 != randVal1 / randVal2) {
JOptionPane.showMessageDialog(null, "Wrong!");
JOptionPane.showMessageDialog(null, "The correct answer is " + randomNumberDiv);
}
{
}
}
}
}
JOptionPane.showMessageDialog(null, "You got " + correct + " correct answers.");
}
}

Looping error in Method in Java

Hi guys this is my first post in this website and I'm still new to Java. This my code that i am working on.
public static void main(String[] args) throws Exception {
// debug
if ($DEBUG) System.out.println("starting\n");
//read data from text file into arrays w,p
String[] wArr = new String[50];
String[] pArr = new String[50];
String fileName = "homs.txt";
readFile(fileName, wArr, pArr);
//main control loop
while (true) {
//use input dialog to get 2 words from user
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
String[] words = input.split("\\s+");
String w1 = words[0];
String w2 = words[1];
//check each word if in dictionary
int w1ix = chkFound(wArr, w1);
boolean isFound = (w1ix >= 0);
System.out.println(w1 + " is found: " + isFound);
int w2ix = chkFound(wArr, w2);
boolean isFound2 = (w2ix >= 0);
System.out.println(w2 + " is found: " + isFound2);
if (w1ix >=0 && w2ix >=0 ) msg = "both words " + w1 + " and " + w2 +
"\n\tare in dictionary";
else { msg = "one or more words not in dictionary: ";
if (w1ix <0) msg += w1 + " ";
if (w2ix <0) msg += w2 + " ";
System.out.println(msg);
//check if homonyms
boolean isHom = chkHom(pArr, w1, w2);
//output result
String line = msg +
"\nWord 1: " + w1 +
"\nWord 2: " + w2 +
"\nWord 1 in dictionary: " + isFound +
"\nWord 2 in dictionary: " + isFound2 +
"\nHomonyms: " + isHom;
JOptionPane.showMessageDialog(null, line);
//ask user to continue Y/N?
int cont = JOptionPane.showConfirmDialog(null, "Continue?");
if (cont > 0)
break;//exit loop or continue
}
//end main
}
}
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
My problem for this code is that when i run it it keeps looping
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
I think the reason for this problem is this part of the code. I have not come up with a solution for this though.
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
https://docs.oracle.com/javase/7/docs/api/constant-values.html#javax.swing.JOptionPane.OK_OPTION
public static final int OK_OPTION 0
your break doesn't work
if (cont > 0)
break;//exit loop or continue
change it to:
final int cont = JOptionPane.showConfirmDialog(null, "Continue?","Continue?", JOptionPane.YES_NO_OPTION);
if(cont == JOptionPane.NO_OPTION){
break;
}

Sorting app based on user input (names and running time) and sorts them in ascending numerical order

I made this program for my class, but when it runs it just randomly sorts the name and does not sorts them in numerical order (ascending). I don't know if I have any mistakes but I'm guessing the problem is in the "ifs" below:
import javax.swing.JOptionPane;
public class RaceOrderApp {
public static void main(String[] args) {
String racer1, racertime1str, racer2, racertime2str, racer3, racertime3str;
int racerTime1, racerTime2, racerTime3;
racer1 = JOptionPane.showInputDialog(null, "Enter the name of racer #1:" );
if (racer1 == null || racer1.length() == 0) {
JOptionPane.showMessageDialog(null, "You did not enter a name. The application will end.");
System.exit(1);}
racertime1str = JOptionPane.showInputDialog(null, "Enter the time of " + racer1 + ":" );
racerTime1 = Integer.parseInt(racertime1str);
if (racerTime1 >= 15 || racerTime1 <= 100) {
JOptionPane.showMessageDialog(null, "You did not enter a valid time. The application will end.");
System.exit(1);}
racer2 = JOptionPane.showInputDialog(null, "Enter the name of racer #2:" );
if (racer2 == null || racer2.length() == 0) {
JOptionPane.showMessageDialog(null, "You did not enter a name. The application will end.");
System.exit(1);}
racertime2str = JOptionPane.showInputDialog(null, "Enter the time of " + racer2 + ":" );
racerTime2 = Integer.parseInt(racertime2str);
if (racerTime2 >= 15 || racerTime2 <= 100) {
JOptionPane.showMessageDialog(null, "You did not enter a valid time. The application will end.");
System.exit(1);}
racer3 = JOptionPane.showInputDialog(null, "Enter the name of racer #3:" );
if (racer3 == null || racer3.length() == 0) {
JOptionPane.showMessageDialog(null, "You did not enter a name. The application will end.");
System.exit(1);}
racertime3str = JOptionPane.showInputDialog(null, "Enter the time of " + racer3 + ":" );
racerTime3 = Integer.parseInt(racertime3str);
if (racerTime3 >= 15 || racerTime3 <= 100) {
JOptionPane.showMessageDialog(null, "You did not enter a valid time. The application will end.");
System.exit(1);}
String firstRacer = racer1 + " " + racerTime1;
String secondRacer = racer2 + " " + racerTime2;
String thirdRacer = racer3 + " " + racerTime3;
if (racerTime1 > racerTime2) {
String temp = firstRacer;
firstRacer = secondRacer;
secondRacer = temp;
}
if (racerTime2 > racerTime3) {
String temp = secondRacer;
secondRacer = thirdRacer;
thirdRacer = temp;
}
if (racerTime1 > racerTime2 ) {
String temp = firstRacer;
firstRacer = secondRacer;
secondRacer = temp;
}
String mensaje="The order of the racers is:\n";
mensaje += "1st. " + firstRacer + "\n";
mensaje += "2nd. " + secondRacer + "\n";
mensaje += "3rd. " + thirdRacer + "\n";
JOptionPane.showMessageDialog(null, mensaje);
}
}
Thanks in advance to anybody who can help!
You've got a problem with you if statements
(racerTime2 >= 15 || racerTime2 <= 100) has something wrong with the signs
It says if bigger than 15 or smaller than 100, it must be bigger than 100 or smaller than 15 as of:
if (racerTime2 <= 15 || racerTime2 >= 100)
All your if statements should end with ; as you are not using else or else if

How to access data in my code? - variable might have not been initialised

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;

Hanging token from user input is not allowing me to proceed in my program

My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);

Categories

Resources