Quick Question Java Program

Hi all. Basically im trying to get a program to do this...
A user inputs any random integer. If the integer is even is divides it by 2. If it is odd it multiplys it by 3 and adds one.
This is supposed to bring you a sequence as it is supposed to always come down to the number 1.
My code just runs consistently. Can anyone tell me why?
import java.util.Scanner;
public class MathTheory
     public void testTheory()
          Scanner keyboard = new Scanner(System.in);
          System.out.println("Please enter any integer");
          int number = keyboard.nextInt();
          System.out.println("Sequence: ");
          while(number>1)
               if(number%2==0)
                    number = number/2;
                    System.out.print(" " + number + " ");
               if(number%2 != 0)
                    number = (number*3) + 1;
                    System.out.print(" " + number + " ");
class mathTheoryTester {
  public static void main(String[] arg) {
     MathTheory X = new MathTheory();
     X.testTheory();
}

Lets trace through the code with an input of 2
          while(number>1)
               if(number%2==0)// this comes out true
                    number = number/2;//So number becomes =1
                    System.out.print(" " + number + " ");
               if(number%2 != 0)  //Since number is = 1, this evaluates true
                    number = (number*3) + 1; // So number is set to 4
                    System.out.print(" " + number + " ");
               // So the loop never exits
          }

Similar Messages

  • Java Programming Language questions...???

    Hi everybody....
    Can I post here my questions about Java Programming Language....or only to to the relevant Sun's forum....http://forum.java.sun.com/index.jspa???
    My greetings,
    Simon

    Simon,
    sure, the worst thing that could happen is that people point you to the SUN forum. Usually this forum answers general Java questions.
    Frank

  • Java programming language main method question?

    Hello everyone I am quite new to the Java programming language and I have a question here concerning my main method. As you can see I am calling 4 others methods with my main method. What does the null mean after I call the method? I really don't understand is significance, what else could go there besides null?
    public static void main(String[] args)
              int cansPerPack = 6;
              System.out.println(cansPerPack);
              int cansPerCrate = 4* cansPerPack;
              System.out.println(cansPerCrate);
              have_fun(null);
              user_input(null);
              more_java(null);
              string_work(null);
         }Edited by: phantomswordsmen on Jul 25, 2010 4:29 PM

    phantomswordsmen wrote:
    ..As you can see I am calling 4 others methods with my main method. 'Your' main method? Your questions indicate that you did not write the code, who did?
    ..What does the null mean after I call the method?.. 'null' is being passed as an argument to the method, so there is no 'after the method' about it.
    ..I really don't understand is significance, what else could go there besides null? That would depend on the method signatures that are not shown in the code snippet posted. This is one of many reasons that I recommend people to post an SSCCE *(<- link).*
    BTW - method names like have_fun() do not follow the common nomenclature, and are not good code for a newbie to study. The code should be put to the pointy end of your sword.

  • Java Programming Competition Sample Questions

    Hi,
    I am interested in participating the Java Programming Competition in my University. For pratice can you point me to some website with sample questions or any question u have in mind.
    Thanks
    Satish

    I was thinking of putting up on-forum competitions, winner gets dukes etc.
    Someone find an empty forum and we can get on it.

  • Java Programming Question

    Hi,Everybody:
    I have a question about Java programming. If I want to write a java class code called if.java like below, how should I do to make it pass the java compiler and make it work. I know the words "if" and "for" are reserved words. I just try to figure it out that is it possible??? Do I need to create my own java compiler or recompiler?
    public class if
    public if() { }
    public static for test()
    return new for();
    public class for
    public for() { System.out.println("for class constructor"); }
    }

    I don't think you can bypass the compiler's rejection of this. There is little point to naming the classes after keywords. Not sure if it's case sensitive though, so maybe "If" or "For"? Otherwise, try "if_" or "for_"

  • Hi, I have quick question about use of USEBEAN tag in SP2. When I specify a scope of SESSION for the java bean, it does not keep the values that I set for variable in the bean persistent.Thanks,Sonny

     

    Make sure that your bean is implementing the serializable interface and that
    you are accessing the bean from the session with the same name.
    Bryan
    "Sandeep Suri" <[email protected]> wrote in message
    news:[email protected]..
    Hi, I have quick question about use of USEBEAN tag in SP2. When I
    specify a scope of SESSION for the java bean, it does not keep the
    values that I set for variable in the bean persistent.Thanks,Sonny
    Try our New Web Based Forum at http://softwareforum.sun.com
    Includes Access to our Product Knowledge Base!

  • Question about Java programming development

    There are five phases in java program development. They are: edit -> compile -> load -> verify -> execute
    However, every time I develops program. I only experience phase 1, phase 2 and phase 5. I always miss phase 3 and 4. When do the class loader and bytecode verifier work? How do they work?
    Second question, how the legitimate programs can execute automatically without typing command java to invoke the interpreter?

    lighthero wrote:
    I still have some questions.
    1. I want to run the program just like the commercial software such as Adobe and MS Office.(just double click to run the program.) How do I execute a java program without typing command java every time?Create an executable JAR: [http://java.sun.com/docs/books/tutorial/deployment/jar/index.html]
    >
    2. How does the JIT compiler work?[http://www.google.ca/search?q=Java+JIT]

  • Java Programming Questions

    I have taken a couple class in Java programming in just regular programming with GUI/console. I am looking to further my programming skills and wonder what course I need to take to become a java programmer for companies. I am confused on all this language in Java and there does not seem to be any reference to explain exactly what these technologies are. Example is.....What is J2EE? What is .JSP? Are they the same things? What environment is most commonly used in jobs? What about Java certifications?

    Here's the path tree to become a Java Programmer from Sun Microsystems:
    http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getlppage?page_id=212&path=SJPF
    There are other paths like Web Development and Databasing, so click around if you're interested in those. I think for a standard Java Programming job you will want the "Java Programming for Professionals - Sun Certified Java Programmer".
    However, most Jobs are specialized and require skills like JSP Development or Java Enterprise. Look around at a job search site and see what types of skills Java jobs are asking for.
    I've noticed, for example, that Java web jobs generally require: PHP, HTML, JSP, XML, SQL, etc.

  • Accessing oracle DB from a java program - question for oracle driver

    Hi,
    I have Oracle 10 G under vista on my desktop. I am trying to write a simple java program to access/update database tables. I saw in one of oracle example to import 2 packages - namely --- import oracle.jdbc.driver.*; import oracle.sql.*;
    Where do I find these 2 packages. Also I read some documentation to download drivers. I would like to use 2 drivers, the thin driver and the OCI driver. Can someone tell me where I can find these drivers and where do I copy these two drivers - so javac and java command can recognize it.
    I will greatly appreciate the help. Julia
    My program is as follows
    (It was working few years ago but things have changed now and I have Vista because my old machine died):
    import java.sql.*; // JDBC package
    //import com.inet.tds.JDBCRowSet;
    import java.util.*;
    import oracle.jdbc.driver.*;
    import oracle.sql.*;
    public class HomeDB
    run as follows:
    C:\Documents and Settings\MMM>cd \jj
    C:\john>set CLASSPATH=.;c:\oracle9i\classes12;%CLASSPATH%
    C:\john>javac HomeDB.java
    C:\john>java HomeDB
    King: 24000.0
    Kochhar: 17000.0
    De Haan: 17000.0
    Hunold: 9000.0
    Ernst: 6000.0
    Austin: 4800.0
    public static void main(String[] argv)throws SQLException
    Connection conn=null;
    try // may throw a SQLException
    conn = getConnection();
    doQuery (conn);
    catch (SQLException e)
    System.err.println(e.getErrorCode() + ": " + e.getMessage());
    finally // make sure the connection is closed
    if (conn != null) try {conn.close();} catch (SQLException e) {};
    //out.close(); // close PrintWriter stream
    private static Connection getConnection() throws SQLException
    String username = "scott";
    String password = "tiger";
    String url = "jdbc:oracle:thin:@localhost:1521:newora";
    // "jdbc:oracle:thin:@localhost:1521:COCKYJOB";
    Connection conn = null;
    String driver = "oracle.jdbc.driver.OracleDriver";
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    } catch ( ClassNotFoundException cnfex ) {
    System.err.println(
    "Failed to load JDBC/ODBC driver." );
    cnfex.printStackTrace();
    }catch (Exception e){
    e.printStackTrace();
    //DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    conn = java.sql.DriverManager.getConnection(url,username,password);
    conn.setAutoCommit(false);
    return conn;
    private static void doQuery (Connection c) throws SQLException
    // statement to be executed
    String query = "SELECT ename, job, mgr FROM EMP";
    Statement st = null;
    ResultSet rs = null;
    try // make sure the close statements are executed (in the finally block)
    // create the statement
    st = c.createStatement();
    // execute the query
    rs = st.executeQuery(query);
    // process results
    while (rs.next())
    // get the employee last name
    String eName = rs.getString("ename");
    String eJob = rs.getString("job");
    String eMgr = rs.getString("mgr");
    System.out.println("Emp Name:" + eName +
    "Job: " + eJob +
    "MGR: " + eMgr);
    finally // make sure the close statements are executed
    // close the result set if it exists
    if (rs != null) try {rs.close();} catch (Exception e) {};
    // close the statement if it exists
    if (st != null) try {st.close();} catch (Exception e) {};
    Edited by: user455788 on Dec 19, 2008 9:13 PM

    You can download the drivers from http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html.
    Note that oracle.jdbc.driver is desupported after 10.2, http://forums.oracle.com/forums/ann.jspa?annID=201, so you might want to consider using a DataSource to provide Connections.
    E.G.
    {message:id=2819114}

  • Need help with Java programming installation question

    Sorry for my lack of knowledge about Java programming, but:....
    A while back I thought I had updated my Java Runtime Environment programming. But I now apparently have two programs installed, perhaps through my not handling the installation properly. Those are:
    J2SE Runtime Environment 5.0 update 5.0 (a 118MB file)
    and:
    Java 2 Runtime Environment, SE v 1.4.2_05 (a 108MB file)
    Do I need both of these installed? If not, which should I uninstall?
    Or, should I just leave it alone, and not worry about it?
    Yeah, I don't have much in the way of technical knowledge...
    Any help or advice would be appreciated. Thank you.
    Bob VanHorst

    Thanks for the feedback. I think I'll do just that. Once in a while I have a problem with Java not bringing up a webcam shot, but when that happens, it seems to be more website based than a general condition.

  • Java program question

    how would i write a java program that takes as input the distance of the commute in miles, the automobiles fuel consumption rate in miles per gallon, and the price of a gallon of gas. this program should then after output the cost of the commute.

    how would i write a java program that takes as input
    the distance of the commute in miles, the automobiles
    fuel consumption rate in miles per gallon, and the
    price of a gallon of gas. this program should then
    after output the cost of the commute.The same way anyone else would do it.

  • Quick time not work with java programming

    I'm student and I want to use java .
    but it don't work with quick time .
    java can't run if I have quick time in my computer .
    (It works if I uninstall quick time)
    And how can I use iTunes without quicktime Or how can I
    fix that problem .
    Some one pls. HALP ME!!!!!
    Notebook   Windows XP Pro  

    Help Apple, Please!!!!
    I have still this problem!
    If I install QuickTime (7.0.3) all Java applications will not run.
    It works if I uninstall QuickTime...!
    Please help!
    Thanks

  • Java program HELPPPP!!!!!

    Hello, I'm very new to Java programming, and well I'm taking Computer Science as my major, and I need a little help to this program:
    You will develop an inheritance hierarchy of classes to enhance your understanding of inheritance, encapsulation, and polymorphism.
    All classes developed must be complete including:
    appropriate symbolic constants
    appropriate data fields
    constructors (default, complete, and, if appropriate, partial)
    accessor methods
    mutator methods
    standard methods inherited and overridden from Object:
    boolean equals(Object other)
    String toString()
    problem specific methods
    The project involves working with washers. A Washer is a circular metallic disc with its circular center removed. As such, the relevant data fields for a washer are:
    the outer diameter (OD) of the larger circle
    the inner diameter (ID) of the smaller circle
    the thickness of the disc
    When constructing or mutating these data fields remember that they need to be validated such that all fields are greater than zero and the outer diameter must be larger than the inner diameter (use helper methods for validation so that the code only appears once).
    In addition to the Washer class you will also need to define two derived classes based on the type of metal used for the washer. These will be BrassWasher and SteelWasher. Brass has a density of 8.4 g/cm3 while steel has a density of 7.8 g/cm3 (both of these numbers are approximate since both metals are alloys and their densities depend on the composition of the alloys). The densities should be defined as symbolic constants in the appropriate derived classes.
    The problem specific methods needed are:
    double volume()
    double weight()
    These should be placed in the appropriate classes.
    The main program (in class TestWashers) will create an array of Washer instances (generate reasonable values for the inner and outer diameters and thickness of the washers as well as the material types by using random numbers (see Math.random())) (discussed in class and look up the documentation). The program will then compute the total weight of the collection of washers as stored in the array. The program will display the list of washers (i.e., by using toString() for each array element) and then the total weight of the whole collection of washers (properly annotated).
    My question is what should I put in the Washer class? you know the parent class. Because I'm confuse on the boolean equals(object other) and String toString(), and the double volume and double weight.
    and how to do the Math.random()?
    This is the program that my teacher told us to do, but I'm having problems on how to start.
    Thanks.

    Please change your code tags. Even you must see that they aren't working.
    You can do this by changing your curly braces to square braces[code]
    Your code is still editable so you can do this without having to repost the whole thing.
    regarding toString: if you wanted a quick way to represent what data a Washer object contains, what would this one line string look like?  Model your toString() after this.
    regarding your equals: what object variables need to be all equal for two washers to be the same type?  Write an equals method to match that.  Note that equals must be passed an object as its parameter.  So the first thing you must do is check to make sure that the passed parameter object is in fact a Washer object (use instanceOf for this).  If not, return false.
    Edited by: Encephalopathic on Oct 1, 2008 7:28 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Quick Question **PLEASE HELP** .jar file?

    Hey everyone, im pretty new to the java scene but I have a really quick question that hopefully someone can help me with.
    I'm really interested in making a .jar file out of my code. And basically I just want to make one. but i understand there are certain things like main class's, etc. that need to be made in order to make a .jar file.
    So basically Say I opened up a new project in blueJ. I made 1 new class called "main." Inside of it I had nothing for conductors and no variables declaired untill the bottom part where i write my code.
    say i write...
    System.out.println("hello");
    and that is it.
    What steps from there do i do to make a jar file and have it be able to be executed and SEE the "hello" printed somewhere NOT in blueJ??
    (I understand there is something about a "static" method? Im not really sure but if somoene could enlighten me on how to make a .jar file that would be great.)
    Thanks a lot everyone!
    Tom

    I don't know anything about BlueJ, but this section of Sun's tutorial explains how to
    write a program that outputs a single line of text to the console:
    http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html
    Deploying an application as an executable .jar file is covered here:
    http://java.sun.com/docs/books/tutorial/deployment/jar/index.html
    The first two sections - "Using JAR Files: The Basics" and "Working with Manifest
    Files: The Basics" - contain the information you need to understand this process.

  • Run non-Java program inside a JFrame

    A quick question, would it be possible to run a non-java application inside a JFrame? By this, I mean restrict the program to be running only inside that frame.

    You could do some of what you need using the JAWT api:
    http://download.java.net/jdk6/docs/technotes/guides/awt/AWT_Native_Interface.html
    Thanks,
    Dmitri
    Java2D Team

Maybe you are looking for

  • Routine code

    Hello ALL ,        iam working in BW but i need to find out  the cause of error because of abap routine can please help me in understanding the code. iam having below routine between 2 ods(Tables) when i first load data from 1st ODS(Table) to second

  • Disk Utility restore on a RAID is extremely slow

    here is my story: i want to replace old internal 250gb hdd with 2х500gb striped raid set. i have 2 G5 Powermacs, so i put 2х500 in one of them and build striped raid. then i booted it in target disk mode and connected via firewire to other G5. other

  • Button's Text Doesn't Display The First Time

    Hi there. I'm new to flash, and have come across the following problem, and can't seem to resolve it. It's really urgent that it's fixed ASAP. Can someone help me please? If you go to www.apollosci.co.za, the flash intro, at the bottom. The tab's tex

  • Error deploying EJBs on Sun App Server

    Someone please help, I am getting a strange problem when deploying an EJB jar. I have had this code working before (before Xmas), but now I am getting the following error: java.lang.NoSuchMethodException: com.enterprise.entity.ContentBean.getId();Rem

  • Ranges in a class

    Hi, We need to buid  a range in a loop for some field. I declare the syntax as done in the report programe. But it throwing the error as the ranges cannt be used in class. Suggestion from system as use data type/like. Thanks in advance. Mohinder Sing