Trigonometry Calculator - Output Of If / Else Statements
Feb 10, 2015
Here is my code. Basically a trigonometry calculator (I hope).
import java.util.Scanner;
public class first {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
double hy;
System.out.println("Please enter length of hypotenuse:");
hy = in.nextDouble();
double op;
[Code] ....
My input:
Please enter length of hypotenuse:
20
Please enter length of opposite:
10
Please enter length of adjacent:
15
Which value would you like to calculate?
(sinA, cosB or tanC)
sinA
Please enter one of the options.
It runs and everything is fine, just that the if statement seems to get skipped over and direct straight to the else and I'm not sure why.
View Replies
ADVERTISEMENT
Feb 12, 2014
I am new to java and I have this assignment that I started but I am now stuck . The instructions are:
Create an ElapsedTimeCalculator class that computes the amount of time that passes between a starting time and an ending time, in military format.
For example, suppose the two times are 1445 and 1730. Then the program output should look something like this:
Start time:1445
End time: 1730
Exactly 2 hour(s) and 45 minute(s) have passed.
Total elapsed time in minutes:165
Total elapsed time in hours:2.75
ElapsedTimeCalculator Class Specifications:
1.Your class will have a constructor that takes two parameters: the starting time and the ending time in military format
2.Your class will also have these methods:
-Get method to return the starting and ending times
-Set method that resets the starting and ending times to values passed as parameters
-a method that returns the hour portion of the elapsed time
-a method that returns the minute portion of the elapsed time
-a method that returns the total elapsed time in minutes
-a method that returns the total elapsed time in hours
Now here below you can see what I have so far...
public class ElapsedTimeCalculator {
private int startTime, endTime;
private int hours;
private int minutes;
private int seconds;
//constructor
ElapsedTimeCalculator(int start, int end)
[Code] ....
I don't have any errors so far, I am more stuck on how to begin a method that returns the hour, minute, etc.. (the third bullet).
View Replies
View Related
Nov 11, 2014
I am stuck on one of the projects: Area Calculator
I am able to code an area calc that works, but am unsure how to move all the input/output to main like the project wants. here is a piece of my code so far:
public static void main( String[] args )
{
Scanner kb = new Scanner(System.in);
int base = 0, height = 0, width = 0, radius = 0, choice;
System.out.println( "-=-=-=-=-=-=-=-=-=-=-" );
System.out.println( "1. Triangle" );
System.out.println( "2. Rectangle" );
System.out.println( "3. Square" );
System.out.println( "4. Circle" );
System.out.print( "Pick a shape: " );
[Code] ....
I have the same thing for rectangle, square, and circle (of course with the correct formulas) and the program works perfect, but the assignment is still wrong until I can move the input/output to main. what do I do?
View Replies
View Related
Sep 11, 2014
I am in the process of creating a calculator GUI that calculates different answers based on inputs two main comboboxes and numbers in the appropriate textfields. The first one allows the user to choose from 18 different materials, while the second has the user choose between two different shapes. In a brief word explanation, here's how it's set up:
User chooses material.
User chooses shape.
User types in appropriate values.
'Calculate' button clicked.
If shape = rectangle, execute rectangle calculation.
Else if shape = cylinder, execute cylinder calculation.
Everything works just fine with zero errors on all 18 materials and all kinds of decimal numbers when the second shape is selected. So the math and layout is solid. However, when the first shape is selected, it returns a $0.00 answer regardless of the input values (still no red-line errors). In efforts to troubleshoot, when I have /* Cylinder section */, the rectangle section works to a 'T'. This, I believe is caused by poor formatting in the syntax of the 'if' 'else if' in regards to the shape combobox.
//If 'Rectangle' is selected:
if(shapeDropDown.getSelectedIndex()==1) {
//6061
if(materialDropDown.getSelectedIndex()==0) {
String msg0 = "The price is: $"
+ currencyFormat.format((0.098*(number2*number3*number4)*3.06));
totalPrice.setText(msg0);
[code]....
View Replies
View Related
Dec 19, 2014
What I'm trying to do below is to say if (adultTickets > 0) I want to bypass the studentOAP tickets question and go straight to the question about dinner. But if (adultTickets ==0) I want to go to the studentOAP question and then if the (studentOAPTickets >0) to go to the question about dinner. But if the (studentOAPTickets ==0) I want to go straight to the question about the contact number.
System.out.print("How many adult tickets do you require? ");
int adultTickets = 0;
boolean validAdultValue = false;
while (validAdultValue == false) {
if(aScanner.hasNextInt())
[Code] ....
View Replies
View Related
May 1, 2014
My initial question had to do with looping but now I'm having trouble adding certain variables.
The original thread is here: [URL] ....
If you look at the end of the code it won't recognize the "overtime" and "hourDiff". I have to use it for each level the
user chooses and am not sure how to do so. Even if I put it under the if{ statement it won't calculate. I assume it's due to it being cut off from other blocks but I'm not sure how to combine them.
My code is:
import javax.swing.JOptionPane;
public class Pay {
public static void main(String[] args) {
double salary2 = 20.00;
double salary3 = 22.00;
[Code] ....
View Replies
View Related
Oct 23, 2014
import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
//Create scanner
Scanner in = new Scanner(System.in);
//Declare variables to hold the board
[Code] ....
I need to create a while statement for random computer moves.
View Replies
View Related
Nov 2, 2014
I'm doing some revision for my OCAJ atm, & I came across this code in a mock question which takes two int arguments & simply returns the larger.
public int max(int x, int y){
if (x > y)
return x;
return y;
}
When evaluating it I thought this would be invalid code as would always return x. But it transpires I was way off & that this actually works! In playing around with it, it seems like the first return statement is treated as:
if {// this bit } & the second return is treated as: else{ //this bit}.
What baffles me though is that you can put any amount of additional statements before the second return and it continues to work, however if you put even a single statement before the first return, the whole thing falls over.
I guess my two questions are - Am I right in my discovery above ( that statements preceeding the first return will always break it)? & secondly is this a good way of coding? for readability, I would always do it as:
public int max(int x, int y){
if (x > y){
return x;
}
else{
return y;
}
}
View Replies
View Related
Oct 4, 2014
I am making a program, where the user answers 3 questions and then I add the number of correct answers in to the (int) numberofcorrect variable, then I want to print the results, and no matter how many correct, the program executes first the correct if statement, then the else statement.
Eg: I have 2 correct it will print:
"Grade B, 2 of 3 "
"You failed the test"
Why does it do that? How can I change my code so the else statement dosent print if one of the if statments is allready printed?I want to know how to not execute the else statement, if one of the if statements have allready been executed.Below is my current code for this problem:
if (numberofcorrect == 3){
System.out.println("Grade A, full score");}
if (numberofcorrect == 2){
System.out.println("Grade B, 2 of 3 ");}
if (numberofcorrect ==1) {
System.out.println("Grade C, 1 of 3");}
else {
System.out.println("You failed the test"); }
View Replies
View Related
Nov 18, 2014
I have read some on this but I'm trying to understand a code and the following part confuses me
if( thisCount == bestCount )
bestCandidates.add( candidate );
else if( thisCount > bestCount ) {
bestCount = thisCount;
bestCandidates.clear();
bestCandidates.add( candidate );
}
}
What I find confusing is this: If I am not mistaken the need for curly braces occurs when using more than one statement and if you use else statements.
So I wonder if I have missunderstood about the else statement and that you dont need curly braces around a one statement if statement that is followed by an else statement...
View Replies
View Related
May 18, 2014
I created a variable for the scanner called serena. Serena variable is equal to what the user inputs. My if statement says that if the answer the user enters is not equal to the actual answer then it is to display "wrong". It is a basic math game I am working on. NetBeans is telling me that I cannot use the scanner in an if statement?
package pkgnew;
import java.util.Scanner;
public class New{
public static void main(String args[]){
Scanner serena = new Scanner(System.in);
double fnum, snum, answer;
[Code] ....
Do I have to define Serena as whatever number the user inputs? If so, how?
View Replies
View Related
Dec 12, 2014
I am new to java and I am trying to write a program where someone has to guess the number. The correct number is 3. If they are below three. It tells them that they are too low and to guess again. If they are too high, it tells them they are too high and to guess again.
However, I am having problems once they enter a number and they get the response "The number was too low. Try again" as it lets them try again but doesn't tell them if it's right, wrong, or too high. I'm not sure what piece of code I am missing. Here is what I have so far:
import java.util.Scanner;
public class Guessthenumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 1-10.");
double value = input.nextDouble();
if(value == 3)
[Code] .....
View Replies
View Related
Jun 11, 2014
I have a small problem with my code that I can't figure out how to make it work the way it is supposed to. The code is supposed to be a game where a user has to guess numbers between 1-1000. The program counts how many times the user tried to guess the number and it displays a certain message if the guess number is less than 10, more than 10 or 10. I was able to write the code using loops. However, the messages will not always get printed on to the screen. The code seems to work fine except for the last part where the messages, "Either you know the secret or you got lucky", "You should be able to do better", "Aha! you know the secret!" are not always displayed like they are supposed to.
import java.util.Scanner;
public class Guess1 {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
Scanner input = new Scanner(System.in);
int guess;
int replay;
int test;
test=1;
replay=1;
int count=0;
[code]....
View Replies
View Related
Mar 30, 2014
I'm having this where i'm trying to return a JPanel with tempPictures but only if they aren't already filled with "actual" pictures. However this causes problems because your never shore that the if statement will execute. I tried adding an else statement but i cant return null i must return a JPanel;
private JPanel buildTopShelf() {
if(myMediaHandler.mediaList.size() < 6) {
JPanel mediaPanel = new JPanel();
mediaPanel.setOpaque(false);
mediaPanel.setLayout(new GridLayout(1,6,22,0));
mediaPanel.setBounds(90, 14, 1020, 210);
[Code] ....
View Replies
View Related
Mar 18, 2014
I am familiar with Java but new to JSP. I have a Java Servlet app where user actions are recorded in a SQL Server database amd I now need to quickly put together a JSP front end application to view user actions. I want two drop down boxes to filter the results that will be displayed in a list box. What I need is the first drop down list box to show unique user names that have logged in. I can interrogate the database with the following SQL;
"SELECT DISTINCT(USER_ID) FROM AUDIT_MESSAGE"
Then when a user is selected from the first drop down list box (perhaps some sort of on change event) a second drop down list box shows the logins times of the selected user. Again I can interrogate the database with the following SQL;
SELECT SESSION_ID, EventTIME FROM dbo.AUDIT_MESSAGE
WHERE OPERATION = 'loginResponse' AND RESULTS = 'OK'
AND USER_ID = 'firstdropdownlistselection'
Then finally when a login time is selected in the second drop down list box all events for the selected user while logged in with that login time are displayed in the list box.
View Replies
View Related
May 9, 2014
write a program that will ask the user to enter five numbers.using If statements if each number entered in greater than zero
import.java.util.Scanner;
public class Java3 {
public static void main(String[] args) {
function addNumbers(n1, n2, n3, n4, n5){
var finalNumber = 0;
[Code] ....
addNumbers(1, 2, 3, 4, 5,);
View Replies
View Related
Apr 22, 2015
What I am attempting to program is a simple Boss battle. I would like the user to have 2 options (for now): Run, or Attack. I got the portion completed and working, but once I tried to implement the Run feature (the way that it's supposed to work is you can either attack OR run), both Attack and Run will happen. Also, for some reason, the running always fails (it will always return the else statement, then move onto the attack.) Here's my code:
import java.util.*;
public class AdvancedBossBattle {
public static void main (String[] args) {
Scanner scan = new Scanner (System.in);
Random gen = new Random();
int bosshp, bossdmg, playerhp, playerdmg, runChance;
String answer;
bosshp = 100;
[Code] ....
View Replies
View Related
Oct 4, 2014
I'm trying to create a simple java math question quiz using random operators, but keep sinking myself into deeper despair. The numbers must range from 0-9 and given an operator: +,-,/,*,%. Can't create a new method or use Case statements. The code isn't finished but don't want to make it any worse.
package marco;
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
System.out.println("How many questions do you want?");
[code]...
View Replies
View Related
May 5, 2014
So I'm pretty sure this is correct, as it follows most examples I can find online, but I keep getting an error that my return variable cannot be resolved. The error is on the return conn; statement. It says conn cannot be resolved. If I place it above within the try block it allows it but then I receive an error saying the method getDBConnection must return type Connection.
import java.sql.*;
public Connection getDBConnection() {
try {
Class.forName("org.sqlite.JDBC");
String path = "jdbc:sqlite::resource:project.db";
[Code] .....
I don't want to create this method. Basically I want to connect to the database in the main program, but I do want methods that can access the DB too. But however I place it, it doesn't let me touch any of the DB variables outside of the Try block.
View Replies
View Related
Apr 1, 2014
So I have one set of If Else If statements. My program calculates just the first comboBox. It is retrieving all the values from the other comboBoxes but I do not understand where to place the other If statement structure so I can calculate the other values I have set for the other objects. I would not like to use a different class for each and I know I have my calculations done right below my current if statement. Could it be left there and where shall I place the other if statements so they get read by my arithmetic sequence?
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource() ;
int deckSiz = (int) Decks.getSelectedIndex() ;
int wheelSiz = (int)Wheels.getSelectedIndex();
[code]....
View Replies
View Related
Feb 19, 2015
How I am supposed to set up the units for my program, and how to correctly display them in the console. Here is a description of my program.
To display the nonzero denominations only, using singular words for single units such as 1 dollar and 1 penny, and plural words for more than one unit such as 2 dollars and 3 pennies. You must use nested if statement when displaying the output.
Sample run:
Enter an amount in double, for example 11.56: 1.56
Your amount 1.56 consists of
1 dollar
2 quarters
1 nickel
1 penny
View Replies
View Related
Apr 1, 2014
I have the following Output
_G7120+1#=K,
_G7132+_G7133#=_G7120,
_G7144+_G7145#=_G7132,
_G7156+_G7157#=_G7144,
_G7168*Z#=_G7156,
_G7180*Z#=_G7168,
_G7192*Z#=_G7180,
_G7204*Y#=_G7192,
_G7192, in 10..15 / 16
X*Y#=_G7204,
X+Y#=_G7133,
_G7145+X#=Z1_a,
Y in 1..15,
Z/Y#=_G7157,
__X in 1..15 / 17 / 20.
From this, I need to extract the statements of variables that do not start with _G . I mean, I need to extract, Y in 1..15 , __X in 1..15 /17/20 but not _G7145 in 10..15 / 16.
I am using regular Expression for this as [^_G]^[A-Za-z0-9_]+ in|ins [-9 -9]..[-9-9] [/[-9-9]..[-9-9]]+
View Replies
View Related
Mar 8, 2014
Combining switch statements into if...else decisions? I'm basically trying to teach myself java and am at the point where I have to combine two user inputted values into if...else statements, only I don't really grasp how to do so. (This stuff is soooo addictive.) I'm trying to let the user input the type of residence they have, how many hours they are usually home, and then recommend a pet based on that. I just don't get how to input both selections they make in if...then statements. I get a bunch of errors as soon as I start the if...else part.
import java.util.Scanner;
public class PetAdvice
{
public static void main(String[] args)
{
int houseType;
int hourHome;
[Code] ....
View Replies
View Related
Mar 30, 2014
This is what I'm trying to do;
Java Code:
import java.util.Scanner;
class test{
public static void main ( String[] args ) {
Scanner scan = new Scanner ( System.in );
int choice = scan.nextInt();
[Code] ....
How is this doable?
View Replies
View Related
Mar 20, 2014
I am trying to Extract the ranges of Variables from a Text File. I extracted lines of the forms X in 1..10 Y in 12..50 Z in 0..19 / 66/ 95..100 Where X in 1 ..10 states that X takes values from set 1 to 10 Similarly for Y and for Z its a Union of different ranges of the values (0 to 19, union 66,union 95 to 100)
I want to Map these Variables to their respective sets using Hashmap where Key is Variable name and value will be a Set. My Hashmap Signature is HashMap> hm=new HashMap>();
Java Code:
while((line=br.readLine())!=null) {
Matt=Patt.matcher(line);
if(Matt.find()) {
//System.out.println(line);
String []s=line.split(" ");
[Code] .....
I am stuck at extracting the variables ranges from these plain strings.
View Replies
View Related
Sep 16, 2014
I am trying to code a program that orders 5 random numbers from high to low with the basic coding i know (im starting to learn theory of methods... so you can imagine) When i run the code i cant get all 5 numbers ordered but my logic says the code is right although it's pretty confusing.
I know you could code in a simpler way but first i wanna get it as it is right now. When i debug (on my own way cause i dont know how to actually use it) shows line 72 with yellow color.
public class NuevaCalculadora {
import java.util.Scanner;
public static void main(String[] args) {
[Code]....
View Replies
View Related