Basic Java Program

I just started my second Java course and my program has no compilation errors but doesn't run right.
First Class: class Star{
     String name;
     Star(){
//          name = "Star";
     public void setName(String name){
          this.name = name;
     public String getName() {
          return name;
}With my main class I declare an Star object as an array with different values, but during execution it only displays the last item i added into the array.
public class TestStar {
public static void main (String [] args) {
     Star [] array = new Star[10];
     for(int i =0; i<10; i++) {
          array[i] = new Star();
          array.setName("The Sun");
          array[i].setName("Polaris");
          array[i].setName("Sagittarius");
          array[i].setName("Pisces");
          array[i].setName("Pegasus");
          array[i].setName("Orion");
          array[i].setName("Omega");
          array[i].setName("Draco Sigma");
          array[i].setName("Chamaeleon");
          array[i].setName("Aquarius");
          System.out.println(array[i].getName());
}My professor couldn't even help, (which scares me) but I believe I only have a small error since it still prints on 10 items but only the last item I added to the array.
Any insight on how to fix this will be much appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

but during execution it only displays the last item i added into the array.No, you're setting every star in the array with the name "Aquarius". Each time through the loop, you create a Star object, rename that same star with a bunch of different values, finally ending up with "Aquarius". Here is one possible way to fix it: public class TestStar {
    public static void main (String [] args) {
        String[] starNames = {
            "The Sun",
            "Polaris",
            "Sagittarius",
            "Pisces",
            "Pegasus",
            "Orion",
            "Omega",
            "Draco Sigma",
            "Chamaeleon",
            "Aquarius"};
        Star[] array = new Star[starNames.length];
        for(int i = 0; i < starNames.length; i++) {
            array[i] = new Star();
            array.setName(starNames[i]);
System.out.println(array[i].getName());
}~                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Basic Java Program help needed urgently.

    I have posted the instructions to my project assignment on here that is due tomorrow. I have spent an extremely large amount of time trying to get the basics of programming and am having some difficulty off of the bat. Someone who has more experience with this and could walk me through the steps is what I am hoping for. Any Help however will be greatly appreciated. I am putting in a lot of effort, but I am not getting the results I need. Thank you for the consideration of assisting me with my issues. If you have any questions please feel free to ask. I would love to open up a dialogue.
    CIS 120
    Mathematical Operators
    Project-1
    Max possible pts 100
    Write a program “MathOperators” that reads two integers, displays user’s name, sum, product,
    difference, quotients and modulus of the two numbers.
    1. Create a header for your project as follows:
    * Prgrammer: Your Name (1 pt) *
    * Class: CIS 120 (1 pt) *
    * Section: (1 pt) *
    * Instructor: (1 pt) *
    * Program Name: Mathematical Operators (1 pt) *
    * Description: This java program will ask the user to enter two integers and *
    display sum, product, difference, quotients and modulus of the two numbers
    * (5 pts) *
    2. Display a friendly message e.g. Good Morning!! (2 pts)
    3. Explain your program to the user e.g. This java program can add, subtract, multiply,
    divide and calculate remainder of any two integer numbers entered by you. Let’s get
    started…. (5 pts)
    4. Prompt the user- Please enter your first name, store the value entered by user in a
    string variable name. Use input.next() instead of input.nextLine(). (8 pts)
    5. Prompt the user- name, enter first integer number , store the value entered by user in
    an integer variable num1.(5 pts)
    6. Prompt the user- name, enter second integer number , store the value entered by user in
    an integer variable num2.(5 pts)
    7. Display the numbers entered by the user as: name has entered the numbers num1and
    num2.(5 pts)
    8. Calculate sum, product, difference, quotients and modulus of the two numbers. ( 30 pts)
    9. Display sum, product, difference, quotients and modulus of the two numbers. ( 10 pts)
    10. Terminate your program with a friendly message like- Thanks for using my program,
    have a nice day!!(2 pts)

    Nice try. You have not demonstrated that you've at least TRIED to do something. No one is going to do your homework for you. Your "urgency" is yours alone.

  • Basic Java programs.....Please read

    I just need some links to where i can dowload some some basic toolboxes and kits. (to make basic programs and practice)
    Please porvide links, i've been searching. Since I'm so unfamiliar with Java programming i haven't has much luck.

    JSE 1.5 download: http://java.sun.com/javase/downloads/index.jsp
    vim download: http://www.vim.org/download.php
    kind regards,
    Jos

  • O Dear! Basic Java Programming problem!

    import java.lang.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import java.util.Random;
    public class QuizApp extends Object
         public static void main(String[] argStrings) throws Exception
              Random random = new Random();
              int generateFirstFigure = random.nextInt(21);
              int generateSecondFigure = random.nextInt(31);
              int generateOperator = random.nextInt(3);
              String operator = "/";
              int correctAnswer = generateFirstFigure + generateSecondFigure;
              if (generateOperator == 0)
                   operator = "+";
                   int correctAnswer = generateFirstFigure + generateSecondFigure;
              if (generateOperator == 1)
                   operator = "-";
                   int correctAnswer = generateFirstFigure - generateSecondFigure;
              if (generateOperator == 2)
                   operator = "/";
                   int correctAnswer = generateFirstFigure / generateSecondFigure;
              //int correctAnswer = generateFirstFigure + operator + generateSecondFigure;
              int incorrectAnswerOne = correctAnswer -2;
              int incorrectAnswerTwo = correctAnswer + 1;
              int incorrectAnswerThree = correctAnswer + 3;
              String questionOne = "What is " + generateFirstFigure + operator + generateSecondFigure + "?"; 
              System.out.println(questionOne);
              System.out.println(incorrectAnswerThree);
              System.out.println(incorrectAnswerOne);
              System.out.println(correctAnswer);
              System.out.println(incorrectAnswerTwo);
    }Basically this code, creates 2 random characters and then allows you to either add, divide or subtract the two numbers... firstly this bit of the code doesnt work, secondly how can the user input a value (the answer) to the math's question?
    Thanks for help,
    Joel

    practissum wrote:
    dketcham, i printed out your hello world pumpkin. its a huge hit in the office!Sorry for propogating the off-topic remarks...but link to the hello world pumpkin?it was the friday coding challenge for last week:
    http://forum.java.sun.com/thread.jspa?threadID=5230548&messageID=9941964#9941964
    It's all about the pretty colors, and trying to squish a simple little program into a squarish-shape, so that another shape can be put within!
    As you can see, I have no real programming skills, but I like pretty colors, so it's all good.

  • Basic java program wont quit

    I'm in a java class and I'm stuck on this issue. I cant figure out where I went wrong. Any help will be most welcome. I found two examples on how to do this. I used a little from both in order to make mine. The program is suppose to loop back and mine does however when I press Q or q to quit I get a few errors. Below is my code. Thanks
    http://pastebin.com/T74XC07D

    import java.util.*;
    public class xxxxxx
        public static void main(String[] args)
            System.out.println("PHONE NUMBER DISSECTOR");
            displayQuestion();
            getNumber();
         public static void displayQuestion()
              System.out.println();
            System.out.println("Enter a phone number in the form cc-area-local,");
            System.out.println("where cc = country code digits, area = area code digits,");
            System.out.println("and local = local phone digits.");
            System.out.print("Or enter q to quit:");
            getNumber();
         public static void getNumber()
            Scanner scan = new Scanner(System.in);
            String strChoice = scan.next(); //gets the users input for program
            String countryCode, areaCode, phoneNum;  //Phone Number vars cc,area,local
            String[] phoneNumber = strChoice.split("-"); //searches for "-"
             if (!strChoice.equals("q") && !strChoice.equals("Q"));
                countryCode = phoneNumber[0];
                areaCode = phoneNumber[1];
                phoneNum = phoneNumber[2];
                System.out.println("");
                System.out.println("country code = " + countryCode);
                System.out.println("area code = " + areaCode);
                System.out.println("local phone number = " + phoneNum);
                System.out.ptintln("Press any key to contine.");
              else if (!strChoice.equals (""));
                       System.out.println();
                        System.out.println("Enter a phone number in the form cc-area-local,");
                        System.out.println("where cc = country code digits, area = area code digits,");
                        System.out.println("and local = local phone digits.");
                        System.out.print("Or enter q to quit:");
                      getNumber();
            System.exit(1);
    }C:\jdk6\bin>javac -g xxxxxx.java
    xxxxxx.java:35: 'else' without 'if'
    else if (!strChoice.equals (""));
    ^
    Edited by: RadarG on Apr 18, 2010 1:27 AM

  • Need help with basic Java programming

    I'm having a little bit of trouble with my code. For the sake of argument, I've removed the code I'm having trouble with, because I know it was inaccurate. I'm trying to create a loop so that this program will keep going through and through until the user enters an invalid variable. I thought the default after the case statements was supposed to make the system exit and output my message. Those two problems, the loop and the default, are what I'm really having problems with. My code is posted below.
    import javax.swing.JOptionPane;
    import java.util.Locale;
    import java.text.NumberFormat;
    public class Retail
    public static void main(String args[])
    String firstNum;
    String secondNum;
    String result;
    int prodNum;      //first number to input
    double quantity; //second number to input
    double total = 0.0;     //total of Prod * Quantity Sold for all items
    // To use American Dollar
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
    // first number entered as string
    firstNum = JOptionPane.showInputDialog( "Enter product number 1-5" );
    // second number entered as string
    secondNum = JOptionPane.showInputDialog( " Enter quantity of items sold" );
    // convert values to type double or int from type string
    prodNum = Integer.parseInt( firstNum );
    quantity = Double.parseDouble( secondNum);
    result="";
    if ( prodNum >=1 && prodNum <=5 ) {
    switch (prodNum)
    case 1: // 1st product
    total = 2.98 * quantity;
    break;
    case 2: // 2nd product
    total = 4.50 * quantity;
    break;
    case 3: // 3rd product
    total = 9.98 * quantity;
    break;
    case 4: //4th product
    total = 4.49 * quantity;
    break;
    case 5:
    total = 6.87 * quantity;
    break;
    default: JOptionPane.showMessageDialog( null, "Wrong product number entered" );
    JOptionPane.showMessageDialog( null, moneyFormat.format(total), "Total Price of Items Purchased", JOptionPane.INFORMATION_MESSAGE );
    System.exit(0);
    ***I know I need to put something in the user input message to state that any value other than 1-5 entered will cause the program to skip to the output, I'll put that in later.***

    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].

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

  • Knight tour programming with only basic java

    i had this assignment from school which ask us to create a program to calculate how many posssibilities to complete knight's tour from a position using basic java and not using applet. So far i can only create an incomplete program which can only go a speccific way and is also incomplete. i am trying to understand the jaava applet type of knight tour program but got too confused as i have just started learning this. Please help me with this.
    here's my code:
    public class uk16638_a3{
         public static void main(String[] args){
         int horizontal[] = {2,1,-1,-2,-2,-1,1,2};
         int vertical[] = {-1,-2,-2,-1,1,2,2,1};
         int chessBoard[][]=new int[8][8];
         int move, currentRow = 0, currentCol= 0, move_count = 0, new_vert, new_horz;
    for(int i=0; i<8; i++)
         for(int j =0; j<8; j++)
              chessBoard[i][j] = 0;
    chessBoard[0][0] = 1;
    do{
    for(move=0;move<8;move++){
    new_vert = currentRow + vertical[move];
    new_horz = currentCol + horizontal[move];
    if ( (new_vert>=0) && (new_vert < 8) )
    if( (new_horz>=0) && (new_horz < 8) )
    if( chessBoard[new_horz][new_vert]==0 ) {
    chessBoard[new_horz][new_vert] = 1;
    move_count++;
    currentRow = new_vert;
    currentCol = new_horz;
    }}}while(move<8);}}

    Sorry with the inconvenience cause i am new with this forum so i am causing many problems to all of you. here's the full code i put but i would really like to ask someone to teach me on creating a backtrack and let the knight moves following a different sequence from the one i already set.
    public class uk16638_a3{
    public static void main(String[] args){
    //the movements of a knight horizontally and vertically
    int horizontal[] = {2,1,-1,-2,-2,-1,1,2};
    int vertical[] = {-1,-2,-2,-1,1,2,2,1};
    int chessBoard[][]=new int[8][8];
    int move, currentRow = 0, currentCol= 0, move_count = 0, new_vert, new_horz;
    //setting all elements in the array to 0
    for(int i=0; i<8; i++)
    for(int j =0; j<8; j++)
    chessBoard[i][j] = 0;
    //the knight starts here
    chessBoard[0][0] = 1;
    //using do while loop, i try to move the knight following the sequence i had already set in the array above. But because its moving at the same direction all the time, it gets stuck.
    do{
    for(move=0;move<8;move++){
    //setting the new coordinates for it to move to
    new_vert = currentRow + vertical[move];
    new_horz = currentCol + horizontal[move];
    if ( (new_vert>=0) && (new_vert < 8) )
    if( (new_horz>=0) && (new_horz < 8) )
    //new position check if its already occupied or not, if occupied it will move on to the next part of the move sequence i set
    if( chessBoard[new_horz][new_vert]==0 ) {
    chessBoard[new_horz][new_vert] = 1;
    move_count++;
    //current coordinate of the new knight position
    currentRow = new_vert;
    currentCol = new_horz;
    }}}while(move<8);}}
    Edited by: Mikki88 on Mar 2, 2009 1:53 AM

  • Run Basic Command-line Java Programs in Sandvox

    Is it possible to put a command-line Java program on a website in Sandvox and make it run?

    See: documentation for designers

  • Getting java program to run (really basic)

    Hi,
    I'm used to running java programs through the programs I write with, like Eclipse, but now I'm trying to run a program on a compuyer without those things and I'm stuck.
    I'm running Windows XP and have downloaded the SDK Version 1.4.2, The java.com website says I have the latest software, everything is up to date.
    All the sites I see say that the way to run a program is to use the 'javac' command from the command prompt. However, doing this (with or without a file name appended) gives me the error: 'javac is not recognized as an internal or external command, operatable program or batch file.'
    What do I need to do to run a simple java program from a bunch of .java files?
    Help much appreciated, thanks.

    All which instuructions?
    1. I've followed all the instructions at 'Installation Instructions', http://www.java.com/en/download/help/5000010300.xml. They have instructions to
    .A: Download and Install: All done.
    .B: Enable and Configure: They say it only relates to browsers and applets
    .C: Test installation: Test comes out positive.
    2. The files that were downloaded: Contain no instructions
    3. All the 'Enable' instructions found here: http://www.java.com/en/download/help/index_configuration.xml
    These relate to:
    .A:Switching between Microsoft VM and JRE
    .B:Enabling JRE for browsers and Applets
    .C: Clearing the cache
    .D: Viewing the console,
    etc etc. None of them seem to be about setting a path.
    Can you tell me which instructions you mean?
    Thanks

  • Running a java program a set number of times

    This is a general question. Is it possible to make a java program run only 5 times for the sake of arguement.
    Basically I want to write a program that will give the user some flexibility when it will actually run another Java program, but I only want them to be able to say "not now' for a set number of times. When the last time comes the other program will launch. I was initially thinking of the Do Whilw loop, but this needs to work when the program is restarted.
    Program starts, it has 5 times it will run before it does something else(doesn't really matter now I think). User takes option "Not Now" and the program ends, but warns the user this will run 4 more times before you will need to do something.
    This process will repeat until the user takes the option "Ok install now" or the time limit expires and the install occurs anyway. Can someone point me in the right direction.

    ok I see so it's like one those programs that you download for free on the internet and they give you a set amount times to use it before you have to pay for it. but in this case when the number of times you use it equals 5 (or when the user clicks ok) a different java app will open automatically.
    My first thought would be to Write a Serialized object to disk using objectOutputStream that stores the number of times the application has been opened. and each time the program runs it checks for the serialized object and then you can do something like what I posted before. of course if were worried about security the user could always look for the object and erase it, if so then I guess we would have to come up with another plan of attack
    Hope this helps

  • 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

  • Java program not updating in correct sequence in applet

    Greetings,
    I have a java program with interactive graphic components. After completely writing the program, I create two shells ( or handle): an application shell with JFrame and an applet shell with JApplet. The application version of the program works fine. But the applet version skips some (middle) steps in the painting process when responding to user inputs.
    Does anyone have any ideas as to what's going on?
    I am not able to embed code snippets because my Internet has not being working and am finger typing this on my cellphone.
    Thanks for any help.

    My cable person won't come before Monday so I am struggling for now. Thanks for the replies, though.
    More info:
    1) both shells are extremely basic. They both simply add the drawing panel like so:
    DrawingPane drawingPanel = new DrawingPanel();
    add(drawingPanel);//frame.add for application
    the application uses statc main; the applet uses init. Nothing more.
    2) the program paints the hands and fingers of a stick figure red or green dependring on which foot of the figure is clicked.
    3) the application version works completely
    4) the applet version updates the right hand the first time; but not on subsequent clicks. More mysteriously, although it skips the hand, it still go on to update the fingers.
    5) No I don't know about event threads yet.
    Thanks.

  • Is it possible to run a java program without using the command prompt?

    Hi,
    I was wondering whether it is possible to run a Java program (not an applet) without using a command line in the command prompt?
    Basically I want to run a program that will be continually running in the background and hence I don't want to have a command prompt screen loaded up as well - I just want the program to be running in the task bar.
    I know how to run the program in the task bar - but I still need to launch the program from the command prompt - is there anyway I can get a program running without having to start it from the command prompt?
    Cheers

    Or create a desktop shortcut (in Windows) or an application launcher ( in Linux GUI).

  • How to run a Java program

    Ok, well I'm new to the world of Java and am excited to learn. I know C++ pretty well and I think that is what is kinda confusing me right now. When I made a simple "Hello world" app and tryed to run it nothing happens. I double clicked on the class file. What I really what to know it how to set up and run a basic application how anyone would. It's a little differnt than just compiling and running an .exe and I think that is what is kinda confusing me as I said before.

    Very basic bare bones:
    javac MyClass.java
    java MyClass
    Details:
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.

Maybe you are looking for

  • MacBook Pro won't turn on and it won't charge

    My MacBook has been working fine and has been charging until now. I left my laptop in without it being plugged in and I presume the laptop died when it ran out of battery. I plugged my charger into laptop but I noticed that there was no charging ligh

  • How to change pounds to dollars

    I live in the UK but I am from the US, and I have to create an invoice, but it sets everything to pounds. I can not find out how to set it to dollars, is there a way without have to change the setting for the computer location? Thanks for the help, D

  • No mail flow Public folders

    Hi. I'm migrate to Exchange 2013. I moved mailbox, moved public folders ( 20 folders in one pf-mailbox). I can see structure public folders, but when i send mail to public folders, i see error: this recepient not found Формирующий сервер: EXCHANGE201

  • Opening logic 8 songs help!!

    My mate has recorded a song using Logic 8 Studio and sent me the disk. My problem is that I can't seem to open it. I have all the audio files but as there is no .iso file it won't open. The data arrange files that come with it don't want to associate

  • How to create a Subtype?

    Hi All, I want to know the steps required to create the Subtypes for my Infotype as i need to create some extra feilds also in the already existing infotype? Thanks Regards, Nidhi