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
ADVERTISEMENT
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
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
Sep 25, 2014
Ok, so I've seen alot of things online about writing switch code, but I can't find any involving user input, let alone multiple input scanners.
The goal is I let the user put in two different integers and it will decide based on both of the integers which of the 15 possible results it will display.
I am also not allowed to use if/else statements in this program.
View Replies
View Related
Sep 27, 2014
i have this code that I need to input into a GUI interface. how to start mixing the two together.
import java.util.Scanner;
import java.util.Date;
import java.text.ParseException;
[Code]....
View Replies
View Related
Jun 9, 2014
I have a JMenuItem "Find" in the Edit Menu. I want to add a shortcut key to the JMenuItem.
For Find for example i want to use Ctrl + F
Here is my 'Action' for 'Find' which can be used via Edit->Find. It works.
Find = new AbstractAction(){
public void actionPerformed(ActionEvent e){
String word = JOptionPane.showInputDialog(new MainWindow(),"","Find",PLAIN_MESSAGE);
new WordSearcher(textArea,word);
}
};
WordSearcher() is a class i am using to search the word
Now i want to add a KeyListener for ctrl+F, for doing the same purpose. Even this one works.
private KeyListener k1 = new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.isControlDown())
{
if(e.getKeyCode()== KeyEvent.VK_F)
[Code] ....
But the problem here is i have to write the same code twice. Is there some way by which I can Use the already written Action Find in the KeyListener.
View Replies
View Related
Sep 10, 2014
So what my program is supposed to do is take a number inputted by the use and then take a phrase. It then changes that phrases letter by the number inputted prior for example if you type in 2 as your int and Hello as your phrase you should get JGNNQ, which i can do. but the problem is that when i run it, it outputs like this:
J
G
N
N
Q
As separate characters how can I combine those characters in 1 string so it looks like JGNNQ? this is my code
import java.util.Scanner;
public class Dcod_MAin {
private static final Object[] String = null;
public static void main(String[] args){
Scanner input = new Scanner (System.in);
System.out.println("What is the day of the month");
int shift;
[Code] ....
View Replies
View Related
Mar 20, 2014
All I need to do is show in just one JFrame the two combined JFrames. One JFrame namely leftPanel will appear to the left or west and the other namely rightPanel to the right or east using BorderLayout. I already did creating them first as JPanels or as internal classes and subsetted them in one JFrame but that didn't work because it looked messy. And now I've created them as two separate JFrames, compiled separately, and tried to subset them as one in the JFrame. I didn't add any functionality to this program because all I intend to do is to show those two JFrames together in one JFrame. Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class dirtyIceCream extends JFrame {
leftPanel westPanel;
rightPanel eastPanel;
public dirtyIceCream()
[code].....
What am I missing or did I code anything wrong here? Or should I use NetBeans IDE for anything as complicated as this?
View Replies
View Related
May 28, 2014
I have developed an application using Java JSP and PostgreSQL database which inputs data from users including multiple file uploads in different formats (MS Word, Excel, PDF etc.). The uploaded files are also stored in the database.
My client wants the software to print a report in PDF format which includes all user data entered (in a defined format) along with all the uploaded documents as appendices.
How the system can include all uploaded files into one PDF report?
View Replies
View Related
May 28, 2014
I have developed an application using Java JSP and PostgreSQL database which inputs data from users including multiple file uploads in different formats (MS Word, Excel, PDF etc.). The uploaded files are also stored in the database.
My client wants the software to print a report in PDF format which includes all user data entered (in a defined format) along with all the uploaded documents as appendices.
How the system can include all uploaded files into one PDF report?
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