Need to be pointed in the right direction with my Loops code - java
newbie at Java here. My professor returned my file with this comment
"3) The program does not implement the new loop correctly. The purpose of the loop was to allow the user to enter in their four numbers and do the math. The program should then ask the user if they want to continue, If they do, the program should allow the entry of four more numbers. The should continue until the user specifically says no they want to stop.
"
I am confused about how to ask the user if they wanted to continue then allow re entry of four more numbers again.
I'm having issues on entering the proper error message as well.
import java.util.Scanner;
public class Loops {
public static void main(String[] args) {
// 1. Declare two integer variables and two double variables
int iNumber;
int iNumber2;
double iDecimal;
double iDecimal2;
int count;
char yesNo = 'y'; // When a char variable is declared, the value needs to be a char not a string. Therefore, it needs a single quote instead of a double quote.
// 2. Instantiate a Scanner object
Scanner input = new Scanner(System.in);
// 3. Place the entry of the number into a loop that requires the user to enter the values at least one time.
//int i = 1;
// NOTE – Steps 4 through 8 are EXACTLY the same as the CE-Decision exercise. You may reuse that code if you would like.
// 4. Using print, display two lines that allows the user to enter in the two integer values on the same line as the prompt.
System.out.print("Input integer value 1: ");
iNumber = input.nextInt();
System.out.print("Input integer value 2: ");
iNumber2 = input.nextInt();
// 5. Using print, display two lines that allows the user to enter in the two double values on the same line as the prompt.
System.out.print("Input double value 1: ");
iDecimal = input.nextDouble();
System.out.print("Input double value 2: ");
iDecimal2 = input.nextDouble();
// 6. Using multiple printf statements, display the result of adding, subtracting, multiplying, dividing and moding the two integer values.
if (iNumber > iNumber2)
{
System.out.println("\nNumber 1 is greater than Number 2: ");
//+ instead of , for Printlns. , for printf. To add, use parenthesis.
System.out.println("\nInput integer value 1: "+ iNumber);
System.out.println("Input integer value 2: "+ iNumber2);
System.out.println("Input double value 1: "+ iDecimal);
System.out.println("Input double value 2: "+ iDecimal2);
System.out.println("\nInteger output: ");
System.out.printf("%s%d%s%d%s%d%n", "Adding ", iNumber, " and ", iNumber2, " = ", iNumber + iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Subtracting ", iNumber, " and ", iNumber2, " = ", iNumber - iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Multiplying ", iNumber, " and ", iNumber2, " = ", iNumber * iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Dividing ", iNumber, " and ", iNumber2, " = ", iNumber / iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Moding ", iNumber, " and ", iNumber2, " = ", iNumber % iNumber2);
System.out.println("\nDouble output: ");
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Adding ", iDecimal, " and ", iDecimal2, " = ", iDecimal + iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Subtracting ", iDecimal, " and ", iDecimal2, " = ", iDecimal - iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Multiplying ", iDecimal, " and ", iDecimal2, " = ", iDecimal * iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Dividing ", iDecimal, " and ", iDecimal2, " = ", iDecimal / iDecimal2);
}
else if (iNumber < iNumber2)
{
System.out.println("\nNumber 2 is greater than Number 1:");
//+ instead of , for Printlns. , for printf. To add, use parenthesis.
System.out.println("\nInput integer value 1: " + iNumber);
System.out.println("Input integer value 2: " + iNumber2);
System.out.println("Input double value 1: " + iDecimal);
System.out.println("Input double value 2: " + iDecimal2);
System.out.println("\nInteger output: ");
System.out.printf("%s%d%s%d%s%d%n", "Adding ", iNumber, " and ", iNumber2, " = ", iNumber + iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Subtracting ", iNumber, " and ", iNumber2, " = ", iNumber - iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Multiplying ", iNumber, " and ", iNumber2, " = ", iNumber * iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Division ", iNumber, " and ", iNumber2, " = ", iNumber / iNumber2);
System.out.printf("%s%d%s%d%s%d%n\n", "Moding ", iNumber, " and ", iNumber2, " = ", iNumber % iNumber2);
System.out.println("Double output: ");
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Adding ", iDecimal, " and ", iDecimal2, " = ", iDecimal + iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Subtracting ", iDecimal, " and ", iDecimal2, " = ", iDecimal - iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Multiplying ", iDecimal, " and ", iDecimal2, " = ", iDecimal * iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Dividing ", iDecimal, " and ", iDecimal2, " = ", iDecimal / iDecimal2);
}
else if (iNumber2 == iNumber)
{
System.out.println("\nBoth numbers are equal");
//+ instead of , for Printlns. , for printf. To add, use parenthesis.
System.out.println("\nInput integer value 1: "+ iNumber);
System.out.println("Input integer value 2: "+ iNumber2);
System.out.println("Input double value 1: "+ iDecimal);
System.out.println("Input double value 2: "+ iDecimal2);
System.out.println("\nInteger output: ");
System.out.printf("%s%d%s%d%s%d%n", "Adding ", iNumber, " and ", iNumber2, " = ", iNumber + iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Subtracting ", iNumber2, " and ", iNumber, " = ", iNumber2 - iNumber);
System.out.printf("%s%d%s%d%s%d%n", "Multiplying ", iNumber, " and ", iNumber2, " = ", iNumber * iNumber2);
System.out.printf("%s%d%s%d%s%d%n", "Division ", iNumber, " and ", iNumber2, " = ", iNumber / iNumber2);
System.out.printf("%s%d%s%d%s%d%n\n", "Moding ", iNumber, " and ", iNumber2, " = ", iNumber % iNumber2);
System.out.println("Double output: ");
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Adding ", iDecimal, " and ", iDecimal2, " = ", iDecimal + iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Subtracting ", iDecimal2, " and ", iDecimal, " = ", iDecimal2 - iDecimal);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Multiplying ", iDecimal, " and ", iDecimal2, " = ", iDecimal * iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Dividing ", iDecimal, " and ", iDecimal2, " = ", iDecimal / iDecimal2);
}
else if (iNumber2 == 0)
{
System.out.println("\nNumber 2 equals 0:");
//+ instead of , for Printlns. , for printf. To add, use parenthesis.
System.out.println("\nInput integer value 1: "+ iNumber);
System.out.println("Input integer value 2: "+ iNumber2);
System.out.println("Input double value 1: "+ iDecimal);
System.out.println("Input double value 2: "+ iDecimal2);
System.out.println("\nInteger output: ");
System.out.printf("%s%d%s%d%s%d%n", "Adding ", iNumber, " and ", iNumber2, " = ", iNumber + iNumber2);
System.out.printf("%s%d%s%d%n", "Subtracting ", iNumber, " = ", iNumber - iNumber2);
System.out.printf("%s%d%s%d%n", "Multiplying ", iNumber, " = ", iNumber * iNumber2);
if (iNumber2 == 0 || iDecimal2 == 0){
System.out.println("Error: You cannot divide and mod by zero!!!");
}
else {
System.out.printf("%s%d%s%d%s%d%n", "Division ", iNumber, " and ", iNumber2, " = ", iNumber / iNumber2);
System.out.printf("%s%d%s%d%s%d%n\n", "Moding ", iNumber, " and ", iNumber2, " = ", iNumber % iNumber2);
}
System.out.println("Double output: ");
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Adding ", iDecimal, " and ", iDecimal2, " = ", iDecimal + iDecimal2);
System.out.printf("%s%.2f%s%.2f%n", "Subtracting ", iDecimal, " = ", iDecimal - iDecimal2);
System.out.printf("%s%.2f%s%.2f%n", "Squaring ", iDecimal, " = ", iDecimal * iDecimal2);
System.out.printf("%s%.2f%s%.2f%s%.2f%n", "Dividing ", iDecimal, " and ", iDecimal2, " = ", iDecimal / iDecimal2);
}
// a. Test the two numbers, subtract the smaller number from the larger number. Display the output with the numbers in the proper order. If the numbers are equal, display a message that subtracting a number from itself gives you zero.
// b. If the two numbers are equal, the program should display the message as “Squaring” a number instead of multiplying two numbers.
// c. If the second number is zero, the program should display an error message saying that you cannot divide or mod by zero.
// 7. Using multiple printf statements, display the result of adding, subtracting, multiplying, and dividing the two double values.
// a. Test the two numbers, subtract the smaller number from the larger number. Display the output with the numbers in the proper order. If the numbers are equal, display a message that subtracting a number from itself gives you zero.
// b. If the two numbers are equal, the program should display the message as “Squaring” a number instead of multiplying two numbers.
// c. If the second number is zero, the program should display an error message saying that you cannot divide by zero.
// 8. Make sure that there is a title before each of the two outputs and there are blank lines between the input section and the two output sections.
// 9. Ask the user if they wish to enter in another set of numbers.
count = input.nextInt();
do {
System.out.println("Do you wish to enter another set of numbers?: (y/n)");
yesNo = input.next().charAt(0);
// a. The only valid entries are : y, Y, n or N (single letters)
if (yesNo != 'Y' && yesNo != 'y' && yesNo != 'N' && yesNo != 'n') {
System.out.println("Error = you must enter Y or N. Please retry. "); // Error message should be inside the if statement block or else the error message would always appear.
}
} while (yesNo != 'Y' && yesNo != 'y' && yesNo != 'N' && yesNo != 'n');
}
}
System.out.print("Do you wish to enter another set of numbers?: (y/n)");
String answer = scan.nextLine();
// b. Use the Java construct input.next().charAt(0) to get the character value
// c. Place the input into a loop that tests the entry for validity
// i. If the entry is valid, end the loop
// ii. If the entry is invalid, display an error message and ask the user to reenter their response
// 10. If the user indicated that they wish to enter new values, continue the loop and allow the user to reenter a new set of values.
// a. The user should be allowed to reenter values as many times as they like. Only the entry of ‘n’ or ‘N’ should cause the loop to end.
// 11. If the user indicated that they do not wish to enter any more values, end the loop and display a thank you/goodbye message.
// 12. Comment your code.
//3) The program does not implement the new loop correctly. The purpose of the loop was to allow the user to enter in their four numbers and do the math.
// The program should then ask the user if they want to continue, If they do, the program should allow the entry of four more numbers.
// The should continue until the user specifically says no they want to stop.
enter image description hereenter image description here
This question is barely readable. You should try writing neater questions so more people will be able to assist you. Give a short portion of the code where the problem lies and ask "why is this incorrect?".
As for your question, I think you should have another while loop, which will include the logic you implemented. Something like while(yesNo == 'Y' || yesNo == 'y'). So while this is true, you read 4 inputs from the user. To me it seems like you don't even care if the user entered 'n' or 'y', your do-while loop merely checks input validity.
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.
Java error handling for project- Line matched except underscores: Invalid Event Code_?
I completed this java project for a class, but I cannot seem to fix the error I'm getting for the web software that grades it- it's called webcat. I've tried the test input the software suggests for a reference test against my solution, and my output looks exactly the same, but I still lost points for this error- "Error in method main of class Event: Line number 2 of your output is incorrect (line numbers begin at 1). Your main method does not print the correct output when the input is "This is a short test " (input less than 26 characters) [] Line matched except underscores: Invalid Event Code_". How can I fix this error when the expected ouput looks fine? Thanks in advance! Code: public class Event { /** * accepts coded event info, prints the info back to std output, and actual cost and prize number. * * #param args Command line arguments - not used. */ public static void main(String[] args) { // variables needed String shrink, event, date, time, section, row, seat; double price, discount, cost; int prizeNum; // accept input Scanner userInput = new Scanner(System.in); // format the numbers DecimalFormat formatNum = new DecimalFormat("$#,##0.00"); // enter input and trim the space System.out.print("Enter your event code: "); shrink = userInput.nextLine().trim(); if (shrink.length() < 26) { System.out.println(); System.out.println("Invalid Event Code"); System.out.println("Event code must have at least 26 characters."); return; } // locates spot in index of code and assigns event = shrink.substring(25, shrink.length()); date = shrink.substring(0, 8); time = shrink.substring(8, 12); section = shrink.substring(19, 21); row = shrink.substring(21, 23); seat = shrink.substring(23, 25); price = Double.parseDouble(shrink.substring(12, 15) + "." + shrink.substring(15, 17)); discount = Double.parseDouble(shrink.substring(17, 19)); // calculates final cost cost = price - (price * (discount / 100)); // random final number prizeNum = (int) (Math.random() * 1000 + 1); // prints the data to std output System.out.println(); System.out.print("Event: " + event + " " + " " + " "); System.out.print("Date: " + date.substring(0, 2) + "/" + date.substring(2, 4) + "/" + date.substring(4, 8) + " " + " " + " "); System.out.println("Time: " + time.substring(0, 2) + ":" + time.substring(2, 4) + " " + " " + " "); System.out.print("Section: " + section + " " + " " + " "); System.out.print("Row: " + row + " " + " " + " "); System.out.println("Seat: " + seat); System.out.print("Price: " + formatNum.format(price) + " " + " " + " "); // formats discount before print formatNum.applyPattern("#.#'%'"); System.out.print("Discount: " + formatNum.format(discount) + " " + " " + " "); // formats cost before print formatNum.applyPattern("$#,##0.00"); System.out.println("Cost: " + formatNum.format(cost)); System.out.print("Prize Number: " + prizeNum); Output: Enter your event code: This is a short test Invalid Event Code Event code must have at least 26 characters.
Storing Statistics in Java Calculator
Having difficulty storing the following statistics to be printed when the program terminates. I have been able to store the total number of valid and invalid expressions however I am having difficulty with the following: The highest overall result value. The lowest overall result value. The aggregate of all result values, i.e. all results added together. The average result value Any guidance for any of the above would be much appreciated. Scanner input = new Scanner(System.in); // Creating new scanner to take user choice input int validExpressions = 0; int invalidExpressions = 0; int lowestval = 0; int highestval; while (true) { System.out.println("Enter K to enter a postfix expression or F to open a text file:"); // requesting user input String choice = input.nextLine(); // Taking user input from keyboard, either K for manual entry or F for file input float answer; // Variable used to store answers. if ("F".equals(choice)) { System.out.println("Please enter the name of a .txt file:"); // user prompted to enter the name of the text file String file = input.nextLine(); // File name will be stored in a String (file) to be used later File txtfile = new File(file); Scanner reader = new Scanner(txtfile); // Creating a new scanner which reads the text file while (reader.hasNextLine()) { // The new scanner (reader) reads each line of the text file String expression = reader.nextLine(); // Each line is stored in a String called Expression String[] parts = expression.split(" "); // The string is split into three parts; two numbers and an operator String part1 = parts[0]; String part2 = parts[1]; String part3 = parts[2]; float number1 = Float.parseFloat(part1); // Parts one and two are both converted from a String to a Float float number2 = Float.parseFloat(part2); // Program processes the operator and applies it to Float number1 and Float number2 before outputting the // expression and the correct answer if ("+".equals(part3)) { answer = number1 + number2; System.out.println(part1 + " " + "+" + " " + part2 + " " + "=" + " " + answer); validExpressions++; } else if ("-".equals(part3)) { answer = number1 - number2; System.out.println(part1 + " " + "-" + " " + part2 + " " + "=" + " " + answer); validExpressions++; } else if ("*".equals(part3)) { answer = number1 * number2; System.out.println(part1 + " " + "*" + " " + part2 + " " + "=" + " " + answer); validExpressions++; } else if ("/".equals(part3)) { answer = number1 / number2; System.out.println(part1 + " " + "/" + " " + part2 + " " + "=" + " " + answer); validExpressions++; } } } else if ("K".equals(choice)) // If the user enters K input will be taken from the keyboard System.out.println("Please enter a post-fix expression:"); // User is prompted to enter a post fix expression Scanner expression = new Scanner(System.in); // Creating a new Scanner called Expression to read user input String exp = expression.nextLine(); // The user's input is stored in a string String[] elements = exp.split(" "); // Expression is split into three elements, two numbers and an operator String element1 = elements[0]; String element2 = elements[1]; String element3 = elements[2]; float num1 = Float.parseFloat(element1); // Element1 and element2 are converted to Floats and named num1 and num2 float num2 = Float.parseFloat(element2); // Program processes the operator and applies it to Float num1 and Float num2 before outputting the // expression and the correct answer if ("+".equals(element3)) { answer = num1 + num2; System.out.println(element1 + " " + "+" + " " + element2 + " " + "=" + " " + answer); validExpressions++; } else if ("-".equals(element3)) { answer = num1 - num2; System.out.println(element1 + " " + "-" + " " + element2 + " " + "=" + " " + answer); validExpressions++; } else if ("*".equals(element3)) { answer = num1 * num2; System.out.println(element1 + " " + "*" + " " + element2 + " " + "=" + " " + answer); validExpressions++; } else if ("/".equals(element3)) { answer = num1 / num2; System.out.println(element1 + " " + "/" + " " + element2 + " " + "=" + " " + answer); validExpressions++; if (choice.isEmpty()) { // If the user does not enter K or F the program will exit System.out.println("Evaluations Complete"); System.out.println("-------------------------"); System.out.println("Valid expressions: " + validExpressions); System.out.println("Invalid expressions: " + invalidExpressions); System.exit(0); } } } } }
I have changed something wrong on logic and syntax,but I have not debuged it ,you may have a try. Scanner input = new Scanner(System.in); // Creating new scanner to take user choice input int validExpressions = 0; int invalidExpressions = 0; float lowestval = 0; float highestval =0 ; float total=0; while (true) { System.out.println("Enter K to enter a postfix expression or F to open a text file:"); // requesting user input String choice = input.nextLine(); // Taking user input from keyboard, either K for manual entry or F for file input float answer; // Variable used to store answers. if ("F".equals(choice)) { System.out.println("Please enter the name of a .txt file:"); // user prompted to enter the name of the text file String file = input.nextLine(); // File name will be stored in a String (file) to be used later File txtfile = new File(file); Scanner reader = new Scanner(txtfile); // Creating a new scanner which reads the text file while (reader.hasNextLine()) { // The new scanner (reader) reads each line of the text file String expression = reader.nextLine(); // Each line is stored in a String called Expression String[] parts = expression.split(" "); // The string is split into three parts; two numbers and an operator String part1 = parts[0]; String part2 = parts[1]; String part3 = parts[2]; float number1 = Float.parseFloat(part1); // Parts one and two are both converted from a String to a Float float number2 = Float.parseFloat(part2); // Program processes the operator and applies it to Float number1 and Float number2 before outputting the // expression and the correct answer if ("+".equals(part3)) { answer = number1 + number2; System.out.println(part1 + " " + "+" + " " + part2 + " " + "=" + " " + answer); validExpressions++; } else if ("-".equals(part3)) { answer = number1 - number2; System.out.println(part1 + " " + "-" + " " + part2 + " " + "=" + " " + answer); validExpressions++; } else if ("*".equals(part3)) { answer = number1 * number2; System.out.println(part1 + " " + "*" + " " + part2 + " " + "=" + " " + answer); validExpressions++; } else if ("/".equals(part3)) { answer = number1 / number2; System.out.println(part1 + " " + "/" + " " + part2 + " " + "=" + " " + answer); validExpressions++; } else{ invalidExcepressions++; continue; } highestval=(highestval>=answer)?highestval:answer; lowestval=(lowestval<=answer)?lowestval:answer; total+=answer; } } else if ("K".equals(choice)){ // If the user enters K input will be taken from the keyboard System.out.println("Please enter a post-fix expression:"); // User is prompted to enter a post fix expression Scanner expression = new Scanner(System.in); // Creating a new Scanner called Expression to read user input String exp = expression.nextLine(); // The user's input is stored in a string String[] elements = exp.split(" "); // Expression is split into three elements, two numbers and an operator String element1 = elements[0]; String element2 = elements[1]; String element3 = elements[2]; float num1 = Float.parseFloat(element1); // Element1 and element2 are converted to Floats and named num1 and num2 float num2 = Float.parseFloat(element2); // Program processes the operator and applies it to Float num1 and Float num2 before outputting the // expression and the correct answer if ("+".equals(element3)) { answer = num1 + num2; System.out.println(element1 + " " + "+" + " " + element2 + " " + "=" + " " + answer); validExpressions++; } else if ("-".equals(element3)) { answer = num1 - num2; System.out.println(element1 + " " + "-" + " " + element2 + " " + "=" + " " + answer); validExpressions++; } else if ("*".equals(element3)) { answer = num1 * num2; System.out.println(element1 + " " + "*" + " " + element2 + " " + "=" + " " + answer); validExpressions++; } else if ("/".equals(element3)) { answer = num1 / num2; System.out.println(element1 + " " + "/" + " " + element2 + " " + "=" + " " + answer); validExpressions++; }else{ invalidExceotions++; continue; } highestval=(highestval>=answer)?highestval:answer; lowestval=(lowestval<=answer)?lowestval:answer; total+=answer; }else if (choice.isEmpty()) { // If the user does not enter K or F the program will exit System.out.println("Evaluations Complete"); System.out.println("-------------------------"); System.out.println("Valid expressions: " + validExpressions); System.out.println("Invalid expressions: " + invalidExpressions); System.out.println("Total :"+total); System.out.println("Average :"+total/validExceptions); System.exit(0); } }
How do I output a draw from a vote (In Java)?
I have no idea on how to output a draw from a vote any help on with this would be appreciated. At the moment it will allow a user to select the amount of candidates and then the user inputs details. Then the user will enter a vote, which is the candidate number, and type 999 to finish. The output will be the winner or winners(draw)the candidates with details and votes and the amount of spolit votes that is votes not in the range declared at the start. int x; char highestChar = '1'; char nextHighestChar = '1'; String alpha = "123456"; int largest=intVoteCount[1]; int nextLargest=intVoteCount[1]; for( x=1; x<=range; x++){ if(intVoteCount[x]>largest){ largest = intVoteCount[x]; highestChar = alpha.charAt(intLoopCount); } if(intVoteCount[x]>highestChar){ nextLargest = intVoteCount[x]; nextHighestChar = alpha.charAt(intLoopCount); } } System.out.println("The winner is Candidate number "+ highestChar + " with " + largest + " votes."); System.out.println("The winner is Candidate number "+ nextHighestChar + " with " + nextLargest + " votes."); System.out.println("-----------------------------"); System.out.println("The Candidate votes are as follows."); for (intLoopCount = 1; intLoopCount <= range; intLoopCount++) { // Display all records. // New Instance System.out.println(""); System.out.println("Candidate " + intLoopCount + " " + strCandidateTitle[intLoopCount] + " " + strCandidateFirstname[intLoopCount] + " " + strCandidateSurname[intLoopCount] + " votes " + intVoteCount[intLoopCount]); } System.out.println("-----------------------------"); System.out.println("Vote Count Spolit: " + intVoteCountSpolit); } }
If largest == nextLargest you have a draw, so print out an appropriate message saying so; otherwise, you have an explicit winner.
Output after multiplication shows weird characters, JAVA
Hello fellow programmers. Maybe it's a trivial question, yet I cant figure out solution, neither I can find any clue how to solve this. If its double post I am really sorry. Here's the code: !! Don't forget to import your "java.util.Scanner" !! double id[]=new double[4]; double price[]=new double[4]; String productName[]=new String[4]; id[0]=10001; id[1]=10002; id[2]=10003; id[3]=10004; price[0]=20; price[1]=25; price[2]=40; price[3]=10; productName[0]="T-Shirt"; productName[1]="More expensive T-Shirt"; productName[2]="Jacket"; productName[3]="Singlet"; int x=0; int z=0; int options; double discount; System.out.println("Type in number of your choice between 1 to 4"); Scanner menu = new Scanner(System.in); options = menu.nextInt(); do { System.out.println("Chosen product n.: "+ options); }while (x > 0); switch (options){ case 1: System.out.println("Id of product: " + id[0] + " " + "Product price:" +price[0] + " " + "Name of product: " + productName[0]); break; case 2: System.out.println("Id of product: " + id[1] + " " + "Product price: " +price[1] + " " + "Name of product: " + productName[1]); break; case 3: System.out.println("Id of product: " + id[2] + " " + "Product price: " +price[2] + " " + "Name of product: " + productName[2]); break; case 4: System.out.println("Id of product: " + id[3] + " " + "Product price: " +price[3] + " " + "Name of product: " + productName[3]); break; } discount=idPrice(price); System.out.println("Price after discount: " + price); } static double idPrice(double finalPrice[]) { return (finalPrice[1]/0.8); } } Here's the output after typing number 1: Type in number of your choice between 1 to 4 1 Chosen product n.: 1 Id of product: 10001.0 Product price: 20.0 Name of product: T-Shirt Price after discount: [D#3590efa8 As you can see the Price after discount is a mess. It should output number 20(25*0.8 (Hell yea 20% discount)). That's the first question. Next thing is. How can I spicify which finalPrice will be multiplied? Thank you all. Hope it will be helpfull to someone else also.
You're printing an array, not it's elements. In order to do so, you have to iterate through them: for (double d : prices) { System.out.println(d); } Edit: After reading the comments, you should print the discount variable: System.out.println("Price after discount: " + discount);
System.out.println("Price after discount: " + price); Print Array of double------------------^ You need to iterate to print the price array like below for (double d : price) { System.out.println("Price is "+d); }
Use java.util.Arrays.toString(price) to get a readable result. What you are getting now is the default toString method of the Object object: public String toString() { return getClass().getName() + "#" + Integer.toHexString(hashCode()); }