Java newbie (what's could be wrong with this program?)

First things first, I just started programming with JAVA recently so please forgive me if it seems stupid. Since I am so relatively new to the language, in order to get a feel for it I started running some simple scripts. I can compile and execute most of them without any problem. However when I tried to compile this one I get a couple of errors I am not familiar with. So my question is what could be wrong and what needs to be changed in order to get it to work? or if the syntax is correct could there be some other problem?
On a side note, I am coming more from a C and C++ background so if anyone can recommend a way to start learning the JAVA language from a prespective in C that would be highly appreciated.
System Environment: I am using j2sdk1.4.2 on a Windows 2000 machine running SP3.
If anything else needs further clarification please let me know.
|------------------------- The Code -----------------------------------|
package RockPaperScissors;
import java.util.HashMap;
public class RockPaperScissors {
String[] weapons = {"Rock", "Paper", "Scissors"};
EasyIn easy = new EasyIn();
HashMap winners = new HashMap();
String playerWeapon;
String cpuWeapon;
int cpuScore = 0;
int playerScore = 0;
public static void main(String[] args) {
RockPaperScissors rps = new RockPaperScissors();
boolean quit = false;
while (quit == false) {
rps.playerWeapon = rps.getPlayerWeapon();
rps.cpuWeapon = rps.getCpuWeapon();
System.out.println("\nYou chose: " + rps.playerWeapon);
System.out.println("The computer chose: " + rps.cpuWeapon + "\n");
rps.getWinner(rps.cpuWeapon, rps.playerWeapon);
if (rps.playAgain() == false) {
quit = true;
System.out.println("Bye!");
public RockPaperScissors() {
String rock = "Rock";
String paper = "Paper";
String scissors = "Scissors";
winners.put(rock, scissors);
winners.put(scissors, paper);
winners.put(paper, rock);
System.out.println("\n\t\tWelcome to Rock-Paper-Scissors!\n");
public String getPlayerWeapon() {
int choice = 6;
String weapon = null;
System.out.println("\nPlease Choose your Weapon: \n");
System.out.println("1. Rock \n2. Paper \n3. Scissors \n\n0. Quit");
try {
choice = easy.readInt();
} catch (Exception e) {
errorMsg();
return getPlayerWeapon();
if (choice == 0) {
System.out.println("Quitting...");
System.exit(0);
} else {
try {
weapon = weapons[(choice - 1)];
} catch (IndexOutOfBoundsException e) {
errorMsg();
return getPlayerWeapon();
return weapon;
public void errorMsg() {
System.out.println("\nInvalid Entry.");
System.out.println("Please Select Again...\n\n");
public String getCpuWeapon() {
int rounded = -1;
while (rounded < 0 || rounded > 2) {
double randomNum = Math.random();
rounded = Math.round(3 * (float)(randomNum));
return weapons[rounded];
public void getWinner(String cpuWeapon, String playerWeapon) {
if (cpuWeapon == playerWeapon) {
System.out.println("Tie!\n");
} else if (winners.get(cpuWeapon) == playerWeapon) {
System.out.println("Computer Wins!\n");
cpuScore++;
} else if (winners.get(playerWeapon) == cpuWeapon) {
System.out.println("You Win!\n");
playerScore++;
public boolean playAgain() {
printScore();
System.out.print("\nPlay Again (y/n)? ");
char answer = easy.readChar();
while (true) {
if (Character.toUpperCase(answer) == 'Y') {
return true;
} else if (Character.toUpperCase(answer) == 'N') {
return false;
} else {
errorMsg();
return playAgain();
public void printScore() {
System.out.println("Current Score:");
System.out.println("Player: " + playerScore);
System.out.println("Computer: " + cpuScore);
|------------------------- Compiler Output ----------------------------|
C:\ide-xxxname\sampledir\RockPaperScissors>javac RockPaperScissors.java
RockPaperScissors.java:8: cannot resolve symbol
symbol : class EasyIn
location: class RockPaperScissors
EasyIn easy = new EasyIn();
^
RockPaperScissors.java:8: cannot resolve symbol
symbol : class EasyIn
location: class RockPaperScissors
EasyIn easy = new EasyIn();
^
2 errors

limeybrit9,
This importing certainly seems to be the problem, I'm still not used to how compilation works within the JAVA language, I'll play around with it a bit and see if I can get it to work correctly.
bschauwe,
The C++ approach has certainly clarified some of the points. I guess I will be sticking to that.
bsampieri,
You were correct on the class looking rather generic, but as I mentioned before I was just sort of tinkering to see if I could get it to work.
Thanks to all for the help, very much appreciated.

Similar Messages

  • What am i doing wrong with this class please help

    What am i doing wrong with this class? I'm trying to create a JFrame with a JTextArea and a ScrollPane so that text can be inserted into the text area. however evertime i run the program i cannot see the textarea but only the scrollpane. please help.
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Instructions extends JFrame{
    public JTextArea textArea;
    private String s;
    private JScrollPane scrollPane;
    public Instructions(){
    super();
    textArea = new JTextArea();
    s = "Select a station and then\nadd\n";
    textArea.append(s);
    textArea.setEditable(true);
    scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    this.getContentPane().add(textArea);
    this.getContentPane().add(scrollPane);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("Instructions");
    this.setSize(400,400);
    this.setVisible(true);
    }//end constructor
    public static void main(String args[]){
    new Instructions();
    }//end class

    I'm just winging this so it might be wrong:
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Instructions extends JFrame{
    public JTextArea textArea;
    private String s;
    private JScrollPane scrollPane;
    public Instructions(){
    super();
    textArea = new JTextArea();
    s = "Select a station and then\nadd\n";
    textArea.append(s);
    textArea.setEditable(true);
    scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    // Here you already have textArea in scrollPane so no need to put it in
    // content pane, just put scrollPane in ContentPane.
    // think of it as containers within containers
    // when you try to put them both in at ContentPane level it will use
    // it's layout manager to put them in there side by side or something
    // so just leave this out this.getContentPane().add(textArea);
    this.getContentPane().add(scrollPane);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("Instructions");
    this.setSize(400,400);
    this.setVisible(true);
    }//end constructor
    public static void main(String args[]){
    new Instructions();
    }//end class

  • Does ANYONE know whats wrong with this program?!?!

    Hey(again),
    Does anyone know whats wrong with this program?:
    public class FloatingNumbersTest
    public static void main(String args[])
    float float1 =50.0f;
    float closeFloat=0.001f
    float farfloat=100.0f
    if (float1<=closeFloat)
    System.out.print("Float1 pretty close to zero");
    if (float1>=closeFloat)
    System.out.print("Float1 is near 0");
    if (float1>=farfloat)
    System.out.print("Float1 is not even close to zero!"0
    }There has seemed to be 5 errors!

    public class FloatingNumbersTest
    public static void main(String args[])
    float float1 =50.0f;
    float closeFloat=0.001f
    float farfloat=100.0f
    if (float1<=closeFloat)
    HERE        System.out.print("Float1 pretty close to zero");
    if (float1>=closeFloat)
    System.out.print("Float1 is near 0");
    if (float1>=farfloat)
    System.out.print("Float1 is not even close to zero!"0
    }you're missing the opening { for the first if.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • What could be wrong with this SuperCluster server?

    Kindly assist, what could be wrong with the super cluster server logs below, it comes up and down. Although as we speak, it is currently up and running now:
    root@ssc0101-mgmt-app1 # zpool status -x
      pool: emagine1
    state: UNAVAIL
    status: One or more devices could not be opened.  There are insufficient
    replicas for the pool to continue functioning.
    action: Attach the missing device and online it using 'zpool online'.
       see: http://www.sun.com/msg/ZFS-8000-3C
    scan: none requested
    config:
    NAME STATE     READ WRITE CKSUM
    emagine1 UNAVAIL      0     0 0  insufficient replicas
    /zonedev/emagine1/zonepool  UNAVAIL 0     0     0  cannot open
    root@ssc0101-mgmt-app1 # iostat -En
    c1t5000C5004382C93Fd0 Soft Errors: 0 Hard Errors: 0 Transport Errors: 0
    Vendor: SEAGATE  Product: ST960005SSUN600G Revision: 0606 Serial No: 1141P17W1H
    Size: 600.13GB <600127266816 bytes>
    Media Error: 0 Device Not Ready: 0 No Device: 0 Recoverable: 0
    Illegal Request: 0 Predictive Failure Analysis: 0
    c1t5000C500436A6673d0 Soft Errors: 0 Hard Errors: 0 Transport Errors: 0
    Vendor: SEAGATE  Product: ST960005SSUN600G Revision: 0606 Serial No: 1141P1DVT9
    Size: 600.13GB <600127266816 bytes>
    Media Error: 0 Device Not Ready: 0 No Device: 0 Recoverable: 0
    Illegal Request: 0 Predictive Failure Analysis: 0
    c1t50015179596974EDd0 Soft Errors: 0 Hard Errors: 0 Transport Errors: 0
    Vendor: ATA      Product: INTEL SSDSA2BZ30 Revision: 0362 Serial No:
    Size: 300.07GB <300069052416 bytes>
    Media Error: 0 Device Not Ready: 0 No Device: 0 Recoverable: 0
    Illegal Request: 1 Predictive Failure Analysis: 0
    c1t500151795966AFCBd0 Soft Errors: 0 Hard Errors: 0 Transport Errors: 0
    Vendor: ATA      Product: INTEL SSDSA2BZ30 Revision: 0362 Serial No:
    Size: 300.07GB <300069052416 bytes>
    Media Error: 0 Device Not Ready: 0 No Device: 0 Recoverable: 0
    Illegal Request: 1 Predictive Failure Analysis: 0
    root@ssc0101-mgmt-app1 # zpool clear emagine1
    root@ssc0101-mgmt-app1 #
    SUNW-MSG-ID: FMD-8000-4M, TYPE: Repair, VER: 1, SEVERITY: Minor
    EVENT-TIME: Tue Nov 13 18:22:27 WAT 2012
    PLATFORM: ORCL,SPARC-T4-4, CSN: -, HOSTNAME: ssc0101-mgmt-app1
    SOURCE: zfs-diagnosis, REV: 1.0
    EVENT-ID: 6e103a73-e131-4abd-eeab-cacd1b658dce
    DESC: All faults associated with an event id have been addressed.
      Refer to http://sun.com/msg/FMD-8000-4M for more information.
    AUTO-RESPONSE: Some system components offlined because of the original fault may have been brought back online.
    IMPACT: Performance degradation of the system due to the original fault may have been recovered.
    REC-ACTION: Use fmdump -v -u <EVENT-ID> to identify the repaired components.
    SUNW-MSG-ID: FMD-8000-6U, TYPE: Resolved, VER: 1, SEVERITY: Minor
    EVENT-TIME: Tue Nov 13 18:22:27 WAT 2012
    PLATFORM: ORCL,SPARC-T4-4, CSN: -, HOSTNAME: ssc0101-mgmt-app1
    SOURCE: zfs-diagnosis, REV: 1.0
    EVENT-ID: 6e103a73-e131-4abd-eeab-cacd1b658dce
    DESC: All faults associated with an event id have been addressed.
      Refer to http://sun.com/msg/FMD-8000-6U for more information.
    AUTO-RESPONSE: All system components offlined because of the original fault have been brought back online.
    IMPACT: Performance degradation of the system due to the original fault has been recovered.
    REC-ACTION: Use fmdump -v -u <EVENT-ID> to identify the repaired components.
    Thanks in advance for your support.

    Let's check the details of the fault. We can run the fmdump command to get the details. Run the following command and post the output.
    fmdump -v -u 6e103a73-e131-4abd-eeab-cacd1b658dce
    thanks
    Erik

  • What the he** is wrong with this code?

    Hi,
    I have 2 tables. Primary table "resease" and secondary table (containing the foreign key) "kunden".
    Selecting a release (dropdownlist), will show you the corresponding entry of kunden (datatable).
    I added buttons to the datatable for deleting certain rows. This all works fine so far.
    But as you are going to delte the last entry of table kunden, I want to delte the corresponding entry of the table release as well. And by trying to do so, I get an exception telling in line "dataTable1Model.commit();"
    "java.sql.SQLException: Lock time out; try later."
    The exception disappears by deleting the inner try-catch block.
    So what is wrong with this code?
    Thank,
    Mark.
    PS: If you need the database-schema or anything else, let me know....
    public String delete_action() {
            try {
             //returns -1, so I can't use it     
                int rowCount = dataTable1Model.getRowCount();          
             //get affected row     
                com.sun.jsfcl.data.DataCache.Row row =
                dataTable1Model.getDataCache().get(dataTable1Model.getRowIndex());
                row.setDeleted(true);
                try {
                    //New RowSet for getting FK of affected line
                    JdbcRowSetXImpl pkRowSet = new JdbcRowSetXImpl();
                    pkRowSet.setDataSourceName("java:comp/env/jdbc/AVT");
                    pkRowSet.setCommand("SELECT fk_idrelease FROM kunden " +
                    "where fk_idrelease = ?");
                    //Convert Row into string
                    String myRow = row.toString();
                    //Getting the index of the first "=" (it's before the FK)
                    int index = myRow.indexOf("=")+1;
                    //Getting the number (FK) out of the string an casting it to int
                    int fk = Integer.parseInt(myRow.substring(index,(index+1)));
                    //Saving the FK in SessionBean1, so I can use it a parameter of
              //the setObject(int, Object)-method
                    getSessionBean1().setFk(fk);
                    //this will give me a RowSet of all lines containing the FK of
              //the affected row
              pkRowSet.setObject(1, getSessionBean1().getFk());
                    pkRowSet.execute();
                    pkRowSet.last();
                    int numRow = pkRowSet.getRow();
              //If the numRow (numbers of rows) is 1, go to cascade_delte
              //and delte the entry with primary key as well
                    if (numRow == 1) {
                        cascade_delete(); //not implemented yet
                }catch (Exception ex) {
                    error("Error counting affected rows: " + ex);
                dataTable1Model.commit();
                dataTable1Model.execute();
                info("Deleting row OK!");
            }catch (Exception e) {
                log("Page 1: Row delete exception: ", e);
                error("Error during deleting: " + e);
            } // end try catch
          return null;
        }

    just a guess - perhaps call pkRowSet.close() at the end of your try/catch?
    v

  • Help with Note cards?? I thought I could do them with this program...

    Help! I purchased Adobe Photoshop Elements 12 back in September, but due to computer problems and working on other projects, I just got started using it. Or at least I'm trying to!
    My main (read: pretty well ONLY) reason for purchasing was that I thought I could make note cards (photo on front, folded, like a blank card, but with one of my photos on the front) for personal use and Christmas gift for my aunt who writes a lot of notes. I really wanted to create a special gift for her, as well as unique cards for my own use.
    But when I open the program and click "Create" all I see is Greeting Cards! And when I click on it, I don't see anything like what I want to create! Help! Is there any way to create this type of card with this program? Or at least close? I would really appreciate ANY and ALL help!!!
    Thanks!

    Hi,
    You can try going to finder, hitting CMD + F and below search this mac, you should see kind. You can try switching that contents and the second option to documents.
    Hope this helps,
    Zevie

  • What am I doing wrong with this filter (counter/frequency issue), probably another newb question.

    I extracted the part of my VI that applies here.  I have a 6602 DAQ board reading a counter for frequency, using a Cherry Corp proximity sensor.  Getting a lot of noise and errant ridiculously high readings.  Speed of shaft which it's measuring is currently 2400rpm with one pulse per revolution so 40hz. 
    Trying to use the express filter VI to clean up the signal and ignore anything over, say, 45hz and under 35hz.  No matter what setting I choose I continually get the  20020 error, Analysis:  The cut-off frequency, fc, must meet:  0 <= fc <= fs/2.  I know this relates to sample period somehow, but for the life of me I can't understand what I'm doing wrong. 
    I used this VI without filtering on bench tests with a hand-drill and got perfect output every time.  Now it's on the machine and being erratic.  Any help here will ease my stress level significantly, thanks.
    VI attached
    Still confused after 8 years.
    Attachments:
    RPM.vi ‏92 KB

    Hello Ralph,
    I'm not sure about mounting your sensor to your rig, but I can provide a couple ideas about the filtering. Depending on the type of noise, the digital filters on the PCI-6602 could help eliminate the behavior you are seeing. If the noise manifests as a "glitches" or a bouncing signal, you could use another counter with a minimum period to help eliminate the noise. This concept is discussed in greater detail in this KnowledgeBase. I noticed that you are using NI-DAQmx; the practical application of the digital filters on the PCI-6602 in NI-DAQmx is discussed in this KnowledgeBase. A more detailed description of the behavior of these filters is provided in the NI-DAQmx Help (Start>>All Programs>>National Instruments>>NI-DAQ) in the book entitled "Digital Filtering Considerations for TIO-Based Devices".
    I also wanted to comment on your original post and explain why you were receiving error -20020. For convenience, I have copied the text of the error code below.
    Error -20020 occurred at an unidentified location
    Possible reason(s):
    Analysis:  The cut-off frequency, fc, must meet:  0 <= fc <= fs/2.
    I think you may have misunderstood exactly what the Filter express VI does. The Filter express VI takes a series of values in a waveform and performs filtering on those signals. So, it will look at a waveform made up of X and Y values and apply the defined filter to this waveform. Specifically in your application, the cut-off frequency (fc) is the Upper Cut-Off level that you specified in the Filter express VI; any frequency components of the waveform outside of the range you have defined will be filtered. The fs is the sample rate based on the data that you wire to the Signal input of the Filter express VI. In your VI, this data is coming from the DAQ Assistant. So, fs will be the sample rate of the DAQ Assistant and is associated with the rate at which points are acquired. The sample rate does NOT relate to the bandwidth of the signal, except that the Nyquist theorem tells us that the sample rate must be at least twice the signal bandwidth in order to determine periodicity of the signal. So, in this case, the sample rate of the DAQ Assistant would need to be at least double the high cut-off frequency.
    However, you are performing a frequency measurement using a counter. I think this is where the confusion comes in. For the frequency measurement using a counter, the DAQ Assistant returns a decimal value which represents the rate of the pulse train being measured by the counter. It does not return the actual waveform that is being read by the counter. It is this waveform that would be band-pass filtered to eliminate frequency content outside of the filter's bandwidth. Instead of the Filter express VI, I would recommend that you simply discard values that are outside the range you specify. I have modified the code you posted earlier to perform this operation. The image below shows the changes that I made; rather than using the Filter express VI, I simply compare the frequency to the "Low Threshold" and "High Threshold". I use a Case structure to display the value on if it is within the limits. Otherwise, I display a "NaN" value. I have also attached the modified VI to this post.
    Message Edited by Matt A on 09-04-2007 07:58 PM
    Matt Anderson
    Hardware Services Marketing Manager
    National Instruments
    Attachments:
    RPM (Modified).JPG ‏17 KB
    RPM (modified).vi ‏72 KB

  • What is wrong with this program segment? I could not understand the error..

    public class Hmw3
         public static char[] myMethod(char[]p1,int p2, char p3)
         {                             //13 th row
              if(p2<p1.length)
                   p1[p2]=p3;
                   System.out.println(p1);
         public static void main(String[] args)
              String sentence="It snows";
              char[] tmp=sentence.toCharArray();
              System.out.println(tmp);
              myMethod(tmp,3,'k');
              sentence=String.copyValueOf(tmp);
              System.out.println(sentence);     
    i wrote this program segment and compiler gave this error:
    C:\Program Files\Xinox Software\JCreator LE\MyProjects\hmw3\Hmw3.java:13: missing return statement
    What is wrong???

    Your method signature states that myMethod should return an array for chars.
    But in ur implementation of myMethod, there is nothing returned.
    Just add a return statement like "return p1"

  • What could be wrong with this resolveNodes / for script?

    Hello, I am stumped and would greatly appreciate some help here.
    I have a table that has the ability to add additional rows.
    Each row includes a "delete" button to clear the row.
    I'd like to hide the "delete" button when another button is clicked.
    There are a variable amount of rows at any given time, so I can't target the button directly.
    I have used the "for" method before, but it doesn't seem to be able to find the nodes in this case.
    My hierarchy looks like this:
    form1
    - productSubform
    - - productJobTable
    - - - productJobRow
    - - - - deleteBtn
    my Javascript looks like this:
    var nodes = form1.productSubform.productJobTable.resolveNodes("productJobRow[*]");
    var len = nodes.length;
    for(var i = 0; i < len; i++) {
            nodes.item(i).deleteBtn.presence = "invisible";
    Can anyone see what could be wrong here?
    Thank you in advance.

    This code worked for me...
      var rows = form1.p1.Table1.resolveNodes("Row1[*]");
      var len = rows.length;
      for (var i=0; i<len; i++) rows.item(i).Button1.presence = "invisible";
    When I used nodes as the variable name, I got this error: "Invalid property set operation."

  • What's wrong with this program that about socket

    package example;
    import java.net.*;
    import java.io.*;
    public class Server implements Runnable{
        Thread t;
        ServerSocket sSocket;
        int sPort=6633;
        public Server(){
            try{
                sSocket=new ServerSocket(sPort);
                System.out.println("server start....");
            }catch(IOException e){
                e.printStackTrace();
            t=new Thread(this);
            t.start();
        public void run(){
            try{
                while(true){
                    Socket cSocket=sSocket.accept();
                    ClientThread cThread=new ClientThread(cSocket);
                    cThread.start();
            }catch(IOException e){
                e.printStackTrace();
       public static void main(String[] args){
            new Server();
    package example;
    import java.net.*;
    import java.io.*;
    public class ClientThread extends Thread{
        Socket cSocket;
        PrintStream writer;
        BufferedReader reader;
        public ClientThread(Socket s){
            cSocket=s;
            try{
                writer=new PrintStream(cSocket.getOutputStream());
                reader=new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
            }catch(IOException e){
                e.printStackTrace();
        public void run(){
            try{
                while(true){
                    String message=reader.readLine();
                    System.out.println("Server get:"+message);
            }catch(IOException e){
                e.printStackTrace();
    package example;
    import java.net.*;
    import java.io.*;
    public class Client{
        public static void main(String[] args){
            String ipaddr="localhost";
            PrintStream writer;
            try{
                Socket  cSocket=new Socket(ipaddr,6633);
                System.out.println(cSocket);
                writer=new PrintStream(cSocket.getOutputStream());
                System.out.println("client send:hello");
                writer.print("hello");
            catch(Exception e){
                e.printStackTrace();
    }first,I run Server,and then I run Client,
    output at Server:
    server start....
    java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at java.net.SocketInputStream.read(SocketInputStream.java:90)
    at sun.nio.cs.StreamDecoder$ConverterSD.implRead(StreamDecoder.java:285)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:182)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    at example.ClientThread.run(ClientThread.java:20)
    what' wrong??????

    In your Client class, after doing writer.print("hello"); you should flush
    the output stream. As it is now, you attempt to write something (without actually
    sending something to your server) and main simply terminates. The server,
    still waiting for some input (you didn't flush on the client side), is confronted with
    a closed client socket (main on the client side terminated and implicitly closed
    the client socket), hence the 'connection reset' exception on the server side.
    kind regards,
    Jos

  • What's wrong with this program?

    /* Daphne invests $100 at 10% simple interest. Deirdre invests $100 at 5% interest compounded annually. Write a program that finds how many years it takes for the value of Deirdre's investment to exceed the value of Daphne's investment. Aso show the two values at that time.*/
    #include <stdio.h>
    #define START 100.00
    int main(void)
    int counter = 1;
    float daphne = START;
    float deirdre = START;
    printf("Daphne invests $100 at 10 percent simple interest. Deirdre invests $100 at 5 percent interest compounded annually.
    When will Deirdre's account value exceed Daphne's?
    Let\'s find out.
    while (daphne > deirdre)
    daphne += 10.00;
    deirdre *= 1.05;
    printf("%f %f
    ", daphne, deirdre);
    printf("At year %d, Daphne has %.2f dollars. Deirdre has %.2f dollars.
    ", counter, daphne, deirdre);
    counter++;
    printf("By the end of year %d, Deirdre's account has surpassed Daphne's in value.
    ", counter);
    return 0;
    This is my output:
    *Daphne invests $100 at 10 percent simple interest. Deirdre invests $100 at 5 percent interest compounded annually.*
    *When will Deirdre's account value exceed Daphne's?*
    *Let's find out.*
    *By the end of year 1, Deirdre's account has surpassed Daphne's in value.*
    What's wrong with it?
    Message was edited by: musicwind95
    Message was edited by: musicwind95

    John hadn't responded at the time I started typing this, but I'll keep it posted anyways in order to expand on John's answer a little bit. The answer to your last question is that the loop's condition has to return true for it to run the first time around. To examine this further, let's take a look at the way you had the while loop before:
    while (daphne > deirdre)
    Now, a while loop will run the code between its braces as long as the condition inside the parenthesis (daphne > deirdre, in this case) is true. So, if the condition is false the first time the code reaches the while statement, then the loop will never run at all (it won't even run through it once -- it will skip over it). And since, before the while loop, both variables (daphne and dierdre) are set equal to the same value (START (100.00), in this case), both variables are equal at the point when the code first reaches the while statement. Since they are equal, daphne is NOT greater than dierdre, and therefore the condition returns false. Since the condition is false the first time the code reaches it, the code inside the loop's braces is skipped over and never run. As John recommended in the previous post, changing it to this:
    while (daphne >= deirdre)
    fixes the problem because now the condition is true. The use of the "greater than or equal to" operator (>=) instead of the "great than" operator (>) means that the condition can now be returned true even if daphne is equal to deirdre, not just if it's greater than deirdre. And since daphne and deirdre are equal (they are both 100.00) when the code first reaches the while loop, the condition is now returned true and the code inside the loop's braces will be run. Once the program reaches the end of the code inside the loop's braces, it will check to see if the condition is still true and, if it is, it will run the loop's code again (and again and again and again, checking to see if the condition is still true each time), and if it's not true, it will skip over the loop's bottom brace and continue on with the rest of the program.
    Hope this helped clear this up for you. Please ask if you have any more questions.

  • What am I doing wrong with this method?

    Ok I tried this for two hours and for some reason my variables from one method wont work with the other method what am I doing wrong?
    public class Testing
    private static void storage(String[] storage){
    String retval= "";
    for(int i=0;i!=storage.length;i++){
    String getstorage= storage[i]+retval;
    return storage[i]+retval;
    }//for
    }//storage
    public static int[] find(String[] str){
    for(int i=0;i!=str.length;i++){
    if(str.equals (storage[i].substring(0,2))){
    return indexOf(str[i], str[i].length);
    else If(str[i].substring(indexOf(str[i]),str[i].length)>storage.substring(indexOf(storage[i]),storage[i].length)){
    return {0,0};
    };//elseif
    }//if
    }//for
    }//find
    }//StrStore

    Thanks got that part fixed and I even kinda learned how to make it so that I can establish the variable somewhere else lemme show you:
    public class StrStore
       private static String[] storage(String[] storage){
                for (int i=0; i!=storage.length; i++);
                  String retval="";
                  return storage[i] +retval;
               }//for
             }//storage
       public static String[] getStorageArray()
         String[] temp= new String[storage.length];
         for (int i=0; i!=storage.length; i++){
                  temp= storage[i];
    return temp;
    }//for
    }//getStorageArray
    public static int[] find(String[] str){
    for(int i=0;i!=str.length;i++){
    if(str[i].equals (storage[i].substring(0,2))){
    return {indexOf(str[i], str[i].length};
    else if(str[i].substring(indexOf(str[i]),str[i].length>storage.substring(indexOf(storage[i]),storage[i].length)){
    return {0,0};
    }//elseif
    }//if
    }//for
    }//find
    public static int[] encode(String str){
    for(int i=0;i!=str.length;i++){
    if(str[i].length>storage[i].length);
    return str[i]+storage[i];
    else{
    find(storage[i]);
    }//elseif
    }//if
    }//for
    }//encode
    public static Int[] decode(int[] code){
    for(int i=0;i!=str.length;i++){
    return find(storage[i]);
    }//for
    }//decode
    public static void main(String[] args)
    int[][] codes = new int[args.length][];
    for(int i=0;i!=args.length;i++){
    codes[i]=encode(args[i]);
    }//for
    storage(getstorage);
    System.out.println("storage = "+ getStorage);
    for(int i=0;i!=args.length;i++){
    System.out.println(decode(codes[i]));
    }//for
    }//main()
    }//StrStore
    however Im still coming up with 5 errors now one is stating that in this section:
    public static String[] getStorageArray()
         String[] temp= new String[storage.length];
         for (int i=0; i!=storage.length; i++){
                  temp= storage[i];
    return temp;
    }//for
    }//getStorageArray
    that a class is expected but I thought I had the class defined? I get that also here:
       public static int encode(String str){
               for(int i=0;i!=str.length;i++){
                 if(str.length>storage[i].length);
    return str[i]+storage[i];
    else{
    find(storage[i]);
    }//elseif
    }//if
    }//for
    }//encode
    but instead of the beginning I get it at the very last line of that snippet
    then I get that these two variables are incompatible
    private static String[] storage(String[] storage){
                for (int i=0; i!=storage.length; i++);
                  String retval="";
                  return storage[i] +retval;
               }//for
             }//storage

  • What is wrong with this program it keeps telling me the file doesn't exist?

    this program is supposed to write the file so why does it need the file to already exist?
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Scanner;
    public class NewClass implements ActionListener{
        static List list = new List();
        static TextField input = new TextField(20);
        static Button submit = new Button("Submit");
        static Frame f = new Frame("RealmList editor");
        static File file = new File("/Applications/World of Warcraft/realmlist.wtf");
        static Label status = new Label("");
        static Button selected = new Button("Change to Selected");
        static File config = new File("/Applications/RealmLister/config.txt");
        static File dir = new File("/Applications/RealmLister/");
        public static void main(String[] args) {
            f.setLayout(new BorderLayout());
            f.add(list, BorderLayout.CENTER);
            Panel p = new Panel();
            p.add(input);
            p.add(submit);
            p.add(selected);
            f.add(p, BorderLayout.NORTH);
            f.add(status, BorderLayout.SOUTH);
            new NewClass();
            f.setSize(500,500);
            f.setVisible(true);
            try {
                loadConfig();
            } catch(Exception e) {}
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent we) {
                    try {
                      writeConfig();
                      System.exit(0);
                    } catch(Exception e) {
                       status.setText("Error: config couldn't be written!("+e+")");
        public NewClass() {
            submit.addActionListener(this);
            input.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                    try {
                    editRealmlist(input.getText(), true);
                    input.setText("");
                 catch(Exception ex) {
                   status.setText("Error: "+e);
            selected.addActionListener(this);
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == submit) {
                try {
                    editRealmlist(input.getText(), true);
                    input.setText("");
                } catch(Exception ex) {
                   status.setText("Error: "+e);
                   wait(3000);
                   status.setText("");
            if(e.getSource() == selected) {
                try {
                    editRealmlist(list.getSelectedItem(),false);
                } catch(Exception ex) {
                    status.setText("Error: "+e);
                    wait(3000);
                    status.setText("");
        public static void loadConfig() throws Exception{
            if(config.exists()) {
                Scanner scan = new Scanner(config);
                ArrayList<String> al = new ArrayList<String>();
                while(scan.hasNext()) {
                    al.add(scan.nextLine());
                for(int i = 0; i < al.size(); i++) {
                    list.add(al.get(i));
        public static void writeConfig() throws Exception{
            FileWriter fw = new FileWriter(config);
            dir.mkdir();
            config.mkdirs();
            String temp = "";
            for(int i = 0; i < list.getItemCount(); i++) {
                temp += list.getItem(i)+"\n";
            fw.write(temp);
            fw.flush();
            System.gc();
        public static void editRealmlist(String realm, boolean addtoList) throws Exception{
            FileWriter fw = new FileWriter(file);
            fw.write("set realmlist "+realm+"\nset patchlist us.version.worldofwarcraft.com");
            fw.flush();
            status.setText("Editing RealmList.wtf Please Wait...");
            Thread.sleep(3000);
            status.setText("");
            System.gc();
            if(addtoList)
                list.add(realm);
        public void wait(int time) {
            try {
                Thread.sleep(time);
            catch(Exception e) {}
    }

    Erm, you should call mkdirs() on a File object that represents a directory.

  • Please wat is wrong with this program

    I want to reverse the user input but when I run this program it only asks for the input and when i key it in and press enter nothing happens.It just freezes.
    Sorry the code is a bit long .
    import java.io.*;
    class StackX
    private int maxSize;
    private char[] stackArray;
    private int top;
    public StackX(int max)  
           maxSize=max;
           stackArray=new char[maxSize];
           top=-1;
    public void push(char j) 
         stackArray[++top]=j;
    public char pop()    
         return stackArray[top--];
    public char peek()  
         return stackArray[top];
    public boolean isEmpty()   
         return (top==-1);
    class Reverser
         private String input;  
         private String output; 
    public Reverser(String in)
         {input = in;}
             public String doRev( )    
         int stackSize=input.length( ); 
         StackX theStack = new StackX(stackSize);
         for(int j=0;j<input.length( );j++)
         char ch=input.charAt(j); 
         theStack.push(ch);
         output ="";
         while( !theStack.isEmpty() )
         char ch=theStack.pop();
         output=output+ch; 
         return output;
    class ReverseApp
         public static void main(String[]args)throws IOException
         String input, output;
         while(true)
         System.out.print("Enter a string:");
         System.out.flush();
         input=getString();
         if( input.equals(""))
          break;
         Reverser theReverser = new Reverser(input);
         output = theReverser.doRev();
         System.out.println("Reversed: " + output);
    public static String getString()throws IOException
         InputStreamReader isr = new InputStreamReader(System.in);
         BufferedReader br= new BufferedReader(isr);
         String s = br.readLine();
         return s;
    }

    One potential problem is that you're using a new reader around system.in every time. I don't know what happens when you do that. Just make it a member variable, or create it once in main and pass it to getString.
    Asid from that, put a bunch of print statements in or use a debugger to see what's happening at each step of the way. You might be getting into an infinite loop somewhere in your reverse operation.

  • What could be wrong with this procedure?

    SET VERIFY OFF;
    ACCEPT v_employee_id NUMBER PROMPT 'Increasing salary. Please enter Employee ID:'
    DECLARE
    v_empdata employees%ROWTYPE;
    v_sal_increase number := 0;
    BEGIN
    SELECT *
    INTO v_empdata
    FROM employees
    WHERE employee_id = &&v_employee_id;
    DBMS_OUTPUT.PUT_LINE (TO_CHAR(v_empdata.employee_id) || ' ' || v_empdata.first_name || ' '|| v_empdata.job_id || ' '
    || v_empdata.department_id || ' ' || v_empdata.salary || ' old ');
    IF
    v_empdata.department_id = 10
    AND v_empdata.job_id = 'CLERK'
    THEN v_sal_increase := 0.0625;
    ELSIF v_empdata.department_id = 20
    AND v_empdata.job_id = 'CLERK'
    THEN v_sal_increase := 0.115;
    ELSIF v_empdata.department_id = 10
    AND v_empdata.job_id = 'CLERK'
    THEN v_sal_increase := 0.0625;
    ELSIF v_empdata.department_id = 30
    AND v_empdata.job_id = 'CLERK'
    THEN v_sal_increase := 0.093;
    ELSIF v_empdata.department_id = 10
    AND v_empdata.job_id = 'CLERK'
    THEN v_sal_increase := 0.0625;
    ELSIF v_empdata.department_id = 10
    AND v_empdata.job_id = 'PRESIDENT'
    THEN v_sal_increase:= 0.00;
    ELSIF v_empdata.salary >= 3000
    THEN v_sal_increase := 0.0425;
    ELSIF v_empdata.salary < 3000
    THEN v_sal_increase := 0.085;
    END IF;
    IF v_sal_increase > 0 THEN
    UPDATE employees
    SET salary = salary * ( 1 + v_sal_increase) WHERE employee_id = v_empdata.employee_id;
    END IF;
    SELECT *
    INTO v_empdata
    FROM employees
    WHERE employee_id = &&v_employee_id;
    DBMS_OUTPUT.PUT_LINE (TO_CHAR(v_empdata.employee_id) || ' ' || v_empdata.first_name || ' '|| v_empdata.job_id || ' '
    || v_empdata.department_id || ' ' || v_empdata.salary || ' ' || (v_sal_increase*100)|| '% new');
    ROLLBACK;
    END;
    SET VERIFY ON;

    SQL>
    1 SET VERIFY OFF;
    2 ACCEPT v_employee_id NUMBER PROMPT 'Increasing salary. Please enter Employee ID:'
    3 DECLARE
    4 v_empdata employees%ROWTYPE;
    5 v_sal_increase number := 0;
    6 BEGIN
    7 SELECT *
    8 INTO v_empdata
    9 FROM employees
    10 WHERE employee_id = &&v_employee_id;
    11 DBMS_OUTPUT.PUT_LINE (TO_CHAR(v_empdata.employee_id) || ' ' || v_empdata.first_name || ' '|| v_empdata.job_id || ' '
    12 || v_empdata.department_id || ' ' || v_empdata.salary || ' old ');
    13 IF
    14 v_empdata.department_id = 10
    15 AND v_empdata.job_id = 'CLERK'
    16 THEN v_sal_increase := 0.0625;
    17 ELSIF v_empdata.department_id = 20
    18 AND v_empdata.job_id = 'CLERK'
    19 THEN v_sal_increase := 0.115;
    20 ELSIF v_empdata.department_id = 10
    21 AND v_empdata.job_id = 'CLERK'
    22 THEN v_sal_increase := 0.0625;
    23 ELSIF v_empdata.department_id = 30
    24 AND v_empdata.job_id = 'CLERK'
    25 THEN v_sal_increase := 0.093;
    26 ELSIF v_empdata.department_id = 10
    27 AND v_empdata.job_id = 'CLERK'
    28 THEN v_sal_increase := 0.0625;
    29 ELSIF v_empdata.department_id = 10
    30 AND v_empdata.job_id = 'PRESIDENT'
    31 THEN v_sal_increase:= 0.00;
    32 ELSIF v_empdata.salary >= 3000
    33 THEN v_sal_increase := 0.0425;
    34 ELSIF v_empdata.salary < 3000
    35 THEN v_sal_increase := 0.085;
    36 END IF;
    37 IF v_sal_increase > 0 THEN
    38 UPDATE employees
    39 SET salary = salary * ( 1 + v_sal_increase) WHERE employee_id = v_empdata.employee_id;
    40 END IF;
    41 SELECT *
    42 INTO v_empdata
    43 FROM employees
    44 WHERE employee_id = &&v_employee_id;
    45 DBMS_OUTPUT.PUT_LINE (TO_CHAR(v_empdata.employee_id) || ' ' || v_empdata.first_name || ' '|| v_empdata.job_id || ' '
    46 || v_empdata.department_id || ' ' || v_empdata.salary || ' ' || (v_sal_increase*100)|| '% new');
    47 ROLLBACK;
    48 END;
    49 /
    50* SET VERIFY ON;
    51 /
    old 10: WHERE employee_id = &&v_employee_id;
    new 10: WHERE employee_id = 107;
    old 44: WHERE employee_id = &&v_employee_id;
    new 44: WHERE employee_id = 107;
    SET VERIFY OFF;
    ERROR at line 1:
    ORA-00922: missing or invalid option

Maybe you are looking for

  • Real newbie-I can hear my loops in my library, but when I drag them to a track, there is no audio.  What am I doing wrong?

    Real newbie question-I can hear the loops in my library, but when I drag them to a track, there is no audio when I playback or record.  What am I doing wrong?

  • Music App Stops Playing

    I'm having an issue with the music app on my Iphone 5 (version 7.0.4) and my brand new Ipad mini (not sure what version). It plays the first few songs fine and then randomly stops, the play button is still an arrow (it's not paused, my head phones ha

  • Dimension Number of BSO Application on Essbase

    Hi, I'm new in Essbase and I should review an existent BSO application to improve its performance. This application has an outline with 5 dimensions, Measure (Account), Period (Time), KPI, Recalculated Market and Organizational Structure. These dimen

  • How to see all music categories in iTunes Store?

    When I enter in iTunes Store I see just standard categories: pop, alternative, rock and even others. But I often notice interesting categories like "music of 70s", "music of 2000s" and others. How to see all these additional subcategories?

  • Version of Autoconfig

    Hi everyone, I have a doubt, i hope somebody can help me. How can i know the current version of autoconfig that i had, i see in metalink how know if we have the last version, but how can i know my current version? Thank you very much. Regards