Simple java program to post meesage to MQ series

Hi..
Somdbody can give me to connect to MQ series.
Maubly i want to know... what are all required to connect to MQ queue(not from Hardware side.), want to know line.. we require servername, qname what else.......
plase let me know litte urgent requiremnt.
regards
kumar

Hi all,
Can i have sample code for this..? Need to give the IP , Port of server connecting,Queuemanager name of the MQ, and provision to specify the path of the input message.
Balaji R
-----------

Similar Messages

  • Problem while executing simple java program

    Hi
    while trying to execute a simple java program,i am getting the following exception...
    please help me in this
    java program :import java.util.*;
    import java.util.logging.*;
    public class Jump implements Runnable{
        Hashtable activeQueues = new Hashtable();
        String dbURL, dbuser, dbpasswd, loggerDir;   
        int idleSleep;
        static Logger logger = Logger.getAnonymousLogger();      
        Thread myThread = null;
        JumpQueueManager manager = null;
        private final static String VERSION = "2.92";
          public Jump(String jdbcURL, String user, String pwd, int idleSleep, String logDir) {
            dbURL = jdbcURL;
            dbuser = user;
            dbpasswd = pwd;
            this.idleSleep = idleSleep;
            manager = new JumpQueueManager(dbURL, dbuser, dbpasswd);
            loggerDir = logDir;
            //preparing logger
            prepareLogger();
          private void prepareLogger(){      
            Handler hndl = new pl.com.sony.utils.SimpleLoggerHandler();
            try{
                String logFilePattern = loggerDir + java.io.File.separator + "jumplog%g.log";
                Handler filehndl = new java.util.logging.FileHandler(logFilePattern, JumpConstants.MAX_LOG_SIZE, JumpConstants.MAX_LOG_FILE_NUM);
                filehndl.setEncoding("UTF-8");
                filehndl.setLevel(Level.INFO);
                logger.addHandler(filehndl);
            catch(Exception e){
            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);
            logger.addHandler(hndl);
            logger.setLevel(Level.FINE);
            logger.info("LOGGING FACILITY IS READY !");
          private void processTask(QueueTask task){
            JumpProcessor proc = JumpProcessorGenerator.getProcessor(task);       
            if(proc==null){
                logger.severe("Unknown task type: " + task.getType());           
                return;
            proc.setJumpThread(myThread);
            proc.setLogger(logger);       
            proc.setJumpRef(this);
            task.setProcStart(new java.util.Date());
            setExecution(task, true);       
            new Thread(proc).start();       
         private void processQueue(){       
            //Endles loop for processing tasks from queue       
            QueueTask task = null;
            while(true){
                    try{
                        //null argument means: take first free, no matters which queue
                        do{
                            task = manager.getTask(activeQueues);
                            if(task!=null)
                                processTask(task);               
                        while(task!=null);
                    catch(Exception e){
                        logger.severe(e.getMessage());
                logger.fine("-------->Sleeping for " + idleSleep + " minutes...hzzzzzz (Active queues:"+ activeQueues.size()+")");
                try{
                    if(!myThread.interrupted())
                        myThread.sleep(60*1000*idleSleep);
                catch(InterruptedException e){
                    logger.fine("-------->Wakeing up !!!");
            }//while       
        public void setMyThread(Thread t){
            myThread = t;
        /** This method is only used to start Jump as a separate thread this is
         *usefull to allow jump to access its own thread to sleep wait and synchronize
         *If you just start ProcessQueue from main method it is not possible to
         *use methods like Thread.sleep becouse object is not owner of current thread.
        public void run() {
            processQueue();
        /** This is just another facade to hide database access from another classes*/
        public void updateOraTaskStatus(QueueTask task, boolean success){
            try{         
                manager.updateOraTaskStatus(task, success);
            catch(Exception e){
                logger.severe("Cannot update status of task table for task:" + task.getID() +  "\nReason: " + e.getMessage());       
        /** This is facade to JumpQueueManager method with same name to hide
         *existance of database and SQLExceptions from processor classes
         *Processor class calls this method to execute stored proc and it doesn't
         *take care about any SQL related issues including exceptions
        public void executeStoredProc(String proc) throws Exception{
            try{
                manager.executeStoredProc(proc);
            catch(Exception e){
                //logger.severe("Cannot execute stored procedure:"+ proc + "\nReason: " + e.getMessage());       
                throw e;
         *This method is only to hide QueueManager object from access from JumpProcessors
         *It handles exceptions and datbase connecting/disconnecting and is called from
         *JumpProceesor thread.
        public  void updateTaskStatus(int taskID, int status){       
            try{
                manager.updateTaskStatus(taskID, status);
            catch(Exception e){
                logger.severe("Cannot update status of task: " + taskID + " to " + status + "\nReason: " + e.getMessage());
        public java.sql.Connection getDBConnection(){
            try{
                return manager.getNewConnection();
            catch(Exception e){
                logger.severe("Cannot acquire new database connection: " + e.getMessage());
                return null;
        protected synchronized void setExecution(QueueTask task, boolean active){
            if(active){
                activeQueues.put(new Integer(task.getQueueNum()), JumpConstants.TH_STAT_BUSY);
            else{
                activeQueues.remove(new Integer(task.getQueueNum()));
        public static void main(String[] args){
                 try{
             System.out.println("The length-->"+args.length);
            System.out.println("It's " + new java.util.Date() + " now, have a good time.");
            if(args.length<5){
                System.out.println("More parameters needed:");
                System.out.println("1 - JDBC strign, 2 - DB User, 3 - DB Password, 4 - sleeping time (minutes), 5 - log file dir");
                return;
            Jump jump = new Jump(args[0], args[1], args[2], Integer.parseInt(args[3]), args[4]);
            Thread t1= new Thread(jump);
            jump.setMyThread(t1);      
            t1.start();}
                 catch(Exception e){
                      e.printStackTrace();
    } The exception i am getting is
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe
    Exception in thread "main" ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
    JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820] Please help me.....
    Thanks in advance.....sathya

    I am not willing to wade through the code, but this portion makes me conjecture your using an Oracle connect string instead of a class name.
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe

  • A simple Java program to be compiled with ojc and executed with java.exe

    Hi ,
    This thread is relevant to Oracle Java Compiler (file ojc) and jave.exe file.
    I have written a simple java program which consists of two simple simple classes and using the JDev's 10.1.3.2 ojc and java files , i'm trying to execute it after the successful compilation....
    The problem is that trying to run it... the error :
    Exception in thread "main" java.lang.NoClassDefFoundError: EmployeeTest
    appears.
    How can i solve this problem...????
    The program is as follows:
    import java.util.*;
    import corejava.*;
    public class EmployeeTest
    {  public static void main(String[] args)
       {  Employee[] staff = new Employee[3];
          staff[0] = new Employee("Harry Hacker", 35000,
             new Day(1989,10,1));
          staff[1] = new Employee("Carl Cracker", 75000,
             new Day(1987,12,15));
          staff[2] = new Employee("Tony Tester", 38000,
             new Day(1990,3,15));
          int i;
          for (i = 0; i < 3; i++) staff.raiseSalary(5);
    for (i = 0; i < 3; i++) staff[i].print();
    class Employee
    {  public Employee(String n, double s, Day d)
    {  name = n;
    salary = s;
    hireDay = d;
    public void print()
    {  System.out.println(name + "...." + salary + "...."
    + hireYear());
    public void raiseSalary(double byPercent)
    {  salary *= 1 + byPercent / 100;
    public int hireYear()
    {  return hireDay.getYear();
    private String name;
    private double salary;
    private Day hireDay;
    For compilation... i use :
    D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdev\bin\ojc -classpath D:\E-Book\Java\Sun_Java_Book_I\Corejava EmployeeTest.java
    For execution , i issue the command:
    D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\java EmployeeTest
    NOTE:I tried to use the jdk of Oracle database v.2 but the error :
    Unable to initialize JVM appeared....
    Thanks , a lot
    Simon

    Hi,
    Thanks god....
    I found a solution without using Jdev.....
    C:\oracle_files\Java\Examples>SET CLASSPATH=.;D:\E-Book\Java\Sun_Java_Book_I\Corejava
    C:\oracle_files\Java\Examples>D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\javac EmployeeTest.java
    C:\oracle_files\Java\Examples>D:\ORACLE_UNZIPPED\JDeveloper_10.1.3.2\jdk\bin\java EmployeeTest
    What does Ant has to do with this?Sorry, under the Ant tree a classpath label is found....I'm very new to Java and JDev...
    You need to include the jar file that has the Day method in it inside project properties->libraries.I have not .jar file.. just some .java files under the corejava directory.... By the way , I have inserted the corejava directory to the project pressing the button Add Jar/Directory.... , but the problem insists..
    Thanks , a lot
    Simon

  • Help with a simple Java program

    I'm making a sort of very simple quiz program with Java. I've got everything working on the input/output side of things, and I'm looking to just fancy everything up a little bit. This program is extremely simple, and is just being run through the Windows command prompt. I was wondering how exactly to go about making it to where the quiz taker was forced to hit the enter key after answering the question and getting feedback. Right now, once the question is answered the next question is immediately asked, and it looks kind of tacky. Thanks in advance for your help.

    Hmm.. thats not quite what I was looking for, I don't think. Here's an example of my program.
    class P1 {
    public static void main(String args[]) {
    boolean Correct;
    char Selection;
    int number;
    Correct = false;
    System.out.println("Welcome to Trivia!\n");
    System.out.println("Who was the first UF to win the Heisman Trophy?\n");
    System.out.print("A) Danny Wuerffel\nB) Steve Spurrier\nC) Emmit Smith\n");
    Selection = UserInput.readChar();
    if(Selection == 'B' | Selection == 'b')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    System.out.println("(\nHit enter for the next question...");
    System.in.readLine();
    Correct = false;
    System.out.println("\nWhat year did UF win the NCAA Football National Championship?\n");
    number = UserInput.readInt();
    if(number == 1996)
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    Correct = false;
    System.out.println("\nWho is the President of the University of Florida?\n");
    System.out.println("A) Bernie Machen\nB) John Lombardi\nC) Stephen C. O'Connell\n");
    Selection = UserInput.readChar();
    if(Selection == 'A' | Selection == 'a')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    }

  • I did write a simple java program but it is not working please help me.....

    This is the program I wrote LineRect just to draw a line a rectangle etc...... Y it is not working How can i used the same program to run without using applet that is by using awt and swing.........Pls Help me.............
    import java.awt.*;
    import java.io.*;
    public class LineRect
    {public void paint(Graphics g)
         {g.drawLine(10,10, 50,50);
         g.drawRect(10, 60, 40,30);
         g.fillRect(60,10,30,80);
         g.drawRoundRect(10,100,80,50,10,10);
         g.fillRoundRect(20,110,60,30,5,5);
         g.drawLine(100,10,230,140);
         g.drawLine(100,140,230,10);
    <APPLET
    CODE =LineRect.class
    WIDTH=250
    HEIGHT=200>
    </APPLET>

    There are many significant errors here for instance you are using a class file as if it were an applet yet you do not subclass applet. Your code has no init method (if it is to be an applet). Your best bet is to go through the tutorials one step at a time. One thing to consider is to subclass a JPanel and draw on the jpanel overriding the paintComponent method. This can then be added to a JFrame or a JApplet's contentPane and would allow the same graphics in both. But again, please study the tutorials on all of this, otherwise you will be doing hit-or-miss programming, and that is no way to learn.
    Much luck!
    Addendum: Also, if you are just beginning in Java programming, I suggest you start with the basics and not with Swing / AWT / graphics programming. Otherwise you will just end up bruised and disappointed. You have to learn to walk before you can run.
    Edited by: Encephalopathic on Dec 26, 2007 5:09 AM

  • How to read card reader (bar code reader) in simple java program ?

    hai all
    how to manipulate (read/write) card readers (or bar code reader ) in
    a java program ?
    should i import any particular package library ?
    pls give me any sample code or tutorials or tools, etc (whatever you have) .
    i am new to this card reader category
    its very urgent
    thank you .

    Nearly all card readers and barcode readers I've ever seen simply stick their input right onto stdin, so you can capture it just as if it had been typed in on a keyboard

  • Can I write and run simple java programs in Xcode

    I need to write and run basic java programs on my mac. I would like to run it in Xcode, but I don't know how to set it up? Is there a way?

    Read the following discussion from last month on here:
    Can Xcode 4.5.1 compile/run java?

  • Help with Simple JAVA program

    I'm a complete novice with Java. I want to write a Java program to run on Windows 2000 servers to write a list of certain files in a directory into a *.txt file. I hope to add complexity once I have this basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.

    I'm a complete novice with Java. I want to write a
    Java program to run on Windows 2000 servers to write
    a list of certain files in a directory into a *.txt
    file. I hope to add complexity once I have this
    basic part working. Here's the code I have so far:
    //this Java application finds poll* files
    public class FindPollApp
    //Create File Object
    File dir = new File("d:/jda/windss/poll");
    //List directory
    if(dir.isDirectory())
    String[] dirContents = dir.list();
    for (int i=0; i < dirContents.length; i++)
    System.out.println(dirContents);
    //Iterate through files
    I get the following errors:
    C:\JAVA>javac FindPollApp.java
    FindPollApp.java:9: illegal start of type
    if(dir.isDirectory())
    ^
    FindPollApp.java:18: <identifier> expected
    ^
    2 errors
    Thanks.
    You need to create a method and insert your if statement in there

  • Best Way to Make a Simple Java Program Configurable?

    I have a java program that does some stuff involving a database. It's basically a script, but I chose to use Java because of the nice JDBC facilities. Anyway, I plan to schedule a task to have the java program executed daily, but it would be nice if I could configure it without having to recompile the program every time. By configuration, I mean remembering about 6 lines of text, such as database connection address, user-name, password, spread sheet to update, etc. Since I am storing a username and password, I should also encrypt the data. Is there some standalone Java program that is made for creating config files, which would be encrypted and have some sort of an API to access all the data stored in the config file? I am basically thinking of a savable hashtable of Strings mapping keys to values where the values can be configured by some standalone application that allows the values associated with each key to be changed, preferably through a GUI. I could make this, but I figured there may already be something that does this.

    SNYP40A123 wrote:
    Only thing I still need is some way to hide the password that I plan to store in it.That's a completely separate issue. There could be a lot of discussion on this but basically you can't reliably hide a password that you store somewhere no matter what you do. You can do things that will prevent the idly curious from knowing it but it's a lot harder to prevent the determined cr&#97;cker from knowing it.

  • Error when running a very simple java program

    java.lang.NoClassDefFoundError: HelloWorldApp
    Exception in thread "main"
    Tool completed successfully
    I am getting the above error. I just downloaded java standard edition 1.4 sdk. I compiled the program with no errors. But when I run it . I get the above error. Is it something related to finding the package java.lang?
    Please let me know.
    Thanks.

    I have the same problem but in a different way. I download/installed jdk1.4 and J2me. I was able to run j2me without any problem following their tutorial.
    I set my config.sys to:
    PATH=C:\j2sdk1.4.0\bin;C:\j2me\j2me_cldc\bin;C:\j2me\midp1.0.3fcs\bin;
    I did compile and ran couple of programs with no problems at all, for some reason some of them give me error ex: Exception in thread "main" java.lang.NoClassDefFoundError: NamofFile
    I read couple of posting about setting the CLASSPATH, is that maybe the source of the problem if so how I can do so given that I�m using win2000. Any Ideas !!!

  • PLEASE HELP!!!! simple java program...

    Hi there,
    im seeking HEP!!!! from any one who could solve my problem. i have a program to be written that consists of gym members details and prints tem out to the screen.
    A program is to be written to store Gym registration details. A Gym member record consists of membership number, name, postcode and fee.
    Write a class definition to represent such Gym membership details.
    Write a main method that declares and initialises two new Gym membership objects.
    Write a method to request data items from the user to fill both the new Gym member objects.
    Write a method to display to the screen the names and membership numbers of both members.
    Example data entry ( ?Z123456?, ?Paul Jones?, ?HN78HG?, 250);
    thanks ...

    public class Gym
        //set the membership number of a member as String
        private void setMembershipNumber(String number)
            membershipNumber = number;
        //sets the name of the member as String
        private void setMemberName(String name)
            memberName = name;
        //sets the post code as String
        private void setPostCode(String postCode)
            memberPostCode = postCode;
        //sets the fee as String
        private void setFee(String fee)
            gymFee = fee;
        //return methods here
        private String getMemberNumber( )
            return membershipNumber;
        private String getMemberName( )
            return memberName;
        private String getPostCode( )
            return memberPostCode;
        private String getFee( )
            return gymFee;
        /* A method displayOutput,just in case the user wants to use all the
         *return methods in just one call
        public void displayOutput( )
            System.out.println("Number: " + getMemberNumber( ) + "\n" +
                              ("Name: " + getMemberName( ) + "\n" +
                              ("Post Code: " + getPostCode( ) + "\n" +
                              ("Fee: " + getFee( )))));
    /*Main  program
    public class GymMembers
        public static void main(String[] args)
          Gym gymMembership1 = new Gym("129983", "Parvez", "1490", "50.00");
          Gym gymMembership2 = new Gym("324512", "Middlesex", "00013", "40.00");
          gymMembership1.displayOutput( );
          System.out.println("\n");
          gymMembership2.displayOutput( );
          System.exit(0);
    }and ther error im getting from the compiler is..........
    C:\Documents and Settings\user\My Documents\Gym.java:91: inner classes cannot have static declarations
    public static void main(String[] args)
    ^
    1 error
    Tool completed with exit code 1

  • Run simple java program error

    Hi:
    I followed the step by step at "Your First Cup of Java (for Microsoft Windows)" at
    http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html#
    all the steps work, esecpt for the run program part, I get Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp. but the HelloWorldApp clases is there. and I set my path and classes path at xp enviroment
    classes %CATALINA_HOME%\common\lib\servlet.jar;c:\jdom-b8\build\jdom.jar;c:\jdom-b8\lib\xerces.jar; Library.java;c:\hsqldb\lib\hsqldb.jar
    %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\system32\WBEM;c:\jdk1.4.0_02\bin; %path%
    hope you can help !
    Thank you

    The problem with running the HelloWorldApp is because you have set the classpath.
    It looks like Tomcat and others are installed on your system. Trying to run before you can walk, eh!
    This is your system CLASSPATH and points to directories that contain classes and/or *.jar files that contain classes:
    .;%CATALINA_HOME%\common\lib\servlet.jar;c:\jdom-b8\build\jdom.jar;c:\jdom-b8\lib\xerces.jar;c:\hsqldb\lib\hsqldb.jar
    I don't know why Libary.java is there in your original post because it is a source file and not a class yet; and you don't point directly at a class, only the folder or JAR it is in.
    This is your system PATH and points to directories that contain programs:
    %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\system32\WBEM;c:\jdk1.4.0_02\bin;
    With XP the environment is split into two parts:
    1/ the system environment variables and will prepend to:
    2/ your user environment variables may have the same name and will append to variables in 1/. So there is no need for the %path% bit.
    Make sure that CATALINA_HOME is set to the base folder of the CATALINA(TOMCAT) installation, if you are planning to use it.
    You shouldn't need to set PATH or CLASSPATH for your user ID unless you only want that user id to have access.
    My advice (if it is your machine) is to uninstall Apache/Tomcat and anything else (such as JDOM) that isn't basic Java until you have learned the language. Then delete the CLASSPATH variable and remove the \system32\WBEM; part of the the PATH variable.
    Regards,
    Hugh.

  • Running a Simple Java Program in Windows 7

    Hello:
    Learning Java.
    I have Windows 7 64 bit. I have following Java installed:
    C:\Program Files\Java\jdk1.6.0_21\demo>java -version
    java version "1.6.0_21"
    Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
    Java HotSpot(TM) 64-Bit Server VM (build 17.0-b17, mixed mode)
    My path is as follows:
    C:\Program Files\Java\jdk1.6.0_21\demo>path
    PATH= C:\Program Files\Java\jdk1.6.0_21\bin;C:\Windows\system32;C:\Windows;C:\Wi
    ndows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files
    (x86)\QuickTime\QTSystem\
    When I try to run a program called Exampleprogram.java as follows, I see below error:
    C:\Program Files\Java\jdk1.6.0_21\demo>java exampleprogram.java
    Exception in thread "main" java.lang.NoClassDefFoundError: exampleprogram/java
    Caused by: java.lang.ClassNotFoundException: exampleprogram.java
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    Could not find the main class: exampleprogram.java. Program will exit.
    C:\Program Files\Java\jdk1.6.0_21\demo>
    Will appreciate your early help. Thanks.
    Victor

    Recomplied and still no luck. I gave a different name to the program and still getting the same error as follows:
    C:\Program Files\Java\jdk1.6.0_21\bin>dir hel*
    Volume in drive C is WINDOWS7PRO
    Volume Serial Number is EB0E-8900
    Directory of C:\Program Files\Java\jdk1.6.0_21\bin
    10/03/2010 11:29 AM 269 helloworld.java
    10/03/2010 11:33 AM 429 HelloWorldApp.class
    2 File(s) 698 bytes
    0 Dir(s) 123,998,978,048 bytes free
    C:\Program Files\Java\jdk1.6.0_21\bin>java helloworld.java
    Exception in thread "main" java.lang.NoClassDefFoundError: helloworld/java
    Caused by: java.lang.ClassNotFoundException: helloworld.java
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    Could not find the main class: helloworld.java. Program will exit.
    C:\Program Files\Java\jdk1.6.0_21\bin>
    Thoughts please.

  • Need urgent help in a simple java program that adds up even numbers and..

    The task is to write a program that allows the user to enter 8 integers and then displays the sum of the odd integers and the product of the even integers
    what i did so far is
    public class Computation
    private int n;
    private int even;
    private int odd;
    public Computation()
    even =0;
    odd = 1;
    public Computation(int num1, int num2, int num3,int num4,int num5,int num6,int num7, int num8)
    n = num1;
    n = num2;
    n = num3;
    n = num4;
    n = num5;
    n = num6;
    n = num7;
    n = num8;
    for(int i=0; i<=n; i++)
    if(n%2 == 0)
    even += n;
    else
    odd *=n;
    public int getEven(int n)
    return even;
    public int getOdd()
    return odd;
    import java.util.*;
    public class Tester
    public static void main(String [] args)
    System.out.println("Enter any three words");
    Scanner input = new Scanner(System.in);
    int num1 = input.nextInt();
    int num2 = input.nextInt();
    int num3 = input.nextInt();
    int num4 = input.nextInt();
    int num5 = input.nextInt();
    int num6 = input.nextInt();
    int num7 = input.nextInt();
    int num8 = input.nextInt();
    Computation compute = new Computation(num1, num2, num3, num4, num5, num6, num7, num8);
    System.out.println("The Summation of the even numbers is: " + compute.getEven( ) + "\n" +"The product of the odd numbers is: " + compute.getOdd());
    }The result i get is always zero.. however, i think the problem lies in the first class when i constructed the numbers and sat them all to one object "n",
    i need help in fixing this bug,,
    thanks

    7uSamx wrote:
    Can you illustrate by a small example please ?Any small example would already contain pretty much the entire code.
    You know how to declare a method, right? You have several in your code, so I assume you do.
    You already know how to check if a given variable is even or odd. You already showed that code, so I assume you do.
    Now put those two together and you'll have a method that decides if the value passed to it is even or odd.
    Now put the desired action in each of the branches of the if-statement and you're almost done.
    Now call the method with each method from your constructor and you're done.

  • Help!  Simple Java Program.

    Here is the problem: Write a program that creates a loan amortization table. The user of the program will supply values for Initial Loan Principal, Annual Percentage Rate and Monthly Payment. The program should print out the appropriate amortization table including the number of Monthly Payments and the Total Interest paid for the life of the loan. The program should allow multiple
    runs (up to 4 different versions) of the table process and should allow the
    user to compare runs in a tabular format.
    This is what I have so far and should work one I completely debug it. I am really new to Java, and I thinks it is somthing to do with the Array. I recently switched from C++ to Java, so I don't think I have the syntax down correctly. Thanks.
    import javax.swing.JOptionPane;
    public class Program_01
         public static void main(String [] args)
              int Runs;
              do{
                        String Run_Question = JOptionPane.showInputDialog(null, "How many times,would you like to run" + 
                        " the program? (Up to four runs only!)", "Run Question", JOptionPane.QUESTION_MESSAGE);
                         Runs = Integer.parseInt(Run_Question);
                        if( Runs < 0 || Runs > 4)
                             JOptionPane.showMessageDialog(null, "The number is not valid, try again!", "Error",
                             JOptionPane.INFORMATION_MESSAGE);
                   }while(Runs < 0 || Runs > 4);
                   Questions(Runs);
         public static void Questions(int Runs)
              for(int index = 0;index < Runs;index ++)
                   String Loan_Principle_String = JOptionPane.showInputDialog(null, "What is the Loan Principle?", "Loan Amount",
                                                         JOptionPane.QUESTION_MESSAGE);     
                   String Percentage_Rate_String = JOptionPane.showInputDialog(null, "What is the Annual Percentage Rate?",
                                                           "Interest Rate", JOptionPane.QUESTION_MESSAGE);
                   String Monthly_Payment_String = JOptionPane.showInputDialog(null, "What is the Monthly Payment", "Payment",
                                                           JOptionPane.QUESTION_MESSAGE);
                   double Loan_Principle = Double.parseDouble(Loan_Principle_String);
                   double Percentage_Rate = Double.parseDouble(Percentage_Rate_String);
                   double Monthly_Payment = Double.parseDouble(Monthly_Payment_String);
                   Calculate(Loan_Principle, Percentage_Rate, Monthly_Payment);
         public static void Calculate (double Loan, double Percentage, double Monthly)
              double[] Principle = new double[]{0,0};
              double[] Interest = new double[]{0,0};
              double[] Remain = new double[]{0,0};
              double Monthly_Percent = Percentage/12;
              double MPR = ((int)((Monthly_Percent + .005) * 100.) / 100.);
              boolean Over = true;          
              double Borrowed = Loan;          
              int Month = 0;
              for (int index = 0; Over != false; index++)
                   double Rate = MPR * Loan;
                   double decimalRate = ((int)((Rate + .005) * 100.) / 100.);
                   Interest[index] = decimalRate;
                   double Prince = Monthly - decimalRate;
                   double decimalPrince = ((int)((Prince + .005) * 100.) / 100.);
                   Principle[index]= decimalPrince;
                   double Rmn = Borrowed - decimalPrince;
                   Borrowed = Rmn;
                   double decimalRmn = ((int)((Rmn + .005) * 100.) / 100.);
                   Remain[index] = decimalRmn;
                   if(Monthly > Remain[index] && Remain[index] > 0)
                        Monthly = Remain[index];
                        Over = false;
                   Month += 1;
              System.out.println("I am here!" + Month);
              System.out.println("Payment #" + " " + "Principle" + " " + "Payment" + " " + "APR" + " " + "MPR" +
               " " + "Interest Payment" + " " + "Principle Payment");
              System.out.println("------------------------------------------------------------------------");
              for(int index = 0; index < Month; index++)
                   System.out.println((index + 1) + "\t" + Remain[index] + "\t" + Percentage + "\t" + MPR + "\t" + Interest[index]
                    + "\t" + Principle[index]);
    }

    Okay, here is my updated code. I am having trouble outputting my formate to align with each category.
    import javax.swing.JOptionPane;
    import java.text.DecimalFormat;
    public class Program_01
         public static void main(String [] args)
              int Runs;
              do
                   String Run_Question = JOptionPane.showInputDialog(null, "How many times would you like to run" + 
                   " the program? (Up to four runs only!)", "Run Question", JOptionPane.QUESTION_MESSAGE);
                    Runs = Integer.parseInt(Run_Question);
                   if( Runs < 0 || Runs > 4)
                        JOptionPane.showMessageDialog(null, "The number is not valid, try again!", "Error",
                        JOptionPane.INFORMATION_MESSAGE);
              }while(Runs < 0 || Runs > 4);
                   Questions(Runs);
         public static void Questions(int Runs)
              for(int index = 0;index < Runs;index ++)
                   String Loan_Principle_String = JOptionPane.showInputDialog(null, "What is the Loan Principle?", "Loan Amount",
                                                         JOptionPane.QUESTION_MESSAGE);     
                   String Percentage_Rate_String = JOptionPane.showInputDialog(null, "What is the Annual Percentage Rate?",
                                                           "Interest Rate", JOptionPane.QUESTION_MESSAGE);
                   String Monthly_Payment_String = JOptionPane.showInputDialog(null, "What is the Monthly Payment", "Payment",
                                                           JOptionPane.QUESTION_MESSAGE);
                   double Loan_Principle = Double.parseDouble(Loan_Principle_String);
                   double Percentage_Rate = Double.parseDouble(Percentage_Rate_String);
                   double Monthly_Payment = Double.parseDouble(Monthly_Payment_String);
                   Calculate(Loan_Principle, Percentage_Rate, Monthly_Payment);     
         public static void Calculate (double Loan, double Percentage, double Monthly)
              double[] Principle = new double[100];
              double[] Interest = new double[100];
              double[] Remain = new double[100];
              double[] Payment = new double[100];
              DecimalFormat Decimal = new DecimalFormat(".00");
              double Total_Interest = 0;
              double T_Interest;          
              double Monthly_Percent = (Percentage/12)/100;
              double MPR = Monthly_Percent;
              boolean Over = true;          
              double Borrowed = Loan;
              double Deposit = Monthly;          
              int Month = 0;
              for (int index = 0; Over = true; index++)
                   double Rate = MPR * Borrowed;
                   double decimalRate = round(Rate,2);
                   Interest[index] = decimalRate;
                   Remain[index] = Borrowed;
                   Month += 1;     
                   if(Monthly > Remain[index ] && Remain[index ] > 0)
                        for(int count = 0; count <= Month; count++)
                             Total_Interest += Interest[count];     
                        T_Interest = round(Total_Interest,2);
                        Payment[index] = T_Interest;
                        Deposit = T_Interest;     
                   else
                        Payment[index] = Deposit;     
                   double Prince = Deposit - decimalRate;
                   double decimalPrince = round(Prince,3);
                   Principle[index]= decimalPrince;
                   System.out.println("I am here!" + decimalPrince);
                   double Rmn = Borrowed - decimalPrince;
                   double decimalRmn = round(Rmn,2);
                   Borrowed = decimalRmn;
                   if(Monthly > Remain[index ] && Remain[index ] > 0)
                        Over = false;
                        break;
              System.out.println("Payment #" + " " + "Principle" + " " + "Payment" + " " + "Percentage" + " " + "MPR" +
               " " + "Interest Payment" + " " + "Principle Payment");
              System.out.println("----------------------------------------------------------------------------");
              for(int index = 0; index < Month; index++)
                   System.out.println("   " + (index + 1) + "\t   " + Decimal.format(Remain[index]) + "   " +
                   Decimal.format(Payment[index]) + "   " + Decimal.format(Percentage) + "     " + MPR +
                   "\t" + Decimal.format(Interest[index]) + "\t\t" + Decimal.format(Principle[index]));     
              T_Interest = ((int)((Total_Interest + .005) * 100.) / 100.);
              System.out.println("\n\t\t\t" + "Total Interest Paid \t" + T_Interest + "\n");
              for(int index = 0; index < Month; index++)
                   System.out.printf("%f %f\n", Principle[index],Remain[index]);
         public static double round(double val, int places) {
         long factor = (long)Math.pow(10,places);
         // Shift the decimal the correct number of places
         // to the right.
         val = val * factor;
         // Round to the nearest integer.
         long tmp = Math.round(val);
         // Shift the decimal the correct number of places
         // back to the left.
         return (double)tmp / factor;
    }

Maybe you are looking for

  • Random lock ups on iPod Touch 8GB

    Out of the blue, my ipod screen will go almost completely black. You can barely see the screen that you were on and it becomes unresponsive. It will then show a black screen with the apple logo, but nothing more. I did a restore on it and removed all

  • Preview crashes every time I open a file

    After installing snow leopard in my MacBook Air and MacBook Pro, every time I try to look to a file that comes attached to an email, preview opens it and it is blank, when I click "show sidebar" preview quits unexpectedly, I have to reopen it and onl

  • What is my iPad min  has problem cellular data?

    Yes I try to telling you about my a new iPad mini is not work on my password

  • /system/library/extensions/AppleUSBethernet host.kext not properly installed

    Message on pro: /system/library/extensions/AppleUSBethernethost.kext not properly installed. What can I do?

  • Page Peel Transition Problem

    I can't seem to manipulate this transition to work properly - Although I set it to 'peel' from one still image clip (A) to another still image clip (B), it is only revealing the very same clip (A) underneath until about a quarter of the way through t