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


ADVERTISEMENT

Logger Logs Old Messages

Mar 4, 2014

I have the following code that comes directly from the book Core Java vol 1. The last two statements are mine but when I change the last statement's String the message being logged doesn't change. For that manner when I change the level of the last statement the file doesn't update to the correct log level. What am I doing wrong?

Java Code:

public class LogTester
{
public static void main(String[] args)
{
if (System.getProperty("java.util.logging.config.class") == null
&& System.getProperty("java.util.config.file") == null)

[code]....

Forgot to say the file also only logs the old message and level from a previous recompilation

View Replies View Related

Processing Queue Containing Dissimilar Messages

May 25, 2014

I am new to Java/OOP in general, and am trying to implement a multi-threaded system that contains a master thread, and a set of worker threads that are heterogeneous in the work they do. Once they complete the work, the workers indicate to the master by posting the result on to its queue. Here is the problem. The results of each type of work is different, and the master has to process each differently. In C (which I'm familiar with), this can be achieved by having a message type that is a union of all the expected messages, and by using a switch statement.

I thought of doing something similar in Java, by using instance of on each incoming message (each individual message class having been subclassed from a super message class) , and doing switch on that, but it doesn't seem to be the OO way to do things. The only other way I could think of was to implement an abstract method to get the type of each message, and then use the type in a switch statement, or if-then-else. Is there some other Java idiom to do this kind of processing? Also, if this is an acceptable method, why is it superior to using the reflection to find out the message type (instead of using the abstract getType())?

The message types look similar to the code below:

abstract class Message {
abstract String getType();
} class Result1 extends Message {
ResultType1 content;
String getType() {

[Code] ....

View Replies View Related

EJB / EE :: Reject Duplicate Messages In ActiveMq

Jun 13, 2014

I am using ActiveMq alongwith Spring in my project. I want my queue to be configured to reject the duplicate messages.I tried my level best to do so. I tried googling for the same. but could not get anything.

View Replies View Related

Storm Chaser With Error Messages

Mar 1, 2015

I am having issues with a few lines of code and a java.util.UnkownFormaException. Here are the issues:

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '1'
at java.util.Formatter.checkText(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at Storm.toString(Storm.java:99)
at StormChaser.DisplayStorms(StormChaser.java:149)
at StormChaser.main(StormChaser.java:55)

I have tried a lot of different things but can't seem to figure it out.

import java.io.*;
import java.util.Scanner;
public class StormChaser {
public static void main(String[] args)

[code]....

View Replies View Related

EJB / EE :: MQ Messages Getting Re-delivered Infinitely With Exception In System Out

Apr 7, 2014

MQ Issue on the Websphere 7.0.0.25 server ..Same Message is getting redelivered again and again and below exception is coming in System out log. And secondly the messages are not getting processed completely.

[4/7/14 12:14:58:616 GMT+05:30] 0000001e LocalTranCoor E WLTC0017E: Resources rolled back due to setRollbackOnly() being called.
[4/7/14 12:16:14:738 GMT+05:30] 00000062 LocalExceptio E CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method "onMessage" on bean "BeanId(myroj#myEJB.jar#MQMessageReceiverMDB, null)". Exception data: java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedMethodAccessor77.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
at com.ibm.ejs.jms.listener.ServerSessionDispatcher.dispatch(ServerSessionDispatcher.java:47)
at com.ibm.ejs.container.MDBWrapper.onMessage(MDBWrapper.java:98)

[code]...

View Replies View Related

Maintain Separate Files For Different Types Of Messages

Sep 19, 2014

I am attempting to maintain separate files for different types of "messages" (user messages, field labels/buttons, data values). In this attempt I am trying to get the description of different data values. For example, a UserStatus "A" might be displayed as Active or Activo.

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="defaultEncoding" value="UTF-8"/>
<property name="basenames">
<list>
<value>WEB-INF/locale/messages/messages</value>
<value>WEB-INF/locale/fields/fields</value>
<value>WEB-INF/locale/values/values</value>
</list>
</property>
</bean>

Here are the relevant entries in the values_en_us.properties file:

user.status.A = Active
user.status.I = Inactive
user.status.P = Pending

I would like to build an Enum for each type of value that I can get the localized value from. In the code below, I have hardcoded the values being passed to the get message to reduce the number of variables when trying to debug this.

import java.util.EnumMap;
import java.util.HashMap;
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public enum UserStatusEnum {

[Code] ....

When this code runs, I get the following message:

org.springframework.context.NoSuchMessageException: No message found under code 'user.status.A' for locale 'en_us'.

On this line of code:

description = appCtx.getMessage("user.status.A", null, new Locale("en_us"));

The application is already showing my custom application error messages I have in the messages localized files, but in that case the ApplicationContext is already available. Because I can get to the contents of the messages_en_us.property files, I'm assuming me config is correct. However, the classes that get the messages content are instantiated by Spring.

The Enums are not created by Spring, so my assumption is that I am doing something wrong in how I am getting a handle on the ApplicationContext or how I am using it.

After looking at the appCtx values in debug mode, I can see that the messageSource > basenames does at least contain my configuration data.

[WEB-INF/locale/messages/messages, WEB-INF/locale/fields/fields, WEB-INF/locale/values/values]

Although I don't see the whole filenames with the file extension anywhere or the property file entries.

View Replies View Related

Java EE SDK :: How To Push Messages From Server Side

Jan 18, 2012

I have some data in the database and values can be added on demand. so when ever the value added to the database i need to promt that message to all users which are accessing my website, so how can i acheive this....

View Replies View Related

I/O / Streams :: How To Send Messages Efficiently From Backend To Frontend

Apr 8, 2014

I'm working on a project that has two separate components. The first is a back end, that will do most of the heavy lifting, the other part is a front end GUI. The GUI will include the back end into it's project as an imported JAR file.

I need to be able to keep these two decoupled, as I might be writing different front ends using the same back end. The challenge in front of me (well one of many) is how to pass messages from the back end to the GUI so I can report things that are happening.

For example, if i call method FOO, FOO might do several different things; connect to a database, divide by zero, solve world hunger. I want to be able to either tie a JTextArea , or another component (or multiple components) to this stack of information, or at the very least, have something listening for this information, and when I see that my back end reports something, my front end is quickly aware of this information, and then I can process it and inform the user of the front end.

It would also be useful to be able to send a message from front end to back end , so perhaps the back end might learn that the front end user is unhappy and would like to stop running the current query.

View Replies View Related

JSF :: Primefaces - Two Messages Getting Displayed Instead Of One For Ajax Blur Event

Jan 28, 2014

I have one row editable datatable.I have implemented email validation to one of the column where error message must display on blur of email field.This is working fine.I have a dialog with form to be displayed in the same page. Validation is implemented to this form also with on blur event. The dialog validation message gets displayed on blur but along with that the main form also displays the same validation message. This should not happen.

JSF page

<h:form id="lpcForm">
<div id="content">
<p:commandLink id="cmdLinkDelete" value="Delete"
style="font-size:15px;padding-left:15px;" ajax="true"
action="#{lpcBean.deleteRecords}" update=":lpcForm:lpcDataTable" />
  
[Code] ....

The message with id lpcErrMsg is the one that i am displaying on blur in the main page when email format is wrong.And this message gets displayed with dialog field validation also although i have never referred to this id to be rendered in the dialog.

The message with id lpcDlgMsg is the message that i am displaying inside the dialog with widgetvar dlg on blur.As of now i have implemented blur event validation for the first required field in the dialog.

View Replies View Related

Open / Send Multiple Messages Over TCP And Close Connection On Events

Oct 7, 2014

I have a simple method in Java through which I send commands to a machine over TCP. The problem is:

Machine can't accept more than two connections in 20 seconds.

I need to send 15-20 commands to the machine in 3 minutes.

This is my current method which is not working as it should, 2 commands get transmited but third command hangs because of the machine.

void sendCommand(String command) throws IOException {
String ipaddress = "192.168.0.2";
Socket commandSocket = null;
BufferedWriter out = null;
BufferedReader in = null;
BufferedWriter outToDetailFile = null;

[Code] .....

Basically what i need is:

1st: I need to open the connection by calling method

public void openConnection(String ipaddress, String port){
//Code to start the connection
}

2nd: I need to be able to send commands to the connection I have already opened (i will send multiple messages in time period of 5-10 minutes):

public void sendCommand(String message){
}

3rd: Close that connection

public void closeConnection(){
}

View Replies View Related

Display Some Messages On Output File In Display Head Function

Mar 18, 2014

Write a class named FileDisplay with the following methods:

1.) constructor: the class's constructor should take the name of a fil as an arugment.
2.) displayHead: This method should display only the first five lines of the file's contents

Here is the following code I have made so far

import java.io.*;
public class FileDisplay
{
private String filename;
 public FileDisplay(String Filename) throws IOException

[Code] ....

First, in my constructor I have taken in an argument and used that argument to open up an output file. Meanwhile, I'm trying to work n the displayhead method to print out information and to read data to. I haven't opened up my input file yet, but I'm not understand how can I read a print data to an output file. in

public void displayHead()
{FileWriter file=new FileWriter(Filename)}

do I make create another instance of the filewriter class to output data?

In simple words, suppose to I want to display some messages on my output file in the displayhead function. Since I already have opened up the file in the constructor, how do I combine that in this method...

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

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 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

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







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