The program is suppose to have the user enter 3 sides using JOptionPane and then tell them what type of triangle it is and to calculate the area using JOptionPane.
I had the program working, but then I realized i needed to add the first if statement i have where if a,b or c is greater than the sum of the other 2 sides then it will print there is no triangle.
My problem is that when the first if statement is true than it works. But if it is not true it tells me there is no triangle and ends the program without going to the rest of the if statements.
package assignment.ii;
import javax.swing.JOptionPane;
import java.lang.*;
public class AssignmentII
{
public static void main(String[] args) {
int a = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a side of the triangle "));
int b = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a side of the triangle "));
int c = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a side of the triangle "));
double s = (.5*(a+b+c));
{
if (a>=b+c || b>=a+c || c>=a+b); {
JOptionPane.showMessageDialog(null, "There is no triangle");
System.exit(0); }
}if ((a==b) && (b==c)) {
JOptionPane.showMessageDialog(null, "The triangle is a equilateral triangle");
}else if (((a*a)+(b*b)) == (c*c)) {
JOptionPane.showMessageDialog(null, "The triangle is a right triangle");
if (a==b || b==c || c==a)
JOptionPane.showMessageDialog(null, "The triangle is a Isosceles triangle");
}else if (((a*a)+(b*b))<(c*c)){
JOptionPane.showMessageDialog(null, "The triangle is an obtuse triangle");
if (a==b || b==c || c==a)
JOptionPane.showMessageDialog(null, "The triangle is a Isosceles triangle");
}else if (((a*a)+(b*b))>(c*c)){
JOptionPane.showMessageDialog(null, "The triangle is an acute triangle");
if (a==b || b==c || c==a)
JOptionPane.showMessageDialog(null, "The triangle is a Isosceles triangle");
}
JOptionPane.showMessageDialog(null, "The area of the triangle is: " + Math.sqrt((s)*(s - a)*(s - b)*(s - c)));
}
}
You have an erroneous semi-colon that terminates that if statement.
if (a>=b+c || b>=a+c || c>=a+b); {
SHOULD BE
if (a>=b+c || b>=a+c || c>=a+b) {
JOptionPane.showMessageDialog(null, "There is no triangle");
System.exit(0); }
Related
I am trying to learn basic C++ this summer and I am struggling with this Rock, Paper, Scissors game program.
For some reason, when I run the program, it only works every other time the do-while loop iterates. So the first time the program executes correctly, then the second time the menu choices print but when the user answers, it just displays the menu again. Then it works on the 3rd iteration, but not the 4th time, and so on.
So the getUserChoice function seems to get called and executes each time, but maybe not the determineWinner function?
I have tried a lot of different changes but I cannot seem to find the bug. Any help would be greatly appreciated!
int getComputerChoice(int computerChoice)
{
//declare vars for min and max of random number
const int MIN = 1;
const int MAX = 3;
//get system time
unsigned seed = time(0);
//randomize rand
srand(seed);
// Generate random number
computerChoice = MIN + rand() % MAX;
return computerChoice;
}
int getUserChoice(int userChoice)
{
//declare constants for menu choices
const int ROCK = 1, PAPER = 2, SCISSORS = 3, QUIT = 4;
cout<<"Rock, Paper, Scissors Game\n"
<<"---------\n"
<<"1) Rock\n"
<<"2) Paper\n"
<<"3) Scissors\n"
<<"4) Quit\n\n"
<<"Enter your choice:\n";
cin>>userChoice;
//validate input
while (userChoice <1 || userChoice>4)
{
cout<<"Invalid selection. Enter 1, 2, 3, or 4:\n";
cin>>userChoice;
}
return userChoice;
}
void determineWinner(int userChoice, int computerChoice)
{
if(userChoice == 1 && computerChoice == 2)
{
cout<<"\nYou selected: ROCK\n\n"
<<"The computer selected: PAPER\n\n"
<<"Computer wins! Paper wraps rock!\n\n"
<<"*********************************\n"<<endl;
}
else if(userChoice == 1 && computerChoice == 3)
{
cout<<"\nYou selected: ROCK\n\n"
<<"The computer selected: SCISSORS\n\n"
<<"You win! Rock smashes scissors!\n\n"
<<"*********************************\n"<<endl;
}
else if(userChoice == 2 && computerChoice == 1)
{
cout<<"\nYou selected: PAPER\n\n"
<<"The computer selected: ROCK\n\n"
<<"You win! Paper wraps rock!\n\n"
<<"*********************************\n"<<endl;
}
else if(userChoice == 2 && computerChoice == 3)
{
cout<<"\nYou selected: PAPER\n\n"
<<"The computer selected: SCISSORS\n\n"
<<"Computer wins! Scissors cut paper!\n\n"
<<"*********************************\n"<<endl;
}
else if(userChoice == 3 && computerChoice == 1)
{
cout<<"\nYou selected: SCISSORS\n\n"
<<"The computer selected: ROCK\n\n"
<<"Computer wins! Rock smashes scissors!\n\n"
<<"*********************************\n"<<endl;
}
else if(userChoice == 3 && computerChoice == 2)
{
cout<<"\nYou selected: SCISSORS\n\n"
<<"The computer selected: PAPER\n\n"
<<"You win! Scissors cut paper!\n\n"
<<"*********************************\n"<<endl;
}
else
cout<<"\nTie, No winner!\n\n"
<<"*********************************\n"<<endl;
}
int main()
{
//declare vars
int userChoice, computerChoice;
do
{
//call determineWinner function
determineWinner(getUserChoice(userChoice), getComputerChoice(computerChoice));
}
while (getUserChoice(userChoice) != 4);
system ("pause");
return 0;
}
getUserChoice is getting called twice per while loop: once inside the body and once in the condition.
do
{
//call determineWinner function
determineWinner(
getUserChoice(userChoice), // Called once here...
getComputerChoice(computerChoice));
}
while (getUserChoice(userChoice) // And again here.
!= 4);
You might consider saving the return value to a variable to you can reuse it without prompting the user again:
do
{
userChoice = getUserChoice(userChoice);
//call determineWinner function
determineWinner(userChoice, getComputerChoice(computerChoice));
}
while (userChoice != 4);
Taking an intro to C++ class in University and we got this project to 'model' a tennis game.
The user will first need to enter the probability that player a will win.
Then generate a number between 1 and 100 until a player has more than 4 points and has 2 more points than the other player.
My problem is that sometimes around the 50% win rate area the output will come out as 4-4.
I am wondering why this is happening?
Any help would be greatly appreciated!!
int prob;
int scoreA = 0;
int scoreB = 0;
int randNB = 0;
srand(time(NULL));
cout <<"---------------\n"
"FAKE TENNIS!\n"
"---------------" <<endl;
cout <<"What is the chance that player \'A\' will win a point?(Enter whole #between 1 - 100): " ;
cin >> prob;
do{
if((scoreA >= 4 || scoreB >= 4) && ((scoreA - scoreB) >= 2 || (scoreB - scoreA) >= 2)) break;
randNB = rand()%100+1;
if (randNB <= prob){
cout<<"A";
scoreA++;
}
else if(randNB > prob){
cout<<"B";
scoreB++;
}
}
while((scoreA <= 3|| scoreB <= 3) && ((scoreA - scoreB) !=2 || (scoreB - scoreA) !=2 ));
cout<<"The final score is " <<scoreA <<" (A) - " << scoreB <<" (B)" <<endl;
if(scoreA > scoreB){
cout <<"A is the winner!!!";
}
else{
cout <<"B is the winner!!!";
}
return 0;
}
You've written the end-loop test twice.
Once as a positive inside the loop (correctly) and once as a negative at the end of the loop.
1) Write it only once. (The "break" will end the loop.) That is, replace the do { ... } while(...) with just while(true) { ... }
2) If you want to write it twice, check <2 rather than != 2 in the second test. The negation of x>=2 is not x!=2
I'm a student and started learning C++ recently.I was making a GPA calculator for my juniors in C++ but I'm facing an error. When I multiply a decimal with a variable, I get the same answer every time. This happens with the decimals only. Exact integers work fine.
I get the right answer if I place the value of variable "cal" in the range of and integer.Like if I place 85, I get 12 as output but when I type the value below 85, I get 3.1 every time.
Can you point out my mistake?
Here is my starting source code :
#include <iostream>
#include <string>
using namespace std;
int main()
{double cal,calh,c1;
cout<< "How many marks you obtained in calculus? \n";
cin >>cal;
cout<<"Enter the credit hours of Calculus? \n";
cin>>calh;
if (cal>85 || cal==85){c1=4*calh;}
else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}
else if (cal>75 || cal==75 || cal<80){c1=3.3*calh;}
else if (cal>70 || cal==70 || cal<75){c1=3*calh;}
else if (cal>65 || cal==65 || cal<70){c1=2.7*calh;}
else if (cal>61 || cal==61 || cal<65){c1=2.3*calh;}
else if (cal>58 || cal==58 || cal<61){c1=2*calh;}
else if (cal>55 || cal==55 || cal<58){c1=1.7*calh;}
else if (cal>50 || cal==50 || cal<55){c1=1*calh;}
else if (cal<50 || cal==49){cout<<"Sorry but you are failed in calculus.";}
cout<<"your total gpa in calculus is "<< c1<<endl;
system("pause");
return 0;
}
Think about what you wrote
else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}
This will match everything (any number is either larger than 80 or less than 85)
You want something like this instead
#include <iostream>
#include <string>
using namespace std;
int main()
{
double cal, calh, c1;
cout << "How many marks you obtained in calculus? \n";
cin >> cal;
cout << "Enter the credit hours of Calculus? \n";
cin >> calh;
if (cal >= 85) { c1 = 4 * calh; }
else if (cal >= 80) { c1 = 3.7*calh; }
else if (cal >= 75) { c1 = 3.3*calh; }
else if (cal >= 70) { c1 = 3 * calh; }
else if (cal >= 65) { c1 = 2.7*calh; }
else if (cal >= 61) { c1 = 2.3*calh; }
else if (cal >= 58) { c1 = 2 * calh; }
else if (cal >= 55) { c1 = 1.7*calh; }
else if (cal >= 50) { c1 = 1 * calh; }
else { cout << "Sorry but you are failed in calculus."; c1 = 0; }
cout << "your total gpa in calculus is " << c1 << endl;
system("pause");
return 0;
}
Let's look at your first two conditional lines:
if (cal>85 || cal==85){c1=4*calh;}
else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}
In the second one, you are entering in the condition for every possible value, as you are asking "any value that are greater than 80, but also any value that are lower than 85". So you will always have c1 = 3.7*calh, except if cal is superior to 85. That's why you are getting the same value everytime.
I think the problem is that you misunderstood the logic of the || operator. When you have several conditions in a if statement separated with a ||, it means that only one of the conditions needs to be true to enter the condition. If you want to keep this logic, remove the "==" and ">" tests and replace them with a ">=" one, and replace your || operator with &&.
Now let's look at your code again. There is some conditions you are repeating there. You already that you are entering the first else if cal is lesser than 85, so you don't need to verify it again. Then, in the end, you can replace
else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}
With:
else if(cal >=80) {c1=3.7*calh;}
Apply this trick everywhere, and you are done.
I have tried many things and i can not seem to figure out why this program will not stop the code if you select N when it prompts to try again or not.
I feel as though i had this working earlier, but i can not find any code from when it was working, and i see no reason this should not work. Can anyone help out?
#include <iostream>
using namespace std;
int main ()
{
char color[10];
char reboot, yes_no;
start:
cout << "What color is the light?\n";
cin >> color;
//if the light is Green
if (!strcmp(color, "green")) {
cout << "The light is Green, you may go ahead and drive thru the intersection.\n";
} else if (!strcmp(color, "Green")) {
cout << "The light is Green, you may go ahead and drive thru the intersection.\n";
//if the light is Yellow
} else if (!strcmp(color, "yellow")) {
cout << "The light is Yellow, safely stop at the intersection, or proceed thru.\n";
} else if (!strcmp(color, "Yellow")) {
cout << "The light is Yellow, safely stop at the intersection, or proceed thru.\n";
//if the light is Red
} else if (!strcmp(color, "red")) {
cout << "The light is Red, you need to stop.\n";
} else if (!strcmp(color, "Red")) {
cout << "The light is Red, you need to stop.\n";
}
//non recognised input
else{
cout << "\nYour input was not recognised...Would you like to restart? (Y/N)\n";
cin >> yes_no;
if(yes_no == 'Y'||'y'){
goto start;
}
}
//restart program
restart:
cout << "\nWould you like to run the program again? (Y/N)\n";
cin >> reboot;
if(reboot == 'Y'||'y'){
goto start;
}
return 0;
}
Your condition is not well formed it should be
if( (reboot == 'Y') || (reboot == 'y') )
{
goto start;
}
As it is, it always evaluates to true since 'y' evaluates to true and true || anything always gives true.
Same thing applies to yes_no check.
EDIT Since you are having trouble, I made a simple program to test it more easily, this should work as expected:
#include <iostream>
using namespace std;
int main()
{
char yes_no;
while (true)
{
cout << "Enter 'N or 'n' to quit\n";
cin >> yes_no;
if(yes_no == 'N'|| yes_no == 'n')
break;
}
return 0;
}
These 2 lines looks a bit strange
if(yes_no == 'Y'||'y')
if(reboot == 'Y'||'y')
maybe you meant below instead??
if(yes_no == 'Y' || yes_no == 'y')
if(reboot == 'Y' || reboot == 'y')
Starting with the real reason your code doesn't work - operator precedence and associativity:
reboot == 'Y'||'y'
always returns true, since it's parsed as (reboot=='Y')||'y'. If you want to test if reboot is equal one of the two chars, test it like that: reboot=='Y'||reboot=='y'.
That should fix your code. Although here are some advices:
Don't use the goto statement. You can loop your code using loops (while, for or do while).
If you're using C++, use std::string for storing text, you can then use text=="some Text" instead of testing the output of strcmp.
For future reference on operator precedence, you can always check Wikipedia.
I attempted to code a code a simple text adventure game from scratch as a programming exercise and got surprising results. Here is the complete code:
//Twisty Passages All Alike.
//An adventure game designed as a practice exercise.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "\t\tTwisty Passages, All Alike!\n";
cout << "\tA text adventure by Jellypox Studios.\n";
//INVENTORY INDEX NUMBERS:
//0. note
//1. hammer
//2.
//ROOM NUMBERS:
//0. living room
//1. storeroom
//Setting up the current room.
int ALL_ITEMS = 10;
string inventory[ALL_ITEMS];
int currentRoom = 0;
string input = "DEFAULT";
//Room 0: living room.
bool haveNote = false;
bool haveHammer = false;
//Room descriptions
if (currentRoom == 0)
{
cout << "You are in the living room.\nThere are doors to the south and west and a staircase to the north.\nYou can see: a table, a cat, a fireplace.\n\n";
}
else if (currentRoom == 1)
{
cout << "You are in the storeroom.\nThe room is a jumbled mass of cupboards, hanging sausages, left-out scraps of food and cockroaches.\nThe only thing of interest here is a large chest in the corner.";
}
//THE LIVING ROOM
while (currentRoom == 0)
{
cin >> input;
//THE TABLE
if (input == "look table" || "look at table")
{
cout << "You see: some bones and scraps";
if (haveHammer = false)
{
cout << ", a hammer";
}
if (haveNote == false)
{
cout << ", a note";
}
cout << ".\n\n";
}
else if (input == "look scraps" || "look at scraps" || "look bones" || "look at bones")
{
cout << "What a mess!\n\n";
}
else if (input == "look note" || "look at note" || "read note")
{
if (haveNote == false)
{
cout << "Pick it up first!\n\n";
}
else
{
cout << "It reads: \"Gone hunting. Will be back soon.\"";
}
}
else if (input == "get note" || "take note" || "pick up note")
{
if (haveNote == false)
{
cout << "Got the note.";
inventory[0] = "note";
haveNote = true;
}
else
{
cout << "You already have the note!\n\n";
}
}
else if (input == "look hammer" || "look at hammer")
{
cout << "It's just an ordinary hammer.\n\n";
}
else if (input == "get hammer" || "take hammer" || "pick up hammer")
{
if (haveHammer == false)
{
cout << "Got the hammer.\n\n";
inventory[1] = "hammer";
haveHammer = true;
}
else
{
cout << "You already have the hammer!\n\n";
}
}
//ELSWHERE IN THE ROOM
else if (input == "look cat" || "look at cat")
{
cout << "It stares up at you irritably.\n\n";
}
else if (input == "look fireplace" || "look at fireplace")
{
cout << "A flickering fire warms the house.\n\n";
}
else if (input == "south" || "go south")
{
//CODE TO MAKE THE DOOR UNLOCKABLE GOES HERE!
cout << "The door is locked.\n\n";
}
else if (input == "west" || "go west")
{
currentRoom = 1;
}
else if (input == "north" || "go north" || "upstairs" || "go upstairs")
{
currentRoom = 2;
}
else
{
cout << "Say what?";
}
}
return 0;
}
I tried using a while loop for the input/output system so that if you type "look at table," it gives you a description of the table, etc. but instead, it does this:
look at table
You see: some bones and scraps, a note.
You see: some bones and scraps, a note.
You see: some bones and scraps, a note.
get note
You see: some bones and scraps, a note.
You see: some bones and scraps, a note.
get hammer
You see: some bones and scraps, a note.
You see: some bones and scraps, a note.
go west
You see: some bones and scraps, a note.
You see: some bones and scraps, a note.
What all did I get wrong?
there are typos in this code, for example
if (haveHammer = false)
which should have double `=' I believe. The compile won't yell at you but the logic is not what you want.
there are non C++ codes in this code,
if (input == "hall..." || "ass" )
In C++, we don't use that although it is valid. It should be
if (input =="hall....") || input == "bbbb")
Since I think you won't just want to compare the memory address of these string literals.
(I did not read the code carefully, thanks for the comments.
It prints "You see: some bones..." once for every word in your input. If you type "the quick brown fox jumped over the lazy dogs" it will probably print "You see: ..." 9 times. So it looks like your "cin >> input" is breaking up your input string into tokens. You have to figure out how to get it to read a whole line and give it to you as one string; I'm so rusty at C++ that I can't remember. :-)
Also, you wrote: if (input == "look table" || "look at table")
The problem here is that "look at table" is always true, so the expression is always true. You probably want: if (input == "look table" || input == "look at table")