The purpose of my program is to ask what the temperature(F) is and what the weather condition outside is like.
The weather condition can be either sunny(1), raining(2), cloudy(3) or snowing(4.) The numbers 1-4 will be used to clarify what the weather condition is (I'm not sure how to do it any other way...)
Then, depending on the combination of temp and weatherCondition I want to be able to display 3 garments out of 10 choices, based on the combo of temp and weatherCondition.
I'm still learning so I apologize if my question or problem seems mundane...
At the moment when a user enters the temp and weatherCondition, a response is given depending on the combo of the two inputs (ex. hot-sunny, freezing-snowing).
Instead, I would like to create one or more txt files and have each one named something like hotSunny.txt for example. Inside these txt files I've listed 10 types of garments. I ultimately want the program to recognize which combo matches its appropriate txt file and then randomly display 3 of the 10.
What I've got so far...
public static void main(String[] args)
{
double temperature;
int weatherCondition;
String input;
input = JOptionPane.showInputDialog("What is " +
"the current temperature?");
temperature = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Sweet I now know the temperature! " +
"Now please take a look out the nearest window is it Sunny , Rainy ," +
" Cloudy or Snowy? " +
"(1 = Sunny) (2 = Raining) " +
"(3 = Cloudy) (4 = Snowing)");
weatherCondition = Integer.parseInt(input);
if (temperature <= 32){
if (weatherCondition == 4){
freezingSnowing();
} else if (weatherCondition == 3){
freezingCloudy();
} else if (weatherCondition == 2){
freezingRain();
} else {
freezingSunny();
}
}..........
else if ((temperature >= 33) && (temperature <= 50)) {
else if ((temperature >= 51) && (temperature <= 75)) {
else if ((temperature >= 76) && (temperature <= 140)) {
public static void freezingSnowing()
{
JOptionPane.showMessageDialog(null, "It's is snowing! I recommend that you dress very warm" +
"and wear a large coat that is preferably water proof.");
}
Your freezingSnowing method should look like this:
public static void freezingSnowing() {
file = new File(MyWeatherApp.class.getResource
(path + "freezingSnowing.txt"));
// path to the txt file
// where path is the local path to the file
scanner = new Scanner(file);
ArrayList<String> garments = new ArrayList<>(10);
while(scanner.hasNextLine()) {
garments.add(scanner.nextLine());
}
ArrayList<Integer> indices = new ArrayList<>(3);
for(int i = 0; i < 3; i++) {
while(true) { // watch out for duplicates
int rand = (int)(Math.random() * 9);
if(!indices.contains(rand))
break;
}
indices.add(rand);
JOptionPane.showMessageDialog(null, "It's is snowing! " +
"I recommend that you dress very warm " +
"and wear " + garments.get(indices.get(1)) +
", " garments.get(indices.get(2)) +
" and " + garments.get(indices.get(3)) +
".");
}
This is my version of randomly picking item.
public static void main(String[] args) {
String[] weatherCond = new String[] {"cold", "hot"};
ArrayList<String> garmets = new ArrayList<String>();
garmets.add("clothes");
garmets.add("hat");
garmets.add("gloves");
garmets.add("coat");
ArrayList<String> pick;
int ITEM = 3;
int temperature = 29;
if (temperature >= 30) { // hot condition
System.out.println("weather condition " + weatherCond[0]);
pick = garmets;
for (int i = 0; i < ITEM; i++) {
int idx = (int) (Math.round(Math.random() * pick.size()) % pick.size());
System.out.print(pick.get(idx) + " " );
pick.remove(idx);
}
} else {
System.out.println("weather condition " + weatherCond[1]);
pick = garmets;
for (int i = 0; i < ITEM; i++) {
int idx = (int) (Math.round(Math.random() * pick.size()) % pick.size());
System.out.print(pick.get(idx) + " " );
pick.remove(idx);
}
}
}
Also, if you want to use a fix set of garmets for a specific weather condition, you could use a hashmap which uses weather condition as a key and garmet groups as a value.
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
What's the simplest way to print a Java array?
(37 answers)
Closed 10 months ago.
I have a method called processClaims() which takes input from the user "by asking how many files need to be claimed". The method is shown below.
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
The problem is with the array or the for loop I belive. The output is shown below which isn't correct
[LInsuranceSystem$EarthquakeInsurance;#548c4f57
If that is wrong here is the whole code, I am having trouble debugging this.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
public class Slack
{
public static void main(String[] args) throws FileNotFoundException {
InsuranceSystem insuranceSystem = new InsuranceSystem();
insuranceSystem.start();
}
}
class InsuranceSystem {
Scanner input = new Scanner(System.in);
Calendar dateTime = Calendar.getInstance();
ArrayList<String> claimsReport = new ArrayList<>();
EarthquakeInsurance[] claims;
String fileName = " ";
char cont = ' ', correct = ' ';
public InsuranceSystem() {
}
public void start() throws FileNotFoundException {
System.out.println("MUTUALLY ACCIDENTAL INC.");
System.out.println("Do you want an analysis of earthquake coverage for your property? Enter 'Y' or 'N': ");
cont = input.next().charAt(0); //reads user input from input and applies to it var cont
input.nextLine(); //clears buffer
if (cont == 'y' || cont == 'Y') {
processClaims();
writeClaimsRecords();
checkInputFile();
}
printThankYou();
}
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
public void writeClaimsRecords() throws FileNotFoundException
{
String record = " ";
Scanner input = new Scanner(System.in);
System.out.println("Enter the file name for the claims' records (WARNING: This will erase a pre-existing file!): ");
fileName = input.nextLine();
PrintWriter outputFile = new PrintWriter(fileName);
for(int i = 0; i < claims.length; i++){
record = String.format("%s, %f, %f%n", claims[i].insured, claims[i].homeInsVal, claims[i].richter);
}
outputFile.printf(record);
outputFile.close();
System.out.println("Data written to the" + fileName + " file.");
}
public void checkInputFile() throws FileNotFoundException {
String fileRecord = " ";
File file = new File("Claims.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()) {
fileRecord = inputFile.nextLine();
System.out.println(fileRecord);
System.out.println("");
inputFile.close();
}
}
public void printThankYou() {
System.out.println("Thank you for using the Earthquake Coverage Analyzer.");
}
class EarthquakeInsurance {
//STUDENTS INSERT LINE COMMENTS DESCRIPTIVE OF THE PURPOSE OF EACH VARIABLE.
private String insured;
private String coverage;
private String message;
private double homeInsVal;
private double richter;
private double payout;
private double deductible;
private Scanner input = new Scanner(System.in);
private boolean repeat;
private char correct;
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance() {
}//END Default Constructor
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance(String insured, double homeInsVal, double richter) {
setInsured(insured);
setHomeInsVal(homeInsVal);
setRichter(richter);
}//END EarthquakeInsurance(String, double, double)
/**
* STUDENTS CODE copy() AND PROVIDE METHOD BOX COMMENTS.
*/
public String copy() {
String insuranceObj = " ";
return insuranceObj;
}
/**
* STUDENTS CODE equals AND PROVIDE METHOD BOX COMMENTS.
*/
public boolean equals(String aClaim) {
boolean isEqual = false;
if (isEqual = false) {
isEqual = true;
}
return isEqual;
}
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setInsured(String insured) {
this.insured = insured;
}//END setInsured(String): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setHomeInsVal(double homeInsVal) {
this.homeInsVal = homeInsVal;
}//END setHomeInsVal(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setRichter(double richter) {
this.richter = richter;
}//END setRichter(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setInsured() {
String insuredCopy = null, first = null, last = null;
int indexOfSpace = 0;
do {
System.out.printf("%nMUTUALLY ACCIDENTAL, INC."
+ "%nEarthquake Coverage Analyzer"
+ "%n%nPlease enter your name: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
while (!isAlpha(insuredCopy)) {
System.out.printf("%nInvalid name! Please re-enter: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
}//while insured's name is NOT alphabetic
System.out.printf("%nYour Name: %s"
+ "%n%nIs this name correct? \'Y\' or \'N\': ",
insured);
correct = input.nextLine().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
} while (repeat); //do-while insured name is not correct
indexOfSpace = insured.indexOf(" "); //Locate where the space is in insured.
if (indexOfSpace > 0) {
first = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, indexOfSpace).toLowerCase();
last = Character.toUpperCase(insured.charAt(indexOfSpace + 1))
+ insured.substring(indexOfSpace + 2, insured.length()).toLowerCase();
insured = first + " " + last;
}//if there is more than one name, capitalize the first letter in each
else {
insured = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, insured.length()).toLowerCase();
}//else capitalize first letter of a single name
}//END setInsured(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setHomeInsVal() {
do {
do {
System.out.printf("%nPlease enter the insured value of your home: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when homeInsVal is invalid
homeInsVal = input.nextDouble();
if (homeInsVal < 0) {
System.out.printf("%nThe insured value of your home cannot be less than or equal to 0.%n");
repeat = true;
}//END if homeInsVal less than zero then prompt again
else {
System.out.printf("%nHome\'s Insured Value: $%,.0f"
+ "%n%nIs this insured value correct? \'Y\' or \'N\': ",
homeInsVal);
correct = input.next().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of insured value
} while (repeat); //END do-while repeats when homeInsVal is not correct
}//END setHomeInsVal(): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setRichter() {
do {
do {
System.out.printf("%nRichter Scale Damage Assessment"
+ "%n 9.0+ Total destruction."
+ "%n 8.0 Most structures fell."
+ "%n 7.0 Many buildings destroyed."
+ "%n 6.0 Many buildings considerably damaged, some collapsed."
+ "%n 4.5 Damage to poorly constructed buildings."
+ "%n 3.5 Felt by many people, no destruction."
+ "%n 0 Generally not felt by people."
+ "%n%nPlease enter the Richter scale value for the earthquake: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when richter is invalid
richter = input.nextDouble();
if (richter < 0) {
System.out.printf("%nInvalid! Richter cannot be negative. Please re-enter.%n");
repeat = true;
}//END if richter less than zero then prompt again
else {
System.out.printf("%nRichter Scale: %.2f"
+ "%n%nIs this richter value correct? \'Y\' or \'N\': ",
richter);
correct = input.next().toLowerCase().charAt(0);
input.nextLine();
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of richter
} while (repeat); //END do-while repeats when homeInsVal is not correct
testRichter();
}//END setRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
private void testRichter() {
if (richter >= 9.0) {
payout = homeInsVal * .90;
deductible = homeInsVal * .10;
message = "Total destruction.";
}//END if richter >= 9.0 else richter < 9.0
else if (richter >= 8.0) {
payout = homeInsVal * .80;
deductible = homeInsVal * .20;
message = "Most structures fell.";
}//END if richter >= 8.0 else richter < 8.0
else if (richter >= 7.0) {
payout = homeInsVal * .70;
deductible = homeInsVal * .30;
message = "Many buildings destroyed.";
}//END if richter >= 7.0 else richter < 7.0
else if (richter >= 6.0) {
payout = homeInsVal * .60;
deductible = homeInsVal * .40;
message = "Many buildings considerably damaged, some collapsed.";
}//END if richter >= 6.0 else richter < 6.0
else if (richter >= 4.5) {
payout = homeInsVal * .50;
deductible = homeInsVal * .50;
message = "Damage to poorly constructed buildings.";
}//END if richter >= 4.5 else richter < 4.5
else if (richter >= 3.5) {
payout = 0;
deductible = 0;
message = "Felt by many people, no destruction.";
}//END if richter >= 3.5 else richter < 3.5
else if (richter >= 0) {
payout = 0;
deductible = 0;
message = "Generally not felt by people.";
}//END if richter >= 0 else richter < 0
}//END testRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getInsured() {
return insured;
}//END getInsured(): int
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getHomeInsVal() {
return homeInsVal;
}//END getHomeInsVal(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getRichter() {
return richter;
}//END getRichter(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getPayout() {
return payout;
}//END getPayout(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getDeductible() {
return deductible;
}//END getDeductible(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getMessage() {
return message;
}//END getMessage(): String
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void validateNumber() {
if (repeat) //AS LONG AS THE INPUT IS "NOT" AN INTEGER OR DOUBLE
{
input.next(); //CONSUME NON-NUMERIC VALUE.
System.out.printf("%nWarning: You entered an invalid integer or "
+ "floating-point value.%n"); //RE-PROMPT
}//END if repeat when a number is an invalid type
}//END validateNumber(boolean): void
/**
* chars() returns the integer values of the characters in word.
* <p>
* allMatch determines whether the integer values for each character
* matches the predicate (criterion) that each character is a letter.
* <p>
* The :: is a method reference operator for calling isLetter from
* the Character class.
*
* #param word is the incoming String value to test.
* #return is true when the word is not empty and is alphabetic
* or false when it isn't.
*/
public final boolean isAlpha(String word) {
/* Test to see if the word is not empty AND if each letter
* in a word is an alphabetic character.
*/
return word != null && word.chars().allMatch(Character::isLetter);
}//END isAlpha(String): final boolean
}//END CLASS EarthquakeInsurance
}
Mistake 1)
for ( EarthquakeInsurance eachClaim : claims);
remove semi
Mistake 2)
System.out.println(claims);
Yes you are print the whole list
See also How do I print my Java object without getting "SomeType#2f92e0f4"?
I feel like I'm almost there with the code but the problem is the while loop I am not allowed to use break and continue statements for this program. The first output test its suppose to have 14 questions where you get 12 right and 2 wrong giving you 86%. As for the second test you get a perfect score while the last test takes you to 20 questions that being the max number of questions, 4 of the first 8 questions correctly and 4 of the first 8 incorrectly, and then the next 12 correctly giving you 80% Code below:
package proj3;
import java.util.Scanner;
public class Project4App {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int correctNum = 0;
int wrongNum = 0;
double percent = 0;
int subNumCorrect = 0;
int subNumWrong = 0;
int addNumCorrect = 0;
int addNumWrong = 0;
int totalQuestions = 0;
while(!(correctNum == 10 && totalQuestions == 10) && !(percent >= 85.0 && totalQuestions >= 10) && (totalQuestions != 20)) {
Question Quest = new Question();
System.out.println("What is the result?" + "\n" + Quest.toString());
int userInt = scnr.nextInt();
if((Quest.getOperator() == '+') && (userInt == Quest.determineAnswer())) {
addNumCorrect += 1;
}
else if(Quest.getOperator() == '+' && (userInt != Quest.determineAnswer())) {
addNumWrong += 1;
}
if((Quest.getOperator() == '-') && (userInt == Quest.determineAnswer())) {
subNumCorrect += 1;
}
else if((Quest.getOperator() == '-') && (userInt != Quest.determineAnswer())) {
subNumWrong += 1;
}
if(userInt == Quest.determineAnswer()){
correctNum += 1;
System.out.println("Congratulations, you got it correct!");
}
else if (userInt != Quest.determineAnswer()){
wrongNum += 1;
System.out.println("The correct answer for " + Quest.toString() + " is " + Quest.determineAnswer());
}
totalQuestions++;
percent = Math.round((double)(correctNum * 100) / (totalQuestions));
}
System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
System.out.println("The percent correct: " + percent + "%");
scnr.close();
}
}
I think this largely does what you want. A number of the counters weren't being modified as was intended. This is partly due to the amount going on in your main method making it hard to see what's going on (too much information). I've extracted functionality to smaller, more well defined methods.
You had a whole lot of logic effectively saying you want the user to have achieved 85% with at least 10 questions answered - and stop when 20 questions are asked. You could factor this condition out to a method returning a boolean isGameComplete(totalQuestions) and put this in the while condition-expression.
I've taken the liberty of implementing a question class based on the functionality that I think achieves the intention.
The correctPercent was rounded to an int which made it impossible to be == to 85.5%, say. I've converted this to a double so if you get more than 85%, say 85.25%, the game completes successfully.
Probably some other stuff I've added, which I've tried to comment in-line, if significant. Hopefully this is what you were after.
If it ever gets too difficult to understand, extracting small chunks of code to well named methods (even long ones) helps enormously, since it reduces your mental load.
class Project4App {
static final Scanner scanner = new Scanner(System.in);
static int correctNum = 0;
static int wrongNum = 0;
static int subNumCorrect = 0;
static int subNumWrong = 0;
static int addNumCorrect = 0;
static int addNumWrong = 0;
static int totalQuestions = 0;
static double percentCorrect = 0;
public static void main(String[] args) {
/**
* answer at least 9/10 questions correctly (to get 85%)
*/
while (percentCorrect < 85.0 && totalQuestions >= 10 && totalQuestions <= 20) {
Question question = new Question();
int userInt = getUsersAnswer(question);
boolean isCorrect = question.determineAnswer(userInt);
updateStatistics(question, isCorrect);
printResults(); // can remove this/comment this out - added to help with debugging
}
System.out.println();
System.out.println("------------ Game Complete! ------------");
printResults();
}
private static void printResults() {
System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
System.out.println("The percent correct: (" + (addNumCorrect+subNumCorrect) + "/" + totalQuestions +") " + percentCorrect + "%");
System.out.println("The percent wrong: (" + (addNumWrong+subNumWrong) + "/" + totalQuestions +") " + (100 - percentCorrect) + "%");
}
private static int getUsersAnswer(Question question) {
System.out.println("What is the result?" + "\n" + question.toString());
int userInt = scanner.nextInt();
return userInt;
}
public static void updateStatistics(Question question, boolean isCorrect){
if (question.getOperator() == '+') {
if (isCorrect) {
addNumCorrect++;
correctNum++; // newly added (wasn't updated)
} else {
addNumWrong++;
wrongNum++; // newly added - unused variable originall
}
} else { // operator is '-'
if (isCorrect) {
subNumCorrect++;
correctNum++; // newly added (wasn't updated)
} else {
subNumWrong++;
wrongNum++; // newly added - unused variable originall
}
}
totalQuestions++; // newly added
percentCorrect = (correctNum * 100) / totalQuestions;
}
}
class Question {
private static final int UPPER_LIMIT_ON_RANDOM_NUMBERS = 20;
private static final Random random = new Random();
private final int number1;
private final int number2;
private final char operator;
public Question() {
operator = Math.random()>0.5 ? '+' : '-';
number1 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // NOTE THE SUBTRACTION NUMBER COULD BE NEGATIVE IF number2
number2 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // IS GREATER THAN number1.
}
public char getOperator() {
return operator;
}
public boolean determineAnswer(int userAnswer) {
switch (operator) {
case '+':
return userAnswer == (number1 + number2);
case '-':
return userAnswer == (number1 - number2);
}
return false; // shouldn't end up here - would be better to throw an unchecked exception and crash the program - new RuntimeException()
}
#Override
public String toString() {
return number1 + " " + operator + " " + number2;
}
}
Output:
------------ Game Complete! ------------
Progress Report:
Addition:
You got 7 correct and 0 incorrect.
Progress Report:
Subtraction:
You got 2 correct and 1 incorrect.
The percent correct: (9/10) 90.0%
The percent wrong: (1/10) 10.0%
I am stuck at a part where I am supposed to declare a string variable called "phrase", where it shouldn't loop, all the way through.
to give you an idea my task is: Similar to Option 1 except the user enters 'N' (instead of 'Q') when they are done entering results for the first team. Then, the program inputs a second team name and its results until 'Q' is entered. Outputs two statements, like the statements in option 1 followed by a third statement that says which team is in first place (based on the number of points)
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal // how would I make this appear in the same while loop?
L
L
O
L
L
W
L
L
Q
Sample output:
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
UPDATE:
My code:
else if (option == 2){
int counter = 0;
int totalpoints = 0;
String phrase = keyboard.next();
while(go){
String letter = keyboard.next();
if (letter.equals("W")){
pointsW++;
}
else if (letter.equals("L")){
pointsL++;
}
else if (letter.equals("O")){
pointsO++;
}
counter++;
if (letter.equals("N")){
totalpoints = pointsW + pointsL + pointsO;
counter--;
go = false;
}
}
int counter2 = 0;
int totalpoints2 = 0;
pointsW = 2;
pointsL = 0;
pointsO = 1;
String phrase2 = keyboard.next();
while (go2){
String letter2 = keyboard.next();
if (letter2.equals("W")){
pointsW++;
}
else if (letter2.equals("L")){
pointsL++;
}
else if (letter2.equals("O")){
pointsO++;
}
counter2++;
if (letter2.equals("Q")){
counter2--;
totalpoints2 = pointsW + pointsL + pointsO;
go2 = false;
}
}
System.out.println(phrase + " has played "+counter+" games and has earned "+totalpoints+" points");
System.out.println(phrase2 + " has played "+counter2+" games and has earned "+totalpoints2+" points");
if (totalpoints > totalpoints2){
System.out.println(phrase + " is in first place by "+(totalpoints - totalpoints2) + " points");
}else{
System.out.println(phrase2 + " is in first place by "+(totalpoints2 - totalpoints) + " points");
}
}
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
The issue: This is the output I am getting "Montreal played 8 games and has earned 11 points" where instead it should be "Montreal has played 8 games and has earned 3 points"
The output I am getting
You can reuse the same variables for individual points i.e. pointsW and pointsO because you do not want to retain their values till the end where you are publishing the results. The same is the case with the variable for the loop condition i.e. go and the variable used for inputting win/loss i.e. letter.
You will need arrays or different variables for storing total points, countings, and team name.
import java.util.Scanner;
public class Standings {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
int pointsW = 0;
int pointsO = 0;
String letter;
boolean go = true;
if (option == 2) {
// Variables for total points, counting, and name for the first team
int playedGamesTeamOne = 0;
int teamOnePoints = 0;
String teamOneName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamOne++;
if (letter.equals("N")) {
teamOnePoints = pointsW + pointsO;
playedGamesTeamOne--;
go = false;
}
}
// Reset common variables
go = true;
pointsW = 0;
pointsO = 0;
// Variables for total points, counting, and name for the second team
int playedGamesTeamTwo = 0;
int teamTwoPoints = 0;
String teamTwoName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamTwo++;
if (letter.equals("Q")) {
teamTwoPoints = pointsW + pointsO;
playedGamesTeamTwo--;
go = false;
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned "
+ teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned "
+ teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out
.println(teamOneName + " is in first place by " + (teamOnePoints - teamTwoPoints) + " points");
} else {
System.out
.println(teamTwoName + " is in first place by " + (teamTwoPoints - teamOnePoints) + " points");
}
}
}
}
A sample run:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
you can use this code for option two
Scanner keyboard = new Scanner(System.in);
int teamCounter = 1;
//String[] teamsNames = new String[2];
String teamOneName="";
String teamTwoName="";
//int[] playedGames = new int[2];
int playedGamesTeamOne = 0;
int playedGamesTeamTwo = 0;
//int[] points = new int[2];
int teamOnePoints = 0;
int teamTwoPoints = 0;
boolean firstTimeTeam1 = true;
boolean firstTimeTeam2 = true;
while (teamCounter <= 2) {
if (teamCounter == 1) {
if (firstTimeTeam1) {
teamOneName = keyboard.nextLine();
firstTimeTeam1 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamOnePoints += 2;
playedGamesTeamOne++;
} else if (letter.equals("L")) {
playedGamesTeamOne++;
} else if (letter.equals("O")) {
teamOnePoints += 1;
playedGamesTeamOne++;
} else if (letter.equals("N")) {
teamCounter++;
}
} else {
if (firstTimeTeam2) {
teamTwoName = keyboard.next();
firstTimeTeam2 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamTwoPoints += 2;
playedGamesTeamTwo++;
} else if (letter.equals("L")) {
playedGamesTeamTwo++;
} else if (letter.equals("O")) {
teamTwoPoints += 1;
playedGamesTeamTwo++;
} else if (letter.equals("Q")) {
teamCounter++;
}
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned " + teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned " + teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out.println(teamOneName + " is in first place by " + (teamOnePoints-teamTwoPoints) + " points");
} else {
System.out.println(teamTwoName + " is in first place by " + (teamTwoPoints-teamOnePoints) + " points");
}
I am a graduate student learning the Java program. As a homework assignment, we are to do the following:
Create a menu of items where the user can input choices into an array
Create a method that figures out the prices of the items chose and return the sum
Right now, my output shows that the total being returned from the method is actually adding all the prices in the if statement instead of coordinating them with the user input array that was copied (see example output on bottom). We have not touched upon anything further than the standard array (no ArrayList or other methods). Please offer any advice, I will do my best to figure it out.
import java.util.Arrays;
import java.util.Scanner;
public class Online_Purchasing_HW6 {
public static final int ARRAY_LENGTH = 10; //Length of the array
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //Reads user input
int[] naMenuChoice = new int [ARRAY_LENGTH]; //Array for items chosen
String[] naMenu = new String [ARRAY_LENGTH]; //Array for menu items
int[] naItemPrice = new int [9]; //Array for item prices
String sCustomerName; //String for customer's name
int nChoice = 0; //Option chosen in menu by user/Used as Index
int nSum = 0; //Sum of items chosen
double dTotalPrice = 0; //Total price plus taxes
double dTaxes = 0; //Total taxes to be applied to total
//Declare Constants
final int SENTINEL = 10; //Used to end loop
final double SALES_TAX = 0.065; //Sales tax to be used
//Choices for menu denoted by strings
String sChoice1 = "1. Smartphone" + "\t" + "\t" + "$249";
String sChoice2 = "2. Smartphone Case" + "\t" + "$39";
String sChoice3 = "3. PC Laptop" + "\t" + "\t" + "$1149";
String sChoice4 = "4. Tablet" + "\t" + "\t" + "$349";
String sChoice5 = "5. Tablet Case" + "\t" + "\t" + "$49";
String sChoice6 = "6. eReader" + "\t" + "\t" + "$119";
String sChoice7 = "7. PC Desktop" + "\t" + "\t" + "$899";
String sChoice8 = "8. LCD Monitor" + "\t" + "\t" + "$299";
String sChoice9 = "9. Laser Printer" + "\t" + "$399";
String sChoice10 = "10. Complete my order";
//Prompt user for name
System.out.print("Please enter your name: ");
//Read customer's name
sCustomerName = input.nextLine();
//Menu of items for purchase
System.out.print("\n");
System.out.println("Best Purchase Products");
System.out.println(sChoice1);
System.out.println(sChoice2);
System.out.println(sChoice3);
System.out.println(sChoice4);
System.out.println(sChoice5);
System.out.println(sChoice6);
System.out.println(sChoice7);
System.out.println(sChoice8);
System.out.println(sChoice9);
System.out.println(sChoice10);
//Prompt user for item selection
System.out.print("Please select an item from the menu above: ");
naMenuChoice[nChoice] = input.nextInt();
//Loop to read integers from user
while (naMenuChoice[nChoice] != SENTINEL) {
//adds 1 everytime more than one item is chosen by the user
nChoice++;
//Prompt user for another choice since he/she has not chosen option "10"
System.out.print("Please select another item from the menu above: ");
naMenuChoice[nChoice] = input.nextInt();
} //end of while loop
System.out.print(Arrays.toString(naMenuChoice));
//If option 10 if chosen, the loop will end with this message
System.out.println("\n" + "Thank you for ordering with Best Purchase, " + sCustomerName );
//call calculateTotalPrice method passing Array
nSum = nCalculatePrice(naMenuChoice);
//Formulas
//Sales Tax
dTaxes = SALES_TAX * nSum;
//Total Amount Due
dTotalPrice = dTaxes + nSum;
System.out.println("Total items ordered: " + nChoice);
System.out.println("Price of items ordered: $" + nSum);
System.out.println("Sales tax: $" + dTaxes);
System.out.println("Total amount due: $" + dTotalPrice);
}//end of main method
//Method for calculating price
public static int nCalculatePrice(int[] naChoicesToPrice){
int nTotalPrice = 0; //int value to return
int nIndex = 0; //used as counter
int nItemPrice = 0; //used to assign price of items
int[] naAddedPrices = new int[ARRAY_LENGTH]; //new array for assigning prices
//For loop to sum up all entries from naItemPrice array
for (nIndex = 0; nIndex < ARRAY_LENGTH; nIndex++){
naAddedPrices[nIndex] = naChoicesToPrice[nIndex];
//end of For Loop
if (nIndex == 1) {
nItemPrice = 249;
nTotalPrice += nItemPrice;}
if (nIndex == 2) {
nItemPrice = 39;
nTotalPrice += nItemPrice;}
if (nIndex == 3) {
nItemPrice = 1149;
nTotalPrice += nItemPrice;}
if (nIndex == 4) {
nItemPrice = 349;
nTotalPrice += nItemPrice;}
if (nIndex == 5) {
nItemPrice = 49;
nTotalPrice += nItemPrice;}
if (nIndex == 6) {
nItemPrice = 119;
nTotalPrice += nItemPrice;}
if (nIndex == 7) {
nItemPrice = 899;
nTotalPrice += nItemPrice;}
if (nIndex == 8) {
nItemPrice = 299;
nTotalPrice += nItemPrice;}
if (nIndex == 9) {
nItemPrice = 399;
nTotalPrice += nItemPrice;}
} //end of for loop
return nTotalPrice;
}//end of naCalculatePrice method
}//end of class
Corresponding output for the program is:
Please enter your name: John Smith
Best Purchase Products
1. Smartphone $249
2. Smartphone Case $39
3. PC Laptop $1149
4. Tablet $349
5. Tablet Case $49
6. eReader $119
7. PC Desktop $899
8. LCD Monitor $299
9. Laser Printer $399
10. Complete my order
Please select an item from the menu above: 9
Please select another item from the menu above: 10
[9, 10, 0, 0, 0, 0, 0, 0, 0, 0]
Thank you for ordering with Best Purchase, John Smith
Total items ordered: 1
Price of items ordered: $3551
Sales tax: $230.815
Total amount due: $3781.815
As you can see, I chose only one item from the menu but it adds up all the prices. I've been on this assignment for 2 weeks so far and I'm growing desperate. I've read most articles on this site pertaining to this subject, read many articles on just methods and arrays, respectively and still can't formulate a working program.Any help would be appreciated.
Nice work so far.
In your for loop to sum up, you have to look into naMenuChoices to see what the customer has ordered. Remember, you may find a 0 or a 10 there, in which case you should not add anything to the sum. Good luck, you’re not that far from your goal.
You may want to make yourself a class for the product/items like
public class Product {
private String itemText;
private int itemPrice;
public Product(String itemText, int itemPrice) {
this.itemText = itemText;
this.itemPrice = itemPrice;
}
public int getItemPrice() {
return itemPrice;
}
#Override
public String toString() {
return itemText + "\t\t$" + itemPrice;
}
}
Fill 9 objects of this class into an array, use them for building the sChoice Strings and use it instead of the naItemPrice array. Modify my code to your needs. It should give a better overview of the code. And eliminate the risk of accidentally charging another price from the customer than the one announced.
for (int i = 0; i < ARRAY_LENGTH; i++){
if(naChoicesToPrice[i]==0 || naChoicesToPrice[i]==10){
nItemPrice = 0;
}
else{
if (naChoicesToPrice[i] == 1) {
nItemPrice = 249;
}
if (naChoicesToPrice[i] == 2) {
nItemPrice = 39;
}
if (naChoicesToPrice[i] == 3) {
nItemPrice = 1149;
}
if (naChoicesToPrice[i] == 4) {
nItemPrice = 349;
}
if (naChoicesToPrice[i] == 5) {
nItemPrice = 49;
}
if (naChoicesToPrice[i] == 6) {
nItemPrice = 119;
}
if (naChoicesToPrice[i] == 7) {
nItemPrice = 899;
}
if (naChoicesToPrice[i] == 8) {
nItemPrice = 299;
}
if (naChoicesToPrice[i] == 9) {
nItemPrice = 399;
}
}
nTotalPrice += nItemPrice;
} //end of for loop
return nTotalPrice;
}
Right now my code is this
import java.text.*;
import java.util.Scanner;
public class Homework6_EvenOdd
{
public static void main(String[] args)
{
//Varaiable declaration
int even=50;
int odd=51;
//Loop logic for even
System.out.print("Your even numbers are "+even+", ");
while (even <= 99)
{
even += 2;
System.out.print(even + ", " );
}
System.out.println ();
//Loop logic for odd
System.out.print ("Your odd numbers are "+(odd)+", ");
while (odd + 1 <= 99)
{
odd += 2;
System.out.print(odd + ", " );
}
}
}
I can't figure out how to do this with only one loop.
I don't even know where to start. I can't figure out how I would get the even and odd numbers to print on separate lines if there is only one loop?
Here is variant which produces exact copy of your current output:
public class Homework6_EvenOdd {
public static void main(final String[] args) {
final StringBuilder even = new StringBuilder();
final StringBuilder odd = new StringBuilder();
for (int i = 50; i <= 100; i++) {
if ((i & 1) == 0) {
even.append(i + ", ");
} else {
odd.append(i + ", ");
}
}
System.out.println("Your even numbers are " + even.toString());
System.out.println("Your odd numbers are " + odd.toString());
}
}
import java.text.*;
import java.util.Scanner;
public class Homework6_EvenOdd
{
public static void main(String[] args){
//Varaiable declaration
int even=50;
int odd=51;
//Loop logic for even
System.out.print("Your even numbers are "+even+", ");
while (even <= 99 || odd + 1 <= 99){
if (even <= 99) {
even += 2;
System.out.print(even + ", " );
}
System.out.println();
if (odd + 1 <= 99) {
odd += 2;
System.out.print(odd + ", " );
}
}
}
Though I have to say this code is not much better. There are much better ways to figure out if a number is even or odd (hint modulo).
You can collect each of odd and even numbers with List.
After that you can print them.
ArrayList<String> odds = new ArrayList<>();
ArrayList<String> evens = new ArrayList<>();
for (int i = 50; i < 100; i++) {
if (i % 2 == 0) {
evens.add(String.valueOf(i));
} else {
odds.add(String.valueOf(i));
}
}
System.out.println("Your even numbers are: " + String.join(", ", evens));
System.out.println("Your odd numbers are: " + String.join(", ", odds));
Note: String.join() is for Java 8 or later.