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...
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; } }
At this moment in time my program compiles and runs as I want it to, but when I look at my code I see that my While Loops braces are placed inside my Try Block. When I move these braces outside of the Try Block, next to the WhileLoop, the program doesn't run like I want it to.
Likewise, when I place the While(answerIsCorrect) inside the Try Block, it doesn't work like I want it to either.
Also, my problem is on Lines 17 and 18.
import javax.swing.*; import java.util.Random; public class SwingInputExample { public static void main(String args[]) { int firstNumber=0; int secondNumber=0; int correctAnswer=0; String studentGuess = null;
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);
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())
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;
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.
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"); }
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?
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)
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;
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;
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.
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;
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?");
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.
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.
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();
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
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]]+
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;