Bowling Lab: if-else Ladder - if-statement

I want to create a lab that can keep track of bowling scores. The input value has to be between 0-10. If the number differs, I want to display "Invalid". However, in my code, if I make consecutive errors, my program won't detect numbers out of the range as "Invalid". How can I code so that the program will make me try again until I put in a possible value?
import javax.swing.JOptionPane;
import java.io.*;
public class Driver14
{
public static void main(String[] args)
{
int totalScore, frame, ball;
totalScore = 0;
frame = 1;
ball = 1;
JOptionPane.showMessageDialog(null,"Welcome to Computer Science Bowling!");
while(frame<11){
int score1 = Integer.parseInt(
JOptionPane.showInputDialog("Score " + totalScore + "\n" + "Frame " + frame + ", Ball " + ball));
if(0<=score1 && score1<11){
totalScore = totalScore + score1;
ball++;
}
else{
score1 = Integer.parseInt(
JOptionPane.showInputDialog("Invalid!\n" + "Score " + totalScore + "\n" + "Frame " + frame + ", Ball " + ball));
totalScore = totalScore + score1;
ball++;
}
int score2 = Integer.parseInt(
JOptionPane.showInputDialog("Score " + totalScore + "\n" + "Frame " + frame + ", Ball " + ball));
if(0<=score2 && score2<11){
totalScore = totalScore + score2;
ball++;
}
else{
score2 = Integer.parseInt(
JOptionPane.showInputDialog("Invalid!\n" + "Score " + totalScore + "\n" + "Frame " + frame + ", Ball " + ball));
totalScore = totalScore + score2;
ball++;
}
frame++;
ball = 1;
}
JOptionPane.showMessageDialog(null,"Finished bowling!\nScore "+ totalScore);
}
}

Generaly you may use this pattern:
public static String askUserForInpute(String message){
String input = null;
try {
input = JOptionPane.showInputDialog(message);
if(/*anyLogic*/) // OR any method that throws exception for instance Integer.parseInt(input)
throw new Exception("YOUR MESSAGE");
} catch (Exception e) {
//ANY INFO YOU WANT
output = askUserForInpute(message);
}
return input;
}
You ask user for input and if input is not right you explicitly or implicitly(by a method) throw an exception then catch it and invoke same method again. This is one of possibilites.

Related

how do I get the change of a number

I cannot get the method to output the last lines, help?
Tried the nested if statments, for and do whiles, while is my new default
double cashpay = 0.00;
int doll = 0;
double quart = 0.0;
double dime = 0.0;
double nic = 0.0;
double penn = 0.0;
int c = 0;
cout << "Please input a number less than 5.00: ";
cin >> cashpay;
if (cashpay <= 5.00) {
while (c >= 0) {
while (c / 1 != 0) {
doll += 1;
c -= 1;
}
while (c / .25 != 0) {
quart += .25;
c -= .25;
}
while (c / .1 != 0) {
dime += .1;
c -= .1;
}
while (c / .05 != 0) {
nic += .05;
c -= .05;
}
while (c / .01 != 0) {
penn += 0.01;
c -= .01;
}
}
cout << " " << endl;
cout << doll << " dollars, ";
cout << quart << " quarters, ";
cout << dime << " dimes, ";
cout << nic << " nickles, and ";
cout << penn << " pennies " << endl;
} else {
cout << "Error. Please enter a number under 5.00" << endl;
}
only gives either the input and then possibly the greater than line, no more/less
In general, this problem is solved in the following pseudo-code:
Let there be four vars of unsigned int: quart(0), dime(0), nick(0), penn(0);
While THE AMOUNT OF CHANGE REMAINING is greater than $.00:
Select the largest value ($.25) or ($.10) or ($.05) or ($.01) that is NOT GREATER than the AMOUNT OF CHANGE REMAINING;
Increment quart or nick or dime or penn as above;
Subtract the selected value from THE AMOUNT OF CHANGE REMAINING;
Return {quart, dime, nick, penn}.

A puzzle on an beginner's program

I wrote this dumb little program after watching about an hour of C++ tutorial. It is garbage, but it produced a really weird error that a few software engineers haven't been able to solve, so now it's interesting to us.
It is supposed to spit out binomials and trinomials, and then give the derivative for the trinomials. The dollar signs are there to help me copypasta into LaTeX.
EDIT: The exact error in the output is it's posting:
"inear equations do you need?-12x+8$"
instead of
"Derivative= "
Thanks for the comment.
A /highfive for anyone who figures out why the output is so weird.
The output:
How many sets of 3 linear equations do you need?
2
How many sets of 3 quadratics do you need?
2
12x-3
-3x+12
-5x-9
15x-5
-5x+15
-4x-2
$8x^2-15x-6$
inear equations do you need?16x-15$
$-15x^2-6x+8$
inear equations do you need?-30x-6$
$-6x^28x-15$
inear equations do you need?-12x+8$
$2x^2-13x-2$
inear equations do you need?4x-13$
$-13x^2-2x+2$
inear equations do you need?-26x-2$
$-2x^22x-13$
inear equations do you need?-4x+2$
$11x^2-3x-13$
inear equations do you need?22x-3$
$-3x^2-13x+11$
inear equations do you need?-6x-13$
$-13x^211x-3$
inear equations do you need?-26x+11$
Press any key to continue . . .
The Code:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
/*Simple Function maker*/
using namespace std;
void polynomial(string numberOfPolys)
{
/*AX^2+BX+C format*/
for (int i = 0; i <= (std::stoi(numberOfPolys, 0)); i++) {
int a = (rand() % 15) + 1;
int b = -1 * ((rand() % 15) + 1);
int c = -1 * ((rand() % 15) + 1);
int d = -1 * ((rand() % 15) + 1);
string problemWriter = '$' + to_string(a) + 'x' + '^' + '2' + to_string(b) + 'x' + to_string(c) + '$';
string problemWriter2 = '$' + to_string(b) + 'x' + '^' + '2' + to_string(c) + 'x' + '+' + to_string(a) + '$';
string problemWriter3 = '$' + to_string(c) + 'x' + '^' + '2' + to_string(a) + 'x' + to_string(b) + '$';
string answerWriter = "Derivative= " + '$' + to_string(a * 2) + 'x' + to_string(b) + '$';
string answerWriter2 = "Derivative= " + '$' + to_string(b * 2) + 'x' + to_string(c) + '$';
string answerWriter3 = "Derivative= " + '$' + to_string(c * 2) + 'x' + '+' + to_string(a) + '$';
cout << problemWriter << endl;
cout << answerWriter << endl;
cout << problemWriter2 << endl;
cout << answerWriter2 << endl;
cout << problemWriter3 << endl;
cout << answerWriter3 << endl;
}
}
int main()
{ /*MX+B format*/
string input;
string polys;
cout << "How many sets of 3 linear equations do you need?" << endl;
getline(cin, input);
cout << "How many sets of 3 quadratics do you need?" << endl;
getline(cin, polys);
for (int i = 0; i < (std::stoi(input, 0)); i++) {
int f = (rand() % 15) + 1;
int g = -1 * ((rand() % 15) + 1);
int h = -1 * ((rand() % 15) + 1);
int k = -1 * (rand() % 15) + 1;
string problemLWriter = to_string(f) + 'x' + to_string(g);
string problemLWriter2 = to_string(g) + 'x' + '+' + to_string(f);
string problemLWriter3 = to_string(h) + 'x' + to_string(k);
cout << problemLWriter << endl;
cout << problemLWriter2 << endl;
cout << problemLWriter3 << endl;
}
polynomial(polys);
return 0;
}
The problem is with the lines when you create the answerWriter strings:
string answerWriter = "Derivative= " + '$' + to_string(a * 2) + 'x' + to_string(b) + '$';
"Derivative= " is a character array, not a string. You cannot concatenate characters to it.
Change it to this:
string answerWriter = string("Derivative")+ '$' + to_string(a * 2) + 'x' + to_string(b) + '$';

Formatting the output of a C++ program

I have already written most of the code for the problem and it works. I'm just unsure of how to format the output.
Problem : Design and develop a C++ program for Calculating e(n) when delta <= 0.000001
e(n-1) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n-1)!
e(n) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n)!
delta = e(n) – e(n-1)
You do not have any input to the program. Your output should be something like this:
N = 2 e(1) = 2 e(2) = 2.5 delta = 0.5
N = 3 e(2) = 2.5 e(3) = 2.565 delta = 0.065
#include <iostream>
using namespace std;
//3! = 3 * 2!
//2! = 2 * 1!
//1! = 1
int factorial(int number)
{
//if number is <= 1, return 1
if (number <= 1)
{
return 1;
}
// otherwise multiply number by factorial(number - 1)
else
{
//otherwise multiply number by factorial(number - 1) and return it
int temp = number * factorial(number - 1);
cout << "factorial of " << number << " = " << temp << endl;
return temp;
}
}
double sumOfFactorials(int n)
{
double sum = 0;
//loop from 1..n, adding the factorial division to a sum
for (int i = 1; i <= n; i++)
{
double dividedValue = 1.00000 / factorial(i);
cout << fixed;
sum = sum + dividedValue;
}
return sum;
}
/**
* Compute the sum of 1 + ... + 1/(n!)
* input number: 1
* output number: 1 + ... + 1/(input!)
*/
double e(int n)
{
double value = 1 + sumOfFactorials(n);
return value;
}
int main()
{
cout << "e:" << e(3) << endl; // 1 + sumOfFactorials(3)
cout << "sumOfFactorials: " << sumOfFactorials(3) << endl; //0 + 1/1! + 1/2! + 1/3!
}
You have the right code, All you need is to format the output. Just modify the main() method. here is a snippet you can try.
NOTE : There is an error in the precision of the answer, I think you can correct it.
PS : Please uncomment your debugging cout lines.
int main()
{
for(int i = 2; i<4; i++){
double en_1 = e(i-1);
double en = e(i);
double delta = en - en_1;
cout << "N = "<<i;
cout << " e("<< (i-1) <<") = " << en_1;
cout << " e("<< (i) <<") = " << en;
cout << "delta = " << delta;
cout << "\n";
}
}

C++ for loop crashes halfway through

I've just started learning about C++ and I'm currently stuck with this for loop that crashes everytime I execute it (it's part of a larger code)
void placeItem()
{
int settler = 20, castle = 5, tower = 10, mine = 10, E = 100;
int player1Settler = 0, player1Castle = 0, player1Tower = 0, player1Mine = 0;
int player2Settler = 0, player2Castle = 0, player2Tower = 0, player2Mine = 0;
int dice, x, y;
currentBoardStatus();
cout << "Player " << playerTurn(1 || 2) << " starts first." << endl;
for (int game = 1; game <= 46; game++)
{
system("CLS");
cout << "Turn #" << game << endl;
dice = rand() % 6 + 1;
x = rand() % 10 + 1;
y = rand() % 10 + 1;
cout << "Dice number: " << dice << endl;
if (dice < 4 && settler > 0)
{
cout << "Settler placed on [" << x << "] [" << y << "]" << endl;
gameBoard(x, y) = "S";
settler = settler--;
if (playerTurn(1))
{
player1Settler = player1Settler + 1;
}
else
{
player2Settler = player2Settler + 1;
}
currentBoardStatus();
}
else if (dice = 4 && castle > 0)
{
cout << "Castle placed on [" << x << "] [" << y << "]" << endl;
gameBoard(x, y) = "C";
castle = castle--;
if (playerTurn(1))
{
player1Castle = player1Castle + 1;
}
else
{
player2Castle = player2Castle + 1;
}
currentBoardStatus();
}
else if (dice = 5 && tower > 0)
{
cout << "Tower placed on [" << x << "] [" << y << "]" << endl;
gameBoard(x, y) = "T";
tower = tower--;
if (playerTurn(1))
{
player1Tower = player1Tower + 1;
}
else
{
player2Tower = player2Tower + 1;
}
currentBoardStatus();
}
else if (dice = 6 && mine > 0)
{
cout << "Mine placed on [" << x << "] [" << y << "]" << endl;
gameBoard(x, y) = "M";
mine = mine--;
if (playerTurn(1))
{
player1Mine = player1Mine + 1;
}
else
{
player2Mine = player2Mine + 1;
}
currentBoardStatus();
}
else
{
cout << "Player skips his/her turn." << endl;
}
nextTurn();
//currentBoardStatus();
system("pause");
}
}
As soon as the loop goes to 16, the entire console application stops responding, and stops there, only letting me exit.
Your code crashes because of
string gameBoard(int i, int j)
{
string arr[10][10];
return arr[i][j];
}
AND
x = rand() % 10 + 1;
y = rand() % 10 + 1;
x and y will have a value between 1 and 10, but the size of arr is 10 and its maximum valid index is 9. Therefore if x or y is 10 (or both), they'll access undefined memory.
Aside from this, there are many flaws with your code like:
dice = 4 when wanting to compare the value (which actually assigns the value 4 to dice as #KeithSmith pointed out)
The fact that you create string arr in int main() and never use it, but declare another string arr inside string gameBoard() and then return an index from it (which is undefined)

C++: Calculate probability percentage during each iteration

Can't seem to get this to work. The idea is to calculate the percentage of heads and tails after each count, accumulating after each iteration. Except I keep getting nan% for my calculations. Anybody see what I'm doing wrong?
void flipCoin(time_t seconds, int flipCount){
vector<int> flips;
float headCount = 0;
float tailCount = 0;
double headProbability = double((headCount/(headCount + tailCount))*100);
double tailProbability = double((tailCount/(headCount + tailCount))*100);
for (int i=0; i < flipCount; i++) {
int flip = rand() % (HEADS - TAILS + 1) + TAILS;
flips.push_back(flip);
if (flips[i] == 1) {
tailCount++;
cout << "Tail Percent: " << tailProbability << "%" << endl;
}else{
headCount++;
cout << "Head Percent: " << headProbability << "%" << endl;
}
}
}
You want to do this
void flipCoin(time_t seconds, int flipCount){
vector<int> flips;
float headCount = 0;
float tailCount = 0;
double headProbability = 0;
double tailProbability = 0;
for (int i=0; i < flipCount; i++) {
int flip = rand() % (HEADS - TAILS + 1) + TAILS;
flips.push_back(flip);
if (flips[i] == 1) {
tailCount++;
tailProbability = double((tailCount/(headCount + tailCount))*100);
cout << "Tail Percent: " << tailProbability << "%" << endl;
}else{
headCount++;
headProbability = double((headCount/(headCount + tailCount))*100);
cout << "Head Percent: " << headProbability << "%" << endl;
}
}
}
Also, if all you want to do is print the percentages, you dont need tailProbability or headProbablity. You can directly print the calculations.
EDIT : You can also replace headCount + tailCount with i+1 . But that could cause problems if you change the function later on.
Your problem lies in the fact that you only ever calculate headProbability and tailProbability once - and when you do calculate them, it will evaluate to 0 / 0.
float headCount = 0;
float tailCount = 0;
// Both are 0, end up as 0/0
double headProbability = double((headCount/(headCount + tailCount))*100);
double tailProbability = double((tailCount/(headCount + tailCount))*100);
//Never recalculated in the loop
To fix this, simply define them as 0 initially, and then recalculate them in the loop. You also don't seem to need a vector here, as you only need to keep track of the count, not the result of every flip:
double headProbability = 0;
double tailProbability = 0;
for(int i = 0; i < flipCount; ++i) {
int flip = rand() % (HEAS - TAIL + 1) + TAILS; //This could be simplified
if(flip == 1) {
++tailCount;
//Recalculate tailProbability
} else {
//Etc...
}
}
nan means Not a number. You got it because you divide by 0.
Your code calcul probabilities just one time, before any flip coin.
You need to put calculs in the loop for recalculate probabilities after each iteration.
void flipCoin(time_t seconds, int flipCount){
vector<int> flips;
float headCount = 0;
float tailCount = 0;
double headProbability;
double tailProbability;
for (int i=0; i < flipCount; i++) {
int flip = rand() % (HEADS - TAILS + 1) + TAILS;
flips.push_back(flip);
headProbability = double((headCount/(headCount + tailCount))*100);
tailProbability = double((tailCount/(headCount + tailCount))*100);
if (flips[i] == 1) {
tailCount++;
cout << "Tail Percent: " << tailProbability << "%" << endl;
}else{
headCount++;
cout << "Head Percent: " << headProbability << "%" << endl;
}
}
}