Scanner Cannot Be Used As Variable In If Statements?

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


ADVERTISEMENT

Switch Statements To Initialize Variable Due To Multiple Outcomes?

May 20, 2014

After this problem is fixed, my math game will run. The answer variable is supposed to be equal to the cases in the second switch statement by random but I get errors whenever I try to initialize it this way. I have been writing this program for almost 5 days now and it is finally wrapping up. Why I can't map the answer variable to the second switch statement the way I want to?

package pkgnew;
import java.util.Scanner;
import java.util.Random;
public class New {
  public static void main(String args[]) {
//Declare and construct variables
Random randomnum = new Random();
int fnum, snum, answer;

[Code] .....

View Replies View Related

Code Not Running Scanner NextLine After Using Scanner NextInt?

Feb 14, 2015

package jdbc;
import java.sql.*;
import javax.sql.*;
import java.util.*;
public class Jdbc {
public static void main(String[] args) {

[code]....

View Replies View Related

Difference In Variable Assignment Between Constructor And Variable Section

May 21, 2014

Given the case I have an object which is assigned only once. What is the difference in doing:

public class MyClass {
private MyObj obj = new MyObj("Hello world");

private MyClass(){}
//...
}

and

public class MyClass {
private MyObj obj;
private MyClass(){
obj = new MyObj("Hello world");
}
//...
}

Is there a difference in performance or usability? (Given also the case there are no static calls expected) ....

View Replies View Related

Are Terms Local Variable And Member Variable Comparable

Oct 27, 2014

The term "Local variable" is related to scope. That is a local variable is one which is defined in a certain block of code, and its scope is confined inside that block of code.And a "Member variable" is simple an instance variable.

I read in a discussion forum that when local variables are declared (example code below), their name reservation takes place in memory but they are not automatically initialized to anything. On the other hand, when member variables are declared, they are automatically initialized to null by default.

Java Code: public void myFunction () {
int [] myInt; // A local, member variable (because "static" keyword is not there) declared
} mh_sh_highlight_all('java');

So it seems that they are comparing local variables and member variables. While I think a member variable can also be be local in a block of code, isn't it?

View Replies View Related

Nested If Statements

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

While Loops Within If Else Statements?

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

Trying To Add Values Under Different If Statements

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

Tic Tac Toe Game Using While Statements

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

If Statements Without Braces

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

If Else - How To Not Execute Both Statements

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

Curly Braces In If And Else Statements

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

If Statements And User Input

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

If Statements - Printing Messages

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

Reference Variable - Create Another Variable And Set It Equal To First

Jan 11, 2015

Given a reference variable : Car c1 = new Car();

when we create another variable and set it equal to the first : Car c2 = c1;

we're pointing c2 at the same car object that c1 points to (as opposed to pointing c2 at c1, which in turn points at the car). So if we have code like,

Car c1 = new Car();
Car[] cA = {c1, c1, c1, c1};

are we doing the same? Are we creating four *new* reference variables, each of which points at the same car (again as opposed to pointing them at c1 itself)? I think so, but want to make sure I'm understanding this correctly.

View Replies View Related

Return Statements While Building A JPanel

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

JSP :: Filtering With Dropdown Lists And SQL Statements

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

If Statements - Each Number Entered In Greater Than Zero

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

Eclipse - Coding Multiple If / Else Statements

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

Can't Create A New Method Or Use Case Statements

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

Returning Object After Try-Catch Statements

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

Swing/AWT/SWT :: Else If Statements - Arithmetic Sequence

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

Correct Units And Nested If Statements

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

Regular Expressions For Range Statements

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

Combining Switch Statements To If / Else Decisions

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

For Loops Inside Of Switch Statements

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







Copyrights 2005-15 www.BigResource.com, All rights reserved