Console.readInt

Right, since you�re the Java Experts.
And I'm very stupid!!!
I downloaded the JDK Kit from Sun
Installed
No Problem,followed the instructions, etc,etc.
When I compile a simple Program such as this one here.
There�s no problem.
(read on after Program)
class Pay01
This class implements a simple program that
will compute the amount of interest that is
earned on $17,000 invested at an interest
rate of 0.07 for one year. The interest and
the value of the investment after one year are
printed to standard output.
public static void main(String[] args) {
/* Declare the variables. */
double principal; // The value of the investment.
double rate; // The annual interest rate.
double interest; // Interest earned in one year.
/* Do the computations. */
principal = 17000;
rate = 0.07;
interest = principal * rate; // Compute the interest.
principal = principal + interest;
// Compute value of investment after one year, with interest.
// (Note: The new value replaces the old value of principal.)
/* Output the results. */
System.out.print("The interest earned is $");
System.out.println(interest);
System.out.print("The value of the investment after one year is $");
System.out.println(principal);
} // end of main()
} // end of class pay01
When I try to run a program or compile a program using console.readInt (ie taking data from the keyboard) I get a compile error.
Heres a SAMPLE PROGRAM which I know is correct that uses console.readInt but does not run. What am I doing wrong?
I thought that the computer did not recognize Console.readInt(ie conflict) so I tried TextIo.get which does the same thing. Still the same problem.
What am I doing wrong???
Did I install JDK wrongly (I dont think so as i followed all the Instructions clearly)??
If so can you give me an idiots version for installing it.
Here are the programs.
What am I doing wrong?????
class ComputeNumbers
* Program to illustrate reading input from the keyboard
* using the method readInt () in the class Console
* The program inputs two numbers from the user and outputs
* the sum , the product, the quotient and the remainder
public static void main (String[] args)
// declare variables
int firstNumber;
int secNumber , sum, prod, quot, rem;
// input 2 numbers from the use
System.out.println(" Enter the first number (integer) ");
firstNumber = Console.readInt(); // assign to (put into) the variable
// firstNumber the value that is typed at the
// keyboard
System.out.println(" Enter the second number (integer) ");
secNumber = Console.readInt();
// compute
sum = firstNumber + secNumber;
prod = firstNumber * secNumber;
quot = firstNumber / secNumber;
rem = firstNumber % secNumber;
// print results
class Pay02 {
This class implements a simple program that
will compute the amount of interest that is
earned on an investment over a period of
one year. The initial amount of the investment
and the interest rate are input by the user.
The value of the investment at the end of the
year is output. The rate must be input as a
decimal, not a percentage (for example, 0.05,
rather than 5).
public static void main(String[] args) {
double principal; // the value of the investment
double rate; // the annual interest rate
double interest; // the interest earned during the year
TextIO.put("Enter the initial investment: ");
principal = TextIO.getlnDouble();
TextIO.put("Enter the annual interest rate: ");
rate = TextIO.getlnDouble();
interest = principal * rate; // compute this year's interest
principal = principal + interest; // add it to principal
TextIO.put("The value of the investment after one year is $");
TextIO.putln(principal);
} // end of main()
} // end of class Interest2

This looks like an assignment. I remember doing something similiar. I assume that Console is a seperate java class that is supposed to simplify reading in from the console. You have to put the Console class in the same directory as your ComputeNumbers class that way you can call its methods. It looks like the methods in Console such as readInt(); are static and that is why you can call them like Console.readInt(); If they are not you must create an instance of Console with the new operator before calling its methods. Hope this helps

Similar Messages

  • Cannot find symbol "console" error

    hi there ~
    Here is environment:
    winXP Pro
    jdk1.5.0_04
    here is part of my code:
            System.out.print("Enter Bit length   \t:");
            int bitlen = Console.readInt();
         System.out.print("Enter integer to be encrypted  :");
         BigInteger big = new BigInteger(Console.readString());here is the error msg:
    C:\Program Files\Java\jdk1.5.0_04\bin>javac myRSA.java
    myRSA.java:115: cannot find symbol
    symbol : variable Console
    location: class myRSA
    int bitlen = Console.readInt();
    ^
    myRSA.java:157: cannot find symbol
    symbol : variable Console
    location: class myRSA
    BigInteger big = new BigInteger(Console.readString());
    ^
    2 errors
    thx for your help in advance.

    The javac compiler does not understand what "Console" means in your code. (BTW, to follow recommended coding conventions, you class should be named MyRSA - using coding conventions will get you better help.)
    It appears that Console is a class you wrote or was given to you. You need to import it, if it is not in the same package as myRSA. And, the compiler needs to be able to find it through the Classpath.

  • I can't figure out what's wrong with this code

    First i want this program to allow me to enter a number with the EasyReader class and depending on the number entered it will show that specific line of this peom:
    One two buckle your shoe
    Three four shut the door
    Five six pick up sticks
    Seven eight lay them straight
    Nine ten this is the end.
    The error message i got was an illegal start of expression. I can't figure out why it is giving me this error because i have if (n = 1) || (n = 2) statements. My code is:
    public class PoemSeventeen
    public static void main(String[] args)
    EasyReader console = new EasyReader();
    System.out.println("Enter a number for the poem (0 to quit): ");
    int n = console.readInt();
    if (n = 1) || (n = 2)
    System.out.println("One, two, buckle your shoe");
    else if (n = 3) || (n = 4)
    System.out.println("Three, four, shut the door");
    else if (n = 5) || (n = 6)
    System.out.println("Five, six, pick up sticks");
    else if (n = 7) || (n = 8)
    System.out.println("Seven, eight, lay them straight");
    else if (n = 9) || (n = 10)
    System.out.println("Nine, ten, this is the end");
    else if (n = 0)
    System.out.println("You may exit now");
    else
    System.out.println("Put in a number between 0 and 10");
    I messed around with a few other thing because i had some weird errors before but now i have narrowed it down to just this 1 error.
    The EasyReader class code:
    // package com.skylit.io;
    import java.io.*;
    * @author Gary Litvin
    * @version 1.2, 5/30/02
    * Written as part of
    * <i>Java Methods: An Introduction to Object-Oriented Programming</i>
    * (Skylight Publishing 2001, ISBN 0-9654853-7-4)
    * and
    * <i>Java Methods AB: Data Structures</i>
    * (Skylight Publishing 2003, ISBN 0-9654853-1-5)
    * EasyReader provides simple methods for reading the console and
    * for opening and reading text files. All exceptions are handled
    * inside the class and are hidden from the user.
    * <xmp>
    * Example:
    * =======
    * EasyReader console = new EasyReader();
    * System.out.print("Enter input file name: ");
    * String fileName = console.readLine();
    * EasyReader inFile = new EasyReader(fileName);
    * if (inFile.bad())
    * System.err.println("Can't open " + fileName);
    * System.exit(1);
    * String firstLine = inFile.readLine();
    * if (!inFile.eof()) // or: if (firstLine != null)
    * System.out.println("The first line is : " + firstLine);
    * System.out.print("Enter the maximum number of integers to read: ");
    * int maxCount = console.readInt();
    * int k, count = 0;
    * while (count < maxCount && !inFile.eof())
    * k = inFile.readInt();
    * if (!inFile.eof())
    * // process or store this number
    * count++;
    * inFile.close(); // optional
    * System.out.println(count + " numbers read");
    * </xmp>
    public class EasyReader
    protected String myFileName;
    protected BufferedReader myInFile;
    protected int myErrorFlags = 0;
    protected static final int OPENERROR = 0x0001;
    protected static final int CLOSEERROR = 0x0002;
    protected static final int READERROR = 0x0004;
    protected static final int EOF = 0x0100;
    * Constructor. Prepares console (System.in) for reading
    public EasyReader()
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
    new InputStreamReader(System.in), 128);
    * Constructor. opens a file for reading
    * @param fileName the name or pathname of the file
    public EasyReader(String fileName)
    myFileName = fileName;
    myErrorFlags = 0;
    try
    myInFile = new BufferedReader(new FileReader(fileName), 1024);
    catch (FileNotFoundException e)
    myErrorFlags |= OPENERROR;
    myFileName = null;
    * Closes the file
    public void close()
    if (myFileName == null)
    return;
    try
    myInFile.close();
    catch (IOException e)
    System.err.println("Error closing " + myFileName + "\n");
    myErrorFlags |= CLOSEERROR;
    * Checks the status of the file
    * @return true if en error occurred opening or reading the file,
    * false otherwise
    public boolean bad()
    return myErrorFlags != 0;
    * Checks the EOF status of the file
    * @return true if EOF was encountered in the previous read
    * operation, false otherwise
    public boolean eof()
    return (myErrorFlags & EOF) != 0;
    private boolean ready() throws IOException
    return myFileName == null || myInFile.ready();
    * Reads the next character from a file (any character including
    * a space or a newline character).
    * @return character read or <code>null</code> character
    * (Unicode 0) if trying to read beyond the EOF
    public char readChar()
    char ch = '\u0000';
    try
    if (ready())
    ch = (char)myInFile.read();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (ch == '\u0000')
    myErrorFlags |= EOF;
    return ch;
    * Reads from the current position in the file up to and including
    * the next newline character. The newline character is thrown away
    * @return the read string (excluding the newline character) or
    * null if trying to read beyond the EOF
    public String readLine()
    String s = null;
    try
    s = myInFile.readLine();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (s == null)
    myErrorFlags |= EOF;
    return s;
    * Skips whitespace and reads the next word (a string of consecutive
    * non-whitespace characters (up to but excluding the next space,
    * newline, etc.)
    * @return the read string or null if trying to read beyond the EOF
    public String readWord()
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;
    try
    while (ready() && Character.isWhitespace(ch))
    ch = (char)myInFile.read();
    while (ready() && !Character.isWhitespace(ch))
    count++;
    buffer.append(ch);
    myInFile.mark(1);
    ch = (char)myInFile.read();
    if (count > 0)
    myInFile.reset();
    s = buffer.toString();
    else
    myErrorFlags |= EOF;
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    return s;
    * Reads the next integer (without validating its format)
    * @return the integer read or 0 if trying to read beyond the EOF
    public int readInt()
    String s = readWord();
    if (s != null)
    return Integer.parseInt(s);
    else
    return 0;
    * Reads the next double (without validating its format)
    * @return the number read or 0 if trying to read beyond the EOF
    public double readDouble()
    String s = readWord();
    if (s != null)
    return Double.parseDouble(s);
    // in Java 1, use: return Double.valueOf(s).doubleValue();
    else
    return 0.0;
    Can anybody please tell me what's wrong with this code? Thanks

    String[] message = {
        "One, two, buckle your shoe",
        "One, two, buckle your shoe",
        "Three, four, shut the door",
        "Three, four, shut the door",
        "Five, six, pick up sticks",
        "Five, six, pick up sticks",
        "Seven, eight, lay them straight",
        "Seven, eight, lay them straight",
        "Nine, ten, this is the end",
        "Nine, ten, this is the end"
    if(n>0)
        System.out.println(message[n]);
    else
        System.exit(0);

  • Please help, java program terminating unexpectedly without reason

    ok, so I have a project I'm working on, here's its description:
    Create a new project named FML_Pig where F is your first initial, M is your middle initial, and L is your last initial. For example, if your name is Alfred Edward Neuman then you would name your project AEN_Pig. If necessary, add a new Java file to this project named FML_Pig.
    Add a java file to the project named FML_Dice.
    Design and implement a Dice class as follows. The Dice class has 2 twenty&#8209;sided dice with numbers on the faces (1 � 20) and 2 twenty-six-sided dice with letters on the faces (a � z).
    import java.util.Random;
    public class FML_Dice
    private static Random gen = new Random();
    private final static int NUM_SIDES = 20;
    private int die1, die2, numSnakeEyes, numVowels, totalPoints;
    private char die3, die4;
    Part 1
    Add a rollDice() method to your FML_Dice class that sets die1 and die2 to a random number between 1 and 20 and it sets die3 and die4 to a random character between �a� and �z�.
    Helpful Hint:
    dice3 = (char)(�a� + gen.nextInt(26)); // sets dice3 to a random char between �a� and �z�.
    Part 2
    Write a constructor that sets die1 and die2 to a random number between 1 and 20 and it sets die3 and die4 to a random character. Your constructor can simply call rollDice() to do this. It should also initialize numSnakeEyes, numVowels, and totalPoints to 0 (after you roll the dice).
    Part 3
    Write methods getDie1(), getDie2(), getDie3(), and getDie4() that returns the value of the respective die. Write a method numSnakes() that returns the number of snake eyes that have been rolled. Write a method numVowels() that returns the number of vowels that have been rolled. Write a method totalPts() that returns the totalPoints.
    Part 4
    Write a toString() method that overwrites the default toString() method. It should return a String representation of the value of all 4 die. For example, 17 2 h w.
    Part 5
    Write a method updateTotals that updates numVowels, numSnakeEyes, and totalPoints based on the current values of die1, die2, die3, and die4. numVowels should be incremented by 1 if either die3 or die4 are a vowel. However, if both die3 and die4 are vowels, the totalPoints should be reset to 0 and numVowels should be reset to 0 also. numSnakeEyes should be incremented by 1 if either die1 or die2 have a face value of 1 (this is not truly a snake eyes, but it gives better odds for the game). totalPoints should be incremented by the sum of die1 and die2 multiplied by (numSnakeEyes + 1).
    Part 6
    Write a main program (use the one in FML_Pig.java) that plays a game of Pig. In this game, two people play against each other. Player1 begins by rolling the dice. The total of die1 and die2 is added to his total score. Player1�s turn continues until he/she rolls a total of 4 vowels then the turn switches to Player2. Whenever a turn switches to the other player, the number of vowels is reset to zero. Also, if at any time both die3 and die4 are vowels, the total score is reset to 0 and the turn switches to the other player. (So the turn switches to the other player whenever the total number of vowels reaches four or there are two vowels rolled at the same time.)
    If a player rolls snakeeyes (for our game, snakeeyes occurs whenever either of the dice have a face value of one � in reality, both die1 and die2 should have a face value of one but then snakeeyes would occur only once every 400 rolls), then his point values are doubled from that point on (all future rolls for the rest of the game, point values for this player are doubled). When a player rolls snake eyes again, point values are tripled for that roll and all future rolls. (Three snake eyes, quadrupled, etc.)
    (continued on the next page)
    Be sure to display the results of the roll for each turn.
    First player to get to 2000 points wins the game and gets to oink like a pig.
    Note: Both players need their own set of Dice since the Dice keeps track of the totalPoints, the number of snake eyes rolled so far, and the number of vowels rolled so far for that particular player. You can do this simply by declaring it that way in the main program:
    Dice player1 = new Dice();
    Dice player2 = new Dice();
    You may add additional methods and instance variables to the class as needed. For example, I would probably write a private helper method isVowel() that is passed a char argument ch and returns true if ch is a vowel.
    Also, you can have the computer play for both player 1 and player 2. Simply loop it until somebody wins. Print out the result for each turn including who rolled the dice (player 1 or player 2), what they rolled, how many snakeeyes do they have, how many points did they get for this turn, and how many total points do they have.
    When you are completely finished, hand in just the java files (FLM_Dice & FLM_Pig). If you happened to write any other classes, make sure they are named with the FML format, and turn these in as well. I do not need EasyReader or p.
    Oink! Oink!
    This pig won the game --------->
    so here's my code:
    this isn't my code but is required to compile my code: // package com.skylit.io;
    import java.io.*;
    *  @author Gary Litvin
    *  @version 1.2, 5/30/02
    *  Written as part of
    *  <i>Java Methods: An Introduction to Object-Oriented Programming</i>
    *  (Skylight Publishing 2001, ISBN 0-9654853-7-4)
    *   and
    *  <i>Java Methods AB: Data Structures</i>
    *  (Skylight Publishing 2003, ISBN 0-9654853-1-5)
    *  EasyReader provides simple methods for reading the console and
    *  for opening and reading text files.  All exceptions are handled
    *  inside the class and are hidden from the user.
    *  <xmp>
    *  Example:
    *  =======
    *  EasyReader console = new EasyReader();
    *  System.out.print("Enter input file name: ");
    *  String fileName = console.readLine();
    *  EasyReader inFile = new EasyReader(fileName);
    *  if (inFile.bad())
    *    System.err.println("Can't open " + fileName);
    *    System.exit(1);
    *  String firstLine = inFile.readLine();
    *  if (!inFile.eof())   // or:  if (firstLine != null)
    *    System.out.println("The first line is : " + firstLine);
    *  System.out.print("Enter the maximum number of integers to read: ");
    *  int maxCount = console.readInt();
    *  int k, count = 0;
    *  while (count < maxCount && !inFile.eof())
    *    k = inFile.readInt();
    *    if (!inFile.eof())
    *      // process or store this number
    *      count++;
    *  inFile.close();    // optional
    *  System.out.println(count + " numbers read");
    *  </xmp>
    public class EasyReader
      protected String myFileName;
      protected BufferedReader myInFile;
      protected int myErrorFlags = 0;
      protected static final int OPENERROR = 0x0001;
      protected static final int CLOSEERROR = 0x0002;
      protected static final int READERROR = 0x0004;
      protected static final int EOF = 0x0100;
       *  Constructor.  Prepares console (System.in) for reading
      public EasyReader()
        myFileName = null;
        myErrorFlags = 0;
        myInFile = new BufferedReader(
                                new InputStreamReader(System.in), 128);
       *  Constructor.  opens a file for reading
       *  @param fileName the name or pathname of the file
      public EasyReader(String fileName)
        myFileName = fileName;
        myErrorFlags = 0;
        try
          myInFile = new BufferedReader(new FileReader(fileName), 1024);
        catch (FileNotFoundException e)
          myErrorFlags |= OPENERROR;
          myFileName = null;
       *  Closes the file
      public void close()
        if (myFileName == null)
          return;
        try
          myInFile.close();
        catch (IOException e)
          System.err.println("Error closing " + myFileName + "\n");
          myErrorFlags |= CLOSEERROR;
       *  Checks the status of the file
       *  @return true if en error occurred opening or reading the file,
       *  false otherwise
      public boolean bad()
        return myErrorFlags != 0;
       *  Checks the EOF status of the file
       *  @return true if EOF was encountered in the previous read
       *  operation, false otherwise
      public boolean eof()
        return (myErrorFlags & EOF) != 0;
      private boolean ready() throws IOException
        return myFileName == null || myInFile.ready();
       *  Reads the next character from a file (any character including
       *  a space or a newline character).
       *  @return character read or <code>null</code> character
       *  (Unicode 0) if trying to read beyond the EOF
      public char readChar()
        char ch = '\u0000';
        try
          if (ready())
             ch = (char)myInFile.read();
        catch (IOException e)
          if (myFileName != null)
            System.err.println("Error reading " + myFileName + "\n");
          myErrorFlags |= READERROR;
        if (ch == '\u0000')
          myErrorFlags |= EOF;
        return ch;
       *  Reads from the current position in the file up to and including
       *  the next newline character.  The newline character is thrown away
       *  @return the read string (excluding the newline character) or
       *  null if trying to read beyond the EOF
      public String readLine()
        String s = null;
        try
          s = myInFile.readLine();
        catch (IOException e)
          if (myFileName != null)
            System.err.println("Error reading " + myFileName + "\n");
          myErrorFlags |= READERROR;
        if (s == null)
          myErrorFlags |= EOF;
        return s;
       *  Skips whitespace and reads the next word (a string of consecutive
       *  non-whitespace characters (up to but excluding the next space,
       *  newline, etc.)
       *  @return the read string or null if trying to read beyond the EOF
      public String readWord()
        StringBuffer buffer = new StringBuffer(128);
        char ch = ' ';
        int count = 0;
        String s = null;
        try
          while (ready() && Character.isWhitespace(ch))
            ch = (char)myInFile.read();
          while (ready() && !Character.isWhitespace(ch))
            count++;
            buffer.append(ch);
            myInFile.mark(1);
            ch = (char)myInFile.read();
          if (count > 0)
            myInFile.reset();
            s = buffer.toString();
          else
            myErrorFlags |= EOF;
        catch (IOException e)
          if (myFileName != null)
            System.err.println("Error reading " + myFileName + "\n");
          myErrorFlags |= READERROR;
        return s;
       *  Reads the next integer (without validating its format)
       *  @return the integer read or 0 if trying to read beyond the EOF
      public int readInt()
        String s = readWord();
        if (s != null)
          return Integer.parseInt(s);
        else
          return 0;
       *  Reads the next double (without validating its format)
       *  @return the number read or 0 if trying to read beyond the EOF
      public double readDouble()
        String s = readWord();
        if (s != null)
          return Double.parseDouble(s);
          // in Java 1, use: return Double.valueOf(s).doubleValue();
        else
          return 0.0;
    }same with this:
    public class p
         public static void l(String S)
          { System.out.println(S);}
         public static void o(String S)
          {System.out.print(S);}
         public static void l(int i)
          { System.out.println(i);}
         public static void o(int i)
          {System.out.print(i);}
         public static void l(boolean b)
          { System.out.println(b);}
         public static void o(boolean b)
          {System.out.print(b);}
        public static void l(char c)
          { System.out.println(c);}
         public static void o(char c)
          {System.out.print(c);}     
         public static void l(double d)
          { System.out.println(d);}
         public static void o(double d)
          {System.out.print(d);} 
        public static void l(Object obj)
          { System.out.println(obj.toString());}
         public static void o(Object obj)
          {System.out.print(obj.toString());}
         public static void l()
          {System.out.println();}
    }       here's my code:
    import java.util.*;
    public class JMM_Pig
         public static void main(String[] args)
              int winner=0;
              int pts=0;
                   JMM_Dice player1=new JMM_Dice();
                   JMM_Dice player2=new JMM_Dice();
                   p.l("Player 1 rolls the dice...");
                   player1.rollDice();
                   player1.updateTotals();
                   boolean loop=true;
                   while(loop)
                   while(player1.numVowels()<=4)
                        p.l("Player 1 continues his turn...");
                        player1.rollDice();
                        player1.updateTotals();
                        p.l("Player 1 rolled a "+player1.getDie1()+" and a "+player1.getDie2()+" and a '"+player1.getDie3()+"' and a '"+player1.getDie4()+"'");
                        p.l("Player 1 rolled "+player1.currvowels()+" vowels.");
                        p.l("Player 1 has "+player1.totalvowels()+" total vowels.");
                        //if(player1.getMagic()==1)
                        //player1.totalPoints=(player1.totalPoints+player1.getDie1()+player1.getDie2())*player1.mult;
                        //pts=(player1.totalPts()+player1.getDie1()+player1.getDie2())*player1.getMult();
                        //player1.setTpts(pts);
                        //if(player1.getMagic()!=1)
                             //player1.totalPoints=player1.totalPoints+player1.getDie1()+player1.getDie2();
                        //pts=player1.totalPts()+player1.getDie1()+player1.getDie2();
                        //player1.setTpts(pts);
                        p.l("Player 1 has "+player1.numSnakes()+" snake eyes.");
                        p.l("Player 1 earned "+player1.ptsreturn()+" points this turn.");
                        p.l("Player 1 has "+player1.totalPts()+" total points.");
                        pts=0;
                        if(player1.totalPts()>=2000)
                             winner=1;
                             player1.setNv(4);loop=false;
                        if((player1.isavowel(player1.getadice()))&&player1.isavowel(player1.getadice2()))
                             player1.setTpts(0);player1.setNv(0);player1.setNv(4);
                   p.l("Player 1's turn has ended...");
                   player1.setNv(0);
                   p.l("Player 2 rolls the dice...");
                   player2.rollDice();
                   player2.setTpts(player2.totalPts()+player2.getDie1()+player2.getDie2());
                   while(player2.numVowels()<=4)
                        p.l("Player 2 continues his turn...");
                        player2.rollDice();
                        player2.updateTotals();
                        p.l("Player 2 rolled a "+player2.getDie1()+" and a "+player2.getDie2()+" and a '"+player2.getDie3()+"' and a '"+player2.getDie4()+"'");
                        p.l("Player 2 rolled "+player2.currvowels()+" vowels.");
                        p.l("Player 2 has "+player2.totalvowels()+" total vowels.");
                        //if(player1.getMagic()==1)
                        //player1.totalPoints=(player1.totalPoints+player1.getDie1()+player1.getDie2())*player1.mult;
                        //pts=(player1.totalPts()+player1.getDie1()+player1.getDie2())*player1.getMult();
                        //player1.setTpts(pts);
                        //if(player1.getMagic()!=1)
                             //player1.totalPoints=player1.totalPoints+player1.getDie1()+player1.getDie2();
                        //pts=player1.totalPts()+player1.getDie1()+player1.getDie2();
                        //player1.setTpts(pts);
                        p.l("Player 2 has "+player2.numSnakes()+" snake eyes.");
                        p.l("Player 2 earned "+player2.ptsreturn()+" points this turn.");
                        p.l("Player 2 has "+player2.totalPts()+" total points.");
                        pts=0;
                        if(player2.totalPts()>=2000)
                             winner=2;
                             player2.setNv(4);loop=false;
                        if((player2.isavowel(player2.getadice()))&&player2.isavowel(player2.getadice2()))
                             player2.setTpts(0);player2.setNv(0);player2.setNv(4);
                   p.l("Player 2's turn has ended...");
                   player2.setNv(0);
                   if(player1.totalPts()>=2000)
                        winner=1;
                        loop=false;
                   if(player2.totalPts()>=2000)
                        winner=2;
                        loop=false;
                   }  //main loop
                   if(winner==1)
                        p.l("It ended with the following statistics...");
                        p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
                        p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
                        p.l("Player 1 wins, oink oink!");
                   if(winner==2)
                        p.l("It ended with the following statistics...");
                        p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
                        p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
                        p.l("Player 2 wins, oink oink!");
    and dice class:
    import java.util.*;
    public class JMM_Dice {
         private static Random gen = new Random();
        private final static int NUM_SIDES = 21;
        private int die1, die2, numSnakeEyes, numVowels, totalPoints;
        private char die3, die4;
        private int dice=0;
           //dice=
           private int dice2=0;
           //dice2=;
           private String adice="";
           //adice=;
           private String adice2="";
           //adice2;
           private int magic=0;
           private int mult=0;
           private int currvowels=0;
           private int totalvowels=0;
      public static EasyReader key = new EasyReader();
      public JMM_Dice()
          dice=0;dice2=0;
           String alpha="abcdefghijklmnopqrstuvwxyz";
          adice="";adice2="";
           rollDice();
           numSnakeEyes=0;numVowels=0;totalPoints=0;
      public void setTpts(int tpts)
           this.totalPoints=tpts;
      public void setNv(int nv)
           this.numVowels=nv;
      public int getDie1()
           return dice;
      public int getDie2()
           return dice2;
      public String getDie3()
           return adice;
      public String getDie4()
           return adice2;
      public int numSnakes()
           return numSnakeEyes;
      public void setSnakes(int s)
           this.numSnakeEyes=s;
      public String getadice()
           return this.adice;
      public String getadice2()
           return this.adice2;
      public int numVowels()
           return numVowels;
      public int getMagic()
           return this.magic;
      public int getNv()
           return this.numVowels;
      public void setMagic(int mag)
           this.magic=mag;
      public int getMult()
           return this.mult;
      public void setMult(int m)
           this.mult=m;
      public int totalPts()
           return totalPoints;
      public String toString()
           return dice+""+dice2+""+adice+""+adice2;
      public boolean isavowel(String str)
           if(str.equals("a")||str.equals("e")||str.equals("i")||str.equals("o")||str.equals("u"))
                return true;
           else
                return false;
      public int ptsreturn()
           return dice+dice2;
      public int currvowels()
           int tmp=currvowels;
           currvowels=0;
           return tmp;
      public int totalvowels()
           return numVowels;
      public void updateTotals()
           if(adice.equalsIgnoreCase("a")||adice.equalsIgnoreCase("e")||adice.equalsIgnoreCase("i")||adice.equalsIgnoreCase("o")||adice.equalsIgnoreCase("u")||adice2.equalsIgnoreCase("a")||adice2.equalsIgnoreCase("e")||adice2.equalsIgnoreCase("i")||adice2.equalsIgnoreCase("o")||adice2.equalsIgnoreCase("u"))
                numVowels++;currvowels++;
           if((isavowel(adice))&&isavowel(adice2))
                totalPoints=0;numVowels=0;
           if(dice==1||dice2==1)
                numSnakeEyes++;
           int fd=dice;
           int sd=dice2;
           int sum=fd+sd;
           totalPoints+=sum*(numSnakeEyes+1);
      public void rollDice()
           dice=gen.nextInt(20)+1;
           dice2=gen.nextInt(20)+1;
           String alpha="abcdefghijklmnopqrstuvwxyz";
           adice=String.valueOf(alpha.charAt(gen.nextInt(26)));
           adice2=String.valueOf(alpha.charAt(gen.nextInt(26)));
      public static void sleep (int wait)
      {     long timeToQuit = System.currentTimeMillis() + wait;
           while (System.currentTimeMillis() < timeToQuit)
                ;   // take no action
    }the program works fine except it's supposed to terminate when one of the two AIs get a score of 2000, right now it terminates no matter what score the AIs get and no matter what I've tried to do it keeps doing that...can someone please tell me why it's terminating so oddly? Thanks! :)

    Here's how my code works in a nutshell, the main program starts with the boolean loop=true;
                   while(loop)
                   {then comes the loops for the two AIs, first the player 1 AI goes with this loop: while(player1.numVowels()<=4)
                   {there the player 1 roles the dice and it keeps going until player 1 gets a total of 2000 points at which time this is supposed to execute: if(player1.totalPts()>=2000)
                             winner=1;
                             player1.setNv(4);loop=false;
                        }, player1.setNv(4); sets numVowels to 4 so that the inner loop exits, loop=false exits the other loop and winner=1; specifies that player 1 won which is used outside of the loops here: if(winner==1)
                        p.l("It ended with the following statistics...");
                        p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
                        p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
                        p.l("Player 1 wins, oink oink!");
                   if(winner==2)
                        p.l("It ended with the following statistics...");
                        p.l("Player 1's score was: "+player1.totalPts()+" and Player 2's score was: "+player2.totalPts());
                        p.l("Player 1 had: "+player1.numSnakes()+" snake eye(s) and Player 2 had: "+player2.numSnakes()+" snake eye(s)");
                        p.l("Player 2 wins, oink oink!");
                   } the same thing happens for player 2 if player 1 didn't already get 2000 points...but the if statement despite everything pointing to the variables containing the right values don't seem to be working, as shown by the example program output I posted it just ends at any random number...hopefully this helps make figuring out what's wrong easier :) ...so can anyone please help me out? thanks! :)

  • Cannot reslove symbol class Date

    I am trying to get a clock to show the time in my program. However, when I try to compile the program a "cannot resolve symbol class Date" error appears. I can't figure out where the problem in my program is. Here is my source code. I would appreciate any help.
    import javax.swing.*;
    import java.io.*;
    import java.lang.*;
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    //import java.util.*;
    import java.math.*;
    public class store
    public static void main(String[] args)
    String dataInput;
         dataInput = JOptionPane.showInputDialog(null, "Input item data: ");
    JOptionPane.showMessageDialog(null, "" + dataInput);
    EasyReader console = new EasyReader();
    int i, j, k, inum, icom, min, nswaps; inum = 0; boolean swap = false;
    double num[] = new double[100]; double dsum, T;
         do
         System.out.println(); System.out.println("Command Menu"); System.out.println();
         System.out.println("1 = Display the data");
    System.out.println("2 = Bubble Sort the numbers");
    System.out.println("3 = Selection Sort the numbers");
    System.out.println("4 = Insertion Sort the numbers");
    System.out.println("5 = Binary Search for a number");
    System.out.println("0 = Exit the program"); System.out.println();
    System.out.print("Enter Command - ");
    icom = console.readInt(); System.out.println();
    switch (icom)
    case 1: // Display the data
                   Display(inum, num);
                   break;
    case 2: // Bubble sort
                   nswaps = 0;
                   for (i = 0; i < (inum-1); i++ )
              for (j = (i+1); j < inum; j++)
                        if (num[i] > num[j])
                                  T = num;
                             num[i] = num[j];
                             num[j] = T;
                             nswaps++;
                   System.out.println("The number of swaps was - " + nswaps);
                   Display(inum, num);
                   break;
    case 3: // Selection sort
                   nswaps = 0;
                   for (i = 0; i < inum - 1; i++) {
              min = i; swap = false;
    for (j = i + 1; j < inum; j++)
         if (num[j] < num[min]) { min = j; swap = true; }
    if (swap) {T = num[min];
              num[min] = num[i];
                        num[i] = T;
                        nswaps++;}
                   System.out.println("The number of swaps was - " + nswaps);
                   Display(inum, num);
                   break;          
    case 4: // Selection sort
                   nswaps = 0;
                   for (i = 1; i < inum; i++)
                   j = i; T = num[i];
                        while ((j > 0) && (T < num[j-1]))
              num[j] = num[j-1]; j--; nswaps++;
                   num[j] = T; nswaps++;
                   System.out.println("The number of swaps was - " + nswaps);
                   Display(inum, num);
                   break;
    case 5: // Binary Search
                   System.out.println("Your numbers will be sorted first");
                   System.out.println();
                   for (i = 1; i < inum; i++)
                   j = i; T = num[i];
                        while ((j > 0) && (T < num[j-1]))
              num[j] = num[j-1]; j--;
                   num[j] = T;
                   System.out.print("Enter the number to locate - ");
                   T = console.readDouble(); nswaps = 0; System.out.println();
                   int left = 0, right = inum, middle; k = -1;
                   while (left <= right)
                        middle = (left + right) / 2;
                        if (T > num[middle]) {left = middle + 1; nswaps++;}
                        else if (T < num[middle]) {right = middle - 1; nswaps++;}
                        else { k = middle; break; }
                   if (k == -1) System.out.println("Your number was not located in the array");
                   else System.out.println("Your number " + T + " is in position " + (k+1));
                   System.out.println();
                   System.out.println(nswaps + " comparisons were needed to search for your number");     
                   Display(inum, num);
                   break;
         } while (icom != 0);
         public static void Display(int inum, double num[])
              {     int k;
                   System.out.println();
                   System.out.println("");
                   System.out.println();
              for (k = 0; k < inum; k++)
              System.out.println((k+1) + " - " + num[k]);
         return;
    class Clock extends Thread
         //A Canvas that will display the current time on the calculator
         Canvas Time;
         //A Date object that will access the current time
         private Date now;
         //A string to hold the current time
         private String currentTime;
         //The constructor for Clock, accepting a Label as an argument
         public Clock(Canvas _Time)
              Time = Time;          //Time is passed by reference, so Time
                                       //now refers to the same Canvas
              start();               //start this thread
         //The overriden run method of this thread
         public void run()
              //while this thread exists
              while (true)
                   try
                        draw_clock();          //calls the draw_clock method
                        sleep(1000);          //puts this thread to sleep for one
                                                 //second
                   //catches an InterruptedException that the sleep() method might throw
                   catch (InterruptedException e) { suspend(); }
                   //catches a NullPointerException and suspends the thread if one occurs
                   catch (NullPointerException e) { suspend(); }
         //A method to draw the current time onto the Time Canvas on the applet
         public void draw_clock()
              try
                   //Obtains the Graphics object from the Canvas Time so that it can
                   //be manipulated directly
                   Graphics g = Time.getGraphics();
                   g.setColor(Color.gray);          //sets the color of the Graphics object
                                                      //to gray for the rectangle background
                   g.fillRect(0,0,165,25);          //fills the Canvas area with a rectangle
                                                      //starting at 0,0 coordinates of the Canvas
                                                      //and extending to the length and width
                   g.setColor(Color.orange);     //sets the color of the Graphics object
                                                      //to orange for the text color
                   get_the_time();                    //calls the get_the_time() method
                   //calls the drawString method of the Graphics object g, which will
                   //draw a string to the screen
                   //Accepts a string and two integers to represent the coordinates
                   g.drawString("Current Time - " + currentTime, 0, 17);          
              //catches a NullPointerException and suspends the thread if one occurs
              catch (NullPointerException e) { suspend(); }
         //A method to obtain the current time, accurate to the second
         public void get_the_time()
              //creates a new Date object for "now" every time this is called
              now = new Date( );
              //integers to hold the hours, minutes and seconds of the current time
              int a = now.getHours();
              int b = now.getMinutes();
              int c = now.getSeconds();
              if (a == 0) a = 12;          //if hours are zero, set them to twelve
              if (a > 12) a = a -12;     //if hours are greater than twelve, make a      
                                            //conversion to civilian time, as opposed to
                                            //24-hour time
              if ( a < 10)               //if hours are less than 10
                   //sets the currentTime string to 0, appends a's value and a
                   //colon
                   currentTime = "0" + a + ":" ;
              else
                   //otherwise set currentTime string to "a", append a colon
                   currentTime = a +":";               
              if (b < 10)                    //if minutes are less than ten
                   //append a zero to string currentTime, then append "b" and a colon
                   currentTime = currentTime + "0" + b + ":" ;
              else
                   //otherwise append "b" and a colon to currentTime string
                   currentTime = currentTime + b + ":" ;
              if (c < 10)                    //if seconds are less than ten
                   //append a zero to string currentTime, then append "c" and a colon
                   currentTime = currentTime + "0" + c ;
              else     
                   //otherwise append "c" to currentTime string
                   currentTime = currentTime + c;
    }          //end of the Clock class

    Wow.
    1) Please in future use the code tags to format code you post so that it doesn't think you have italics in your code and render it largely1 unreadable. Read this
    http://forum.java.sun.com/help.jspa?sec=formatting
    2) You commented out the import of java.util which is the problem you are complaining about.
    3) Are you planning to stick all the code you ever write into the one source file? Why is all this stuff rammed together. Yoinks.

  • Binary search in java

    Hi,
    I keep getting a java.lang.ClassCastException with these two classes when I try to perform a binary search. Any tips?
    Phonebook class:
    =============
    import java.util.*;
    public class Phonebook
    private static long comparisons = 0;
    private static long exchanges = 0;
         public static void main (String[] args)
         // Create an array of Phonebook records
         PhoneRecord[] records = new PhoneRecord[10];
         records[0] = new PhoneRecord("Smith","Bob", 1234367);
         records[1] = new PhoneRecord("Jones","Will", 1234548);
         records[2] = new PhoneRecord("Johnson","Frank", 1234569);
         records[3] = new PhoneRecord("Mc John","Pete", 1234560);
         records[4] = new PhoneRecord("OBrien","Frank", 1234571);
         records[5] = new PhoneRecord("OConnor","Joe", 1234572);
         records[6] = new PhoneRecord("Bloggs","Ricky", 1233570);
         records[7] = new PhoneRecord("empty","empty", 8888888);
         records[8] = new PhoneRecord("empty","empty", 9999999);
         records[9] = new PhoneRecord("Van Vliet","Margreet", 1244570);
         // call menu
         Menu(records);
         } // end main
    //================================================
    // menu
    //================================================
    static void Menu(PhoneRecord[] records)
         int option;
         // menu options
         System.out.println("===========Menu==============================");
         System.out.println("=============================================");
         System.out.println(" ");
         System.out.println("1. Find record (Advanced Search) ");
         System.out.println("2. Quick Search ");
         System.out.println("3. Add a record ");
         System.out.println("4. Show database ");
         System.out.println("5. Sort database ");
         System.out.println("6. Exit     ");
         System.out.println(" ");
         System.out.println("=============================================");
         System.out.println("=============================================");
         System.out.println(" ");
         System.out.println("Choose a number ");
         option = Console.readInt();
         // every menu option has its own method
         if (option == 1)
              FindRecord(records);
         if (option == 2)
              QuickSearch(records);
         else if (option == 3)
              AddRecord(records);
         else if (option == 4)
              ShowDatabase(records);
         else if (option == 5)
              quickSort(records, 0, 9);
              ShowDatabase(records);
         // if 6 then terminate the program
         else
                   System.out.println("Goodbye!");
    } // end of menu
    //=================================================
    // menu option 1: Find a record - using linear search
    //=================================================
    static void FindRecord(PhoneRecord[] records)
    int option;
    do
    // the user can search based on first name or last name
    System.out.println("Do you want to search for:");
    System.out.println("1. First Name");
    System.out.println("2. Last Name");
    System.out.println("3. End search");
    option = Console.readInt();
         // option 1 is search based on first name
         if (option == 1)
              System.out.println("Enter First Name");
              String first = Console.readString();
              int notthere = -1;
              for (int i=0; i < 10; i++)
                   if (first.equals(records.first_Name))
                        System.out.println("----------------------------------");
                        System.out.println(records[i].last_Name + ", " + records[i].first_Name);
                        System.out.println(records[i].phonenumber);
                        System.out.println("----------------------------------\n\n");
                   // if a record is found, the variable notthere will be > -1
                   notthere = i;
              } // end search array
                   // if notthere is -1, then there is no record available
                   if (notthere < 0)
                   System.out.println("------------------------------");
                   System.out.println("No record available");
                   System.out.println("------------------------------\n\n");
         } // end option 1 First Name
         // option 2 allows the user to search based on last name
         else if (option == 2)
              System.out.println("Enter Last Name");
              String last = Console.readString();
              int notthere = -1;
              for (int i=0; i < 10; i++)
                   if (last.equals(records[i].last_Name))
                        System.out.println("----------------------------------");
                        System.out.println(records[i].last_Name + ", " + records[i].first_Name);
                        System.out.println(records[i].phonenumber);
                        System.out.println("----------------------------------\n\n");
                   notthere = i;
                   // if notthere is -1 then there is no record available
                   // if notthere is > -1 then there is a record available
                   } // end search array
                   if (notthere < 0)
                   System.out.println("------------------------------");
                   System.out.println("No record available");
                   System.out.println("------------------------------\n\n");
         } // end option 2 Last Name
         else
              // if the user types in a wrong number, he or she returns to the menu
              Menu(records);
    while (option != 3);
    } // end FindRecord
    //=================================================
    // menu option 2: Quick Search - using binary search
    //=================================================
    static void QuickSearch(PhoneRecord[] records)
         // Sort array - Using Quicksort
         quickSort(records, 0, 9);
         // allow user to enter the last name
         System.out.println("Enter Last Name");
         String last = Console.readString();
         // use binary search to find the target
         int index = binarySearch(records, last);
         // -1 means that there are no records
         if (index == -1)
         System.out.println("------------------------------");
         System.out.println("No record available");
         System.out.println("------------------------------\n\n");
         // print out the record
         System.out.println("----------------------------------");
         System.out.println(records[index].last_Name + ", " + records[index].first_Name);
         System.out.println(records[index].phonenumber);
         System.out.println("----------------------------------\n\n");
         // return to menu
         Menu(records);
    } // end QuickSearch
    public static int binarySearch( Comparable [ ] a, Comparable x )
    int low = 0;
    int high = 9;
    int mid;
    while( low <= high )
    mid = ( low + high ) / 2;
    if( a[ mid ].compareTo( x ) < 0 )
    low = mid + 1;
    else if( a[ mid ].compareTo( x ) > 0 )
    high = mid - 1;
    else
    return mid;
    return -1; // not found
    //=================================================
    // menu option 3: Add a record
    //=================================================
    static void AddRecord(PhoneRecord[] records)
    int option;
    int index = 0;
    // enter details
    do
         // to say that the array is not full yet, I use the variable filled
         int filled = 0;
    System.out.println("Enter the First Name");
    String frst = Console.readString();
    System.out.println("Enter the Last Name");
    String lst = Console.readString();
    System.out.println("Enter the phone number");
    int phn = Console.readInt();
    // search the array for the empty slot
         for (int i=0; i < 10; i++)
              if (records[i].first_Name.equals("empty") && filled == 0)
              records[i].first_Name = frst;
              records[i].last_Name = lst;
              records[i].phonenumber = phn;
              filled = 1;
         // Sort array - Using Quicksort
         quickSort(records, 0, 9);
         // Print out sorted values
         for(int i = 0; i < records.length; i++)
              System.out.println("----------------------------------");
              System.out.println(records[i].last_Name + ", " + records[i].first_Name);
              System.out.println(records[i].phonenumber);
              System.out.println("----------------------------------\n\n");
         System.out.println("Do you want to add more records?");
         System.out.println("1. Yes");
         System.out.println("2. No");
         option = Console.readInt();
         if (option == 2)
              Menu(records);
         // sets the database to full
         int empty = 0;
         for (int i=0; i < 10; i++)
              // empty = 1 means that there is an empty slot
              if (records[i].first_Name.equals("empty"))
                   empty = 1;
         // if the system didn't find an empty slot, the database must be full
         if (empty == 0)
         System.out.println("Database is full");
         option = 2;
         Menu(records);
    while (option != 2);
    } // end AddRecord
    //=================================================
    // menu option 4: Show database
    //=================================================
    static void ShowDatabase(PhoneRecord[] records)
              // shows the entire database
              for (int i=0; i < 10; i++)
                        System.out.println("----------------------------------");
                        System.out.println(records[i].last_Name + ", " + records[i].first_Name);
                        System.out.println(records[i].phonenumber);
                        System.out.println("----------------------------------");
         Menu(records);
    //===============================================
    // Sort array
    //=============================================
    public static void quickSort (Comparable[] a, int left, int right)
         // Sort a[left?right] into ascending order.
         if (left < right) {
         int p = partition(a, left, right);
         quickSort(a, left, p-1);
         quickSort(a, p+1, right);
    static int partition (Comparable[] a, int left, int right)
         // Partition a[left?right] such that
         // a[left?p-1] are all less than or equal to a[p], and
         // a[p+1?right] are all greater than or equal to a[p].
         // Return p.
         Comparable pivot = a[left];
         int p = left;
         for (int r = left+1; r <= right; r++) {
         int comp = a[r].compareTo(pivot);
         if (comp < 0) {
         a[p] = a[r]; a[r] = a[p+1];
    a[p+1] = pivot; p++;          }
         return p;
    } // end class PhoneBook
    PhoneRecord class:
    ================
    public class PhoneRecord implements Comparable
    public int phonenumber;
    public String last_Name;
    public String first_Name;
    public PhoneRecord(String last_Name, String first_Name, int phonenumber)
    this.last_Name = last_Name;
    this.phonenumber = phonenumber;
    this.first_Name = first_Name;
    /* Overload compareTo method */
    public int compareTo(Object obj)
    PhoneRecord tmp = (PhoneRecord)obj;
    // sorting based on last name
    String string1 = this.last_Name;
    String string2 = tmp.last_Name;
    int result = string1.compareTo(string2);
    if(result < 0)
    /* instance lt received */
    return -1;
    else if(result > 0)
    /* instance gt received */
    return 1;
    /* instance == received */
    return 0;

    JosAH wrote:
    prometheuzz wrote:
    bats wrote:
    Hi,
    I keep getting a java.lang.ClassCastException with these two classes when I try to perform a binary search. Any tips?
    ...Looking at your binary search method:
    public static int binarySearch( Comparable [ ] a, Comparable x)I see it expects to be fed Comparable objects. So, whatever you're feeding it, it's not a Comparable (ie: it doesn't implement Comparable), hence the CCE.It's even worse: if an A is a B it doesn't make an A[] a B[].
    kind regards,
    JosMy post didn't make much sense: if there were no Comparables provided as an argument, it would have thrown a compile time error. The problem lies in the compareTo(...) method.

  • Basic blackjack program - help please

    can soemone please still me if this will work?
    this will become a VERY rudimentary blackjack program
    meaning there is no AI.
    this is how i wanted
    You got a "card"
    You got a "card"
    your score is:
    would you like to hit or stay?
    and then if it hits it tells u the dealers score
    then it keeps on doing the same thing..like
    you got a..
    your score is...
    hit or stay?
    and of course im trying to add to ask the user if they want A to be 1 or 11 (which i have but dont know how to incorporate)
    sorry this is my second day learning java so be easy on me.
    no double down or splits or betting is required.
    this is basically a skeleton that im having trouble using
    but i have to use the given randomGenerator
    can somone help me organize this or help me add codes to do this?
    import java.io.*;
    import java.util.*;
    public class blackjack
        public static void main ( String [] args )
            ConsoleReader console = new ConsoleReader( System.in );
            int uscore = ucard1 + ucard2;
            int dscore = dcard1 + dcard2;
            int dcard1; // dealer card1
            int dcard2; // dealer card2
            int dcard3; // dealer card3
            int dcard4; // dealer card4
            int dcard5; // dealer card5
            int ucard1; // user card1
            int ucard2; // user card2
            int ucard3; // user card3
            int ucard4; // user card4
            int ucard5; // user card5
            int hit = 1;
            while (hit == 1)
            Random generator = new Random ();
            int diamonds = 1 + generator.nextInt( 13 );
            int spades = 1 + generator.nextInt( 13 ); 
            int hearts = 1 + generator.nextInt( 13 ); 
            int clubs = 1 + generator.nextInt( 13 ); 
            System.out.println ("Welcome to the Blackjack Game");
            switch ( dcard )
               case 1:   return "Ace";
               case 2:   return "2";
               case 3:   return "3";
               case 4:   return "4";
               case 5:   return "5";
               case 6:   return "6";
               case 7:   return "7";
               case 8:   return "8";
               case 9:   return "9";
               case 10:  return "10";
               case 11:  return "Jack";
               case 12:  return "Queen";
               case 13:  return "King";
            switch ( ucard )
               case 1:   return "Ace";
               case 2:   return "2";
               case 3:   return "3";
               case 4:   return "4";
               case 5:   return "5";
               case 6:   return "6";
               case 7:   return "7";
               case 8:   return "8";
               case 9:   return "9";
               case 10:  return "10";
               case 11:  return "Jack";
               case 12:  return "Queen";
               case 13:  return "King";
           if ( dcard1 + dcard2  == 21) {
                System.out.println("Dealer has Blackjack.  Dealer wins.");
               return false;
          if (  ucard1 + ucard2   == 21) {
              System.out.println("You have Blackjack.  You win.");
               return true;
            System.out.println(" You got "+ ucard1 +"  ");
            System.out.println(" You got "+ ucard2 +"  ");
            if ( value2 == case 1 )
                System.out.println("Would you like your A to be 1 or 11?")
            System.out.println("Your score is " + uscore + ":");
            System.out.println("To hit press 1 and to stay press 2");
            hit = 0;
            hit = console.readInt();
            if ( hit =  1 )
                System.out.println("You got + ucard3 + ")
            System.out.println("Your score is " + uscore + ":");
            System.out.println("To hit press 1 and to stay press 2");
            hit = 0;
            hit = console.readInt();
                System.out.println("You got + ucard4 + ")
            System.out.println("Your score is " + uscore + ":");
            System.out.println("To hit press 1 and to stay press 2");
            hit = 0;
            hit = console.readInt();
            System.out.println("You got + ucard5 + ");
            System.out.println("Your score is " + uscore + ":");
            System.out.println("To hit press 1 and to stay press 2");
            hit = 0;
            hit = console.readInt();
            if (cont = 2);
            System.out.println("Dealer's score is + "dscore" + :");
            System.out.println("Your score is + "uscore" + :");
            if (dscore >= uscore)
                System.out.println("I won! get better!")
            if (uscore > dscore)
                System.out.println("Somehow, you beat me")
            

    Here is an example of what I've done before, and it needs to be fixed in several ways...
    my playing card value enum
    enum PlayingCardValue
        NO_CARD("","", 0, -1),  // placeholder so that ace starts at one
        ACE("A", "ace", 1, 11),  // has two values 1 or 11
        DEUCE("2", "deuce", 2, -1),  // everything else has only 1 numeric value
        THREE("3", "three", 3, -1),  // -1 is a marker that says "don't use this"
        FOUR("4", "four", 4, -1),
        FIVE("5", "five", 5, -1),
        SIX("6", "six", 6, -1),
        SEVEN("7", "seven", 7, -1),
        EIGHT("8", "eight", 8, -1),
        NINE("9", "nine", 9, -1),
        TEN("10", "ten", 10, -1),
        JACK("J", "jack", 10, -1),
        QUEEN("Q", "queen", 10, -1),
        KING("K", "king", 10, -1);
        private String shortName;
        private String name;
        private int value1;  // main valuve
        private int value2;  // -1 if not valid, a positive number if valid (if the ace)
        // enums have private constructors
        private PlayingCardValue(String shortName, String name, int value1, int value2)
            this.shortName = shortName;
            this.name = name;
            this.value1 = value1;
            this.value2 = value2;
        public String getRep()
            return this.shortName;
        public int getValue1()
            return this.value1;
        public int getValue2()
            return this.value2;
        @Override
        public String toString()
            return this.name;
    }my Playing card suit enum
    enum PlayingCardSuit
        SPADES ("spades"),
        HEARTS ("hearts"),
        DIAMONDS("diamonds"),
        CLUBS("clubs");
        private String name;
        private PlayingCardSuit(String name)
            this.name = name;
        @Override
        public String toString()
            return name;
    }My playingcard class
    * http://forum.java.sun.com/thread.jspa?threadID=5184760&tstart=0
    * @author Pete
    class PlayingCard
        private PlayingCardValue value;
        private PlayingCardSuit suit;
        public PlayingCard(PlayingCardValue value, PlayingCardSuit suit)
            this.value = value;
            this.suit = suit;
        public PlayingCardValue getValue()
            return this.value;
        public PlayingCardSuit getSuit()
            return this.suit;
        @Override
        public String toString()
            return this.value + " of " + this.suit;
    }You get the idea?

  • Problem with method just cannot get it to work

    hi. i got a problem in this part of my program. i am to read in a text file and store it in the arrys before printing it out.but i cannot get the file to be read into the array and to be printed out correctly.
    my text file to be read in is something like this:
    Question0
    what is your name
    a: nick
    b: john
    c: peter
    d: jane
    c
    Question1
    what is your most prefered colour
    a: red
    b: blue
    c: green
    d: yellow
    a
    but when i run the code i have written it keeps printing out like this:(excally what is printed out). the entire order is being messes but with no "questionO" which there should be and the "what is your name question being repeated twice, and the second time without the answer.
    what is your name
    a: nick
    b: john
    c: peter
    d: jane
    c
    what is your name
    a: nick
    b: john
    c: peter
    d: jane
    Question1
    what is your most prefered colour
    a: red
    b: blue
    c: green
    d: yellow
    a
    please can you advice me if in any part of this i have gone wrong, and what should i do to solve the probelm. i really need this help thanks.
    my code is:
    static int questionIndex = 0;
    static int mainMenuOption = 0;
    static String []question = new String[20];
    static String []answer = new String[20];
              do {
                   mainMenu();
                   mainMenuOption = Console.readInt("Enter Choice(1-3) :");
                        if (mainMenuOption==2)
                             takeTestOption();
              } while (mainMenuOption!=3);
              public static void mainMenu() {
                   System.out.println("2.Take Test");
                   System.out.println("3.Quit");
                   System.out.println("");
    public static void takeTestOption(){
                        readInQuestion();               
                   public static void takeTestOption(){
                   //     mainMenu();//prints out the menu options to be entered by the users
                        readInQuestion();
                        //printingOutQuestion();               
                   public static void readInQuestion() {
                        String fileName = "apple.txt";
                        FileIn readInFile = new FileIn(fileName);
                        String readInFileText = readInFile.readString();
                        String finalText= "";
                             if(readInFile.getReadStatus() != readInFile.FILE_NOT_FOUND){
                                   while (readInFile.getReadStatus() != readInFile.EOF ){
                                        while (readInFileText.length() !=2) {
                                            finalText = finalText+readInFileText;
                                            readInFileText = readInFile.readString();
                                       question[questionIndex]=finalText;
                                       if (readInFileText.length()==2) {
                                            answer[questionIndex] = readInFileText;
                                       questionIndex++;
                                       readInFileText = readInFile.readString();
                                        printingOutQuestion();
                   public static void printingOutQuestion() {
                        for (int index=0;index<questionIndex; index++){
                             System.out.println(question[index]);
                             System.out.println(answer[index]);
                   }

    You are using a class that was supplied by the teacher (FileIn). This is a class that none of us knows about. If it is small, it would be useful to post that as well.

  • Trouble inputting to an Array...

    I have the following setup:
    CLASS STORAGEBUSINESS
    private ArrayList<Customer> storageCustomer;
    // setters & getters
    public void setCustomers() {
      if (storageCustomer == null)
         storageCustomer = new ArrayList<Customer>();
    public ArrayList getCustomer() {
      return storageCustomer;
    // This method adds a customer ...
    public boolean addCustomer(Object inCustomer)
      if (inCustomer instanceof Customer)
           return getCustomer().add(inCustomer);
      else
         return false;
    }CLASS INTERFACE
    public void createACustomer()
      if (storageBusiness != null)
        Customer customer
         = new Customer(
                    Console.readInt  ("Customer ID created: "),
                    Console.readLine ("Please enter name:  "),
              Console.readLine ("Please enter address: "),
              Console.readInt  ("Please enter contact phone number: "));
                    System.out.println(customer);
        if (storageBusiness.addCustomer(customer))
         System.out.println("\n Customer was added successfully");
        else
         System.out.println("\n Customer was -NOT- added");
      else
             System.out.println("Function did not perform");
    }But for some reason I am not able to input into Array storageCustomer, can anyone help.

    Do you mean that,
    private ArrayList<Customer> storageCustomer;
    public void setCustomers() {
      if (storageCustomer == null)
         storageCustomer = new ArrayList<Customer>();doesn't actually create an array (or array list). I must be way off here. What do I need to create an array? One that is created from Class Customer.

  • HELP with textpad

    hi!
    ok im an extreme beginner to java, i just recently downloaded and installed the jdk compiler and textpad my code compiles fine but when i run it i get this message in the dos window:
    "Exception in thread "main" java.lang.NoClassDefFoundError:'file name'"
    am i missing a class or a path or something?
    any help would be much appreciated as i really need to actully get it working and iv been having alot of problems even installing it!!
    thankx
    -louise

    oh ya and heres the code,just real simple stuff(as i said im only learning)
    /*Write a program that reads in this information, and lets the customer know whether they are in for some money or not.
    Extend this program as follows:
    If the customer does qualify, inform them how much money they will get:
    "     If their balance is greater than 100, then they get 2000
    "     If their balance is greater than 50, (but less than or equal to 100), then they get 1000
    "     If their balance is positive (but less than or equal to 50) then they get 500
    "     Finally if their balance is negative they are told to put some money in their account*/
    public class Bank
         public static void main (String [] args)
              int age, years;
              double balance;
              ConsoleReader console = new ConsoleReader(System.in);
              //prompt user for data
              System.out.print("Please enter your age ");
              age = console.readInt ();
              if(age <18)
                   System.out.print("sorry you must be 18 or over to to be eligible for a loan ");
              else
              System.out.print("please enter the number of years you have been with this bank ");
              years = console.readInt ();
                   if(years >5)
                        System.out.print("congratulations you qualifiy and you get 1000 euro ");
                   else
                        System.out.print("please enter your account balance ");
                        balance = console.readDouble ();
                        if(balance >100)
                             System.out.print("congratulations you qualifiy and you get 1000 euro ");
                        else
                             System.out.print("sorry you are not eligible for a loan ");
                   }and also i know theres nothing really wrong with the code as it runs in the computers it my college..

  • Error when trying to read integer with JCreator

    *********CODE:
    import corejava.*;
    class Reverse {
         public static void main(String[] args) {
              int number;
              number = Console.readint("Please enter an integer: ");
    ***********ERROR:
    --------------------Configuration: TEST - j2sdk1.4.2_15 <Default> - <Default>--------------------
    C:\Documents and Settings\mik\My Documents\JCreator Pro\MyProjects\a\TEST\src\TEST.java:6: cannot access corejava.Console
    bad class file: C:\j2sdk1.4.2_15\jre\lib\ext\corejava.jar(corejava/Console.class)
    class file has wrong version 49.0, should be 48.0
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    number = Console.readint("Please enter an integer: ");
    ^
    1 error
    Process completed.
    Why is this happening ?
    i just cant seem to read an integer from the user no matter what i try :-(
    Edited by: miki85 on Oct 1, 2007 5:37 AM

    Here's one I used to use back in the 1.5 days... I take no credit for the code though.
    package krc.io;
    * Keyboard - static methods for basic line-buffered keyboard input.
    * Author: J. M. Morris (jmm at dcs gla ac uk).
    * Version 1.1 J. M. Morris October 28th 1998.
    * Version 1.2 K. R. Corlett January 27th 2007.
    * Example of use
    * The statements:
    *     i=Keyboard.readInt();
    *     b=Keyboard.readBoolean();
    *     c=Keyboard.readChar();
    *     t=Keyboard.readToken();
    *     s=Keyboard.readString();
    *     System.out.println("> i='"+i+"', b='"+b+"', c='"+c+"', t='"+t+"', and s='"+s+"'");
    * Given the Keyboard input:
    *     "      23    TRue X   Java123   the  rest   "
    * Produce the output:
    *     > i=23, b=true, c='X', t="Java123", and s="  the  rest   "
    * See: the unit tests in the main method for lots more usage examples.
    import java.io.*;
    import java.util.List;
    import java.util.ArrayList;
    public abstract class Keyboard {
        static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        static String bfr = "";
        static int bfrlen = 0;
        static int p = 1; // bfr[p..] contains next input
        // BASIC METHODS - READ THE NEXT WORD AND CONVERT IT TO DESIRED TYPE
        // Consume and return the remainder of current line (end-of-line discarded).
        public static String readString() {
            try {
                if( bfr!=null && p>bfrlen ) readLine();
                eofCheck();
                int t=p; p=bfrlen+1;
                return(bfr.substring(t));
            } catch (IOException ex) {
                System.err.println(ex);
                return "";
        public static String readString(String prompt) {
            print(prompt + " (String) : ");
            return readString();
        // Consume and return a character (which may be an end-of-line).
        public static char readChar() {
            try {
                if( bfr!=null && p>bfrlen ) readLine();
                eofCheck();
                char c = (p==bfrlen ? '\n' : bfr.charAt(p-1));
                p++;
                return(c);
            } catch (StringIndexOutOfBoundsException ex) {
                //just silently swallow the exception !!!
                return((char)0);
            } catch (IOException ex) {
                System.err.println(ex);
                return((char)0);
        public static char readChar(String prompt) {
            print(prompt +" (char) : ");
            return readChar();
        // Consume and return a boolean. Trailing delimiter consumed.
        // Any string other than "true" (case insensitive) is false.
        public static boolean readBoolean() {
            try {
                return new Boolean(getToken()).booleanValue();
            } catch (Exception ex) {
                System.err.println(ex);
                return false;
        public static boolean readBoolean(String prompt) {
            print(prompt + " (boolean) : ");
            return readBoolean();
        // Consume and return an integer. Trailing delimiter consumed.
        public static int readInt() {
            try {
                return Integer.parseInt(getToken());
            } catch (Exception ex) {
                System.err.println(ex);
                return 0;
        public static int readInt(String prompt) {
            print(prompt + " (int) : ");
            return readInt();
        // Consume and return a double. Trailing delimiter consumed.
        public static double readDouble() {
            try {
                return new Double(getToken()).doubleValue();
            } catch (Exception ex) {
                System.err.println(ex);
                return 0.0;
        public static double readDouble(String prompt) {
            print(prompt + " (double) : ");
            return readDouble();
        // ADVANCED PUBLIC METHODS
        // Consume and return the next token (word) from input.
        // The trailing delimiter is also consumed. A token is a maximal sequence
        // of non-whitespace characters.
        public static String readToken() {
            try {
                return getToken();
            } catch (IOException ex) {
                System.err.println(ex);
                return "";
        // The next available character if any (which may be an end-of-line). The
        // character is not consumed. If bfr is empty return null character.
        public static char peekChar() {
            if (bfr==null || p>bfrlen) return('\000');
            else if (p==bfrlen) return('\n');
            else return bfr.charAt(p);
        public static int available() {
        // Number of characters available on this line (including end-of-line,
        // which counts as one character, ie '\n')
            if (bfr==null) return 0;
            else return (bfrlen+1-p);
        public static boolean hasMoreTokens() {
        // Are there more tokens on the current line?
            if(bfr==null) return false;
            int q;
            for(q=p; q<bfrlen && isWhitespace(q); q++);
            return(q<bfrlen);
        public static void skipLine() {
        // Skip any remaining input on this line.
            if(bfr!=null) p = bfrlen+1;
        public static void skipWhitespace() {
        // Consumes whitespaces until a non-whitespace character is entered (which
        // is not consumed).
            try {
                skipWhitespaces();
            } catch (IOException ex) {
                System.err.println(ex);
        public static boolean eof() { // NOT More characters?
        // This method is intended for use when stdin has been redirected from file
            if(available()>0) return false;
            try {
                readLine();
            } catch (IOException ex) {
                System.err.println(ex);
            return (bfr == null);
        public static String pause() {
            print("Press return to continue.");
            return(Keyboard.readString());
        public static boolean isWhitespace(int offset) {
            return (Character.isWhitespace(bfr.charAt(offset)));
        // PRIVATE HELPER METHODS
        private static void readLine() throws IOException {
            p = 0;
            bfrlen = 0;
            bfr = null;
            bfr = stdin.readLine();
            bfrlen = bfr.length();
        private static String getToken() throws IOException {
        // Consumes and returns the next word from input.
            skipWhitespaces();
            int t = p++;
            while( p<bfrlen && !(isWhitespace(p)) ) p++;
            return(bfr.substring(t,p++));
        private static void skipWhitespaces() throws IOException {
        // Consumes input until a non-whitespace character is entered (which
        // is not consumed).
            while ( bfr!=null && (p>=bfrlen||isWhitespace(p)) ) {
                if (p>=bfrlen) {
                    readLine();
                } else {
                    p++;
        private static void eofCheck() throws IOException {
            if(bfr==null) throw new IOException("Unexpected end of file.");
        private static void print(String msg) {
            System.out.print(msg);
        private static void println(String msg) {
            System.out.println(msg);
        // test harness
        public static void main(String[] args) {
            int i;
            double d;
            char c;
            boolean b;
            String s, t, u;
            println("TEST KEYBOARD VERSION 1.1");
            println("-------------------------");
            print("\nEnter a sequence of integers, terminated by -9: ");
            do {
                i = Keyboard.readInt();
                println("> i=^"+i+"^");
            } while(i!=-9);
            print("\nEnter integer character double boolean string: ");
            i = Keyboard.readInt(); println(""+i);
            c = Keyboard.readChar(); println(""+c);
            d = Keyboard.readDouble(); println(""+d);
            b = Keyboard.readBoolean(); println(""+b);
            s = Keyboard.readString(); println(s);
            pause();
            // Test for the empty string
            print("\nTest no input: ");
            s = pause();
            println("> expect s=^^; s=^"+s+"^");
            // Test readInt eats trailing spaces
            println("\nTest readInt eats trailing spaces: Copy & paste the below line:");
            println("3 ");
            i = Keyboard.readInt();
            s = Keyboard.readString();
            println("> expect s=^^; s=^"+s+"^");
            // Test skipWhitespace
            println("\nTest skipWhitespace: Copy & paste the below line");
            println("      123");
            Keyboard.skipWhitespace();
            c = Keyboard.peekChar();
            println("The first non-whitespace you entered was: "+c);
            println("There should be 3 characters available is: "+Keyboard.available());
            Keyboard.skipLine();
            c = Keyboard.peekChar();
            if (c == '\000') println("Nothing available.");
            else println("Available c=^"+c+"^");
            // Test read methods
            println("\nTest read methods: Copy & paste the below line");
            println("      23    TRue X   Java123   the  rest   ");
            i = Keyboard.readInt(); println("> i=^"+i+"^");
            b = Keyboard.readBoolean();  println("> b=^"+b+"^");
            c = Keyboard.readChar(); println("> c=^"+c+"^");
            t = Keyboard.readToken();  println("> t=^"+t+"^");
            s = Keyboard.readString(); println("> s=^"+s+"^");
            // Test hasMoreTokens()
            println("\nTest hasMoreTokens: Enter several words on a line : ");
            List<String> list = new ArrayList<String>(10);
            do {
                list.add(Keyboard.readToken());
            } while(Keyboard.hasMoreTokens());
            Keyboard.skipLine();
            for (String item : list) {
                println("> " + item);
            // Test available()
            println("Test available: Enter an arbitrary line of text");
            s = "";
            c = Keyboard.readChar(); s += c;
            while(Keyboard.available()>0) {
                c = Keyboard.readChar(); s += c;
            println(s);
    }Edited by: corlettk on Oct 1, 2007 1:12 PM

  • Find Logical Erros Causing an Odd Error in BlackJack

    This doesn't happen too often but sometimes it does.
    I can't seem to find a reason why.
    If i enter 1, it should enter the while loop but it instead ends the process.
    --------------------Configuration: <Default>--------------------
    You drew a 10
    You drew a Queen
    Your score is 20
    Press 1 to hit or 2 to stand
    1
    Process completed.
    This seems to me that whenever I go over 21, it ends everything
    can someone find an error to what might be causing the problem?
    If you need ConsoleReader tell me
    import java.io.*;
    import java.util.*;
    class BlackJackFixed
    public static void main ( String [] args)
            int cont = 1;
        ConsoleReader console = new ConsoleReader( System.in );
        Random generator=new Random();
        int pscore = 0; //playerscore
        int dscore = 0; // dealerscore
         int pcard1 = 1 + generator.nextInt(13);
         int pcard2 = 1 + generator.nextInt(13);
         int dcard1 = 1 + generator.nextInt(13);
         int dcard2 = 1 + generator.nextInt(13);
         if(pcard1 == 1)
        System.out.println("You drew an A. Would you like it to be 1 or 11?");
         int ace = console.readInt();
         System.out.println("Your ace is now " +ace);
         pcard1 = ace;
         else if(pcard1 == 11)
         System.out.println("You drew a Jack");
         pcard1 = 10;
         else if(pcard1 == 12)
         System.out.println("You drew a Queen");
         pcard1 = 10;
         else if(pcard1 == 13)
         System.out.println("You drew a King");
         pcard1 = 10;
         else if (pcard1 <= 10 || pcard1 != 1)
         System.out.println("You drew a " + (pcard1));
         if(pcard2 == 1)
        System.out.println("You got an A. Would you like it to be 1 or 11?");
         int ace = console.readInt();
         System.out.println("Your ace is now " +ace);
         pcard2 = ace;
         else if(pcard2 == 11)
         System.out.println("You drew a Jack");
         pcard2 = 10;
         else if(pcard2 == 12)
         System.out.println("You drew a Queen");
         pcard2 = 10;
         else if(pcard2 == 13)
         System.out.println("You drew a King");
         pcard2 = 10;
         else if (pcard2 <= 10 || pcard2 != 1)
         System.out.println("You drew a " + (pcard2));
         pscore = pcard1 + pcard2;
         dscore = dcard1 + dcard2; // dealers card to check BlackJack
         if(pcard1 + pcard2 == 21)
         System.out.println("You win. You have BLACKJACK!");
         else if(dcard1 + dcard2 == 21)
         System.out.println("Dealer BlackJack. You lose");
         else if(pscore < 21)
         System.out.println("Your score is " + (pscore));
         System.out.println("Press 1 to hit or 2 to stand");
         cont = 0;
         cont = console.readInt();
       while(cont == 1 && pscore < 21 && dscore < 21)
        int pcard3 = 1 + generator.nextInt(13);
        dscore = dcard1 + dcard2;
         if(pcard3 == 1)
        System.out.println("You got an A. Would you like it to be 1 or 11?");
         int ace = console.readInt();
         System.out.println("Your ace is now " +ace);
         pcard3 = ace;
         else if(pcard3 == 11)
         System.out.println("You drew a Jack");
         pcard3 = 10;
         else if(pcard3 == 12)
         System.out.println("You drew a Queen");
         pcard3 = 10;
         else if(pcard3 == 13)
         System.out.println("You drew a King");
         pcard3 = 10;
         else if (pcard3 <= 10 || pcard3 != 1)
         System.out.println("You drew a " + (pcard3));
         pscore += pcard3;     
         if(pscore > 21)
         System.out.println("Busted. You went over 21. Quit Gambling");
         if(dscore > 21)
         System.out.println("Dealer is Busted. It went over 21. Bad Computer!");
         else if(pcard1 + pcard2 == 21)
         System.out.println("BlackJack! You Win!");
         else if(pscore < 21) //did not use else just to be safe
         System.out.println("Your total is " + (pscore));
         System.out.println("Dealer total is " + (dscore));
         System.out.println("Press 1 to hit or 2 to stand");
         cont = 0;
         cont = console.readInt();
      while (dscore < 17 && pscore < 21)
        int dcard4 = 1 + generator.nextInt(13);
        System.out.println("Deaer total is " + ( dscore ));
           System.out.println("Dealer drew a " +(dcard4));
            dscore += dcard4;
             if(pscore > dscore || dscore > 21)
          System.out.println("You win");
          System.out.println("Dealer has " +(dscore));
          break;
          if(dscore > pscore || pscore > 21)
          System.out.println("You lose!");
          System.out.println("Dealer has " +(dscore));
          break;
          else if(dscore == pscore)
          System.out.println("It's a Draw. Dealer also had " +(pscore)); // used pscore just to be safe.
          break;
            while (cont == 2 && pscore < 21 && dscore < 21)
             while (dscore < 17)
             int dcard4 = 1 + generator.nextInt(13);     
             System.out.println("Deaer total is " + ( dscore ));
             System.out.println("Dealer drew a " +(dcard4));
             dscore += dcard4;
          if(pscore > dscore || dscore > 21)
          System.out.println("You win");
          System.out.println("Dealer has " +(dscore));
          break;
          else if(dscore > pscore || pscore > 21)
          System.out.println("You lose!");
          System.out.println("Dealer has " +(dscore));
          break;
          else if(dscore == pscore)
          System.out.println("It's a Draw.");
          break;
    }.

    import java.io.*;
    import java.util.*;
    class BJF2
        public static void main(String[] args)
            int cont = 1;
            int test = 1; //replay
            ConsoleReader console = new ConsoleReader( System.in );
            Random generator=new Random();
            int pscore = 0; //playerscore
            int dscore = 0; // dealerscore
            int pcard1 = 1 + generator.nextInt(13);
            int pcard2 = 1 + generator.nextInt(13);
            int dcard1 = 1 + generator.nextInt(13);
            int dcard2 = 1 + generator.nextInt(13);
            System.out.println("Welcome to the World of BlackJack");
            System.out.println("Remember that We're Follwoing the English Royal Rule");
            System.out.println("This means the Computer will HIT only if his " +
                               "score is less than 17 \n");
            if(pcard1 == 1)
                System.out.println("You drew an A. Would you like it to be 1 or 11?");
                int ace = console.readInt();
                System.out.println("Your ace is now " +ace);
                pcard1 = ace;
            else if(pcard1 == 11)
                System.out.println("You drew a Jack");
                pcard1 = 10;
            else if(pcard1 == 12)
                System.out.println("You drew a Queen");
                pcard1 = 10;
            else if(pcard1 == 13)
                System.out.println("You drew a King");
                pcard1 = 10;
            else //if (pcard1 <= 10 || pcard1 != 1)
                System.out.println("You drew a " + (pcard1));
            if(pcard2 == 1)
                System.out.println("You got an A. Would you like it to be 1 or 11?");
                int ace = console.readInt();
                System.out.println("Your ace is now " +ace);
                pcard2 = ace;
            else if(pcard2 == 11)
                System.out.println("You drew a Jack");
                pcard2 = 10;
            else if(pcard2 == 12)
                System.out.println("You drew a Queen");
                pcard2 = 10;
            else if(pcard2 == 13)
                System.out.println("You drew a King");
                pcard2 = 10;
            else //if (pcard2 <= 10 || pcard2 != 1)
                System.out.println("You drew a " + (pcard2));
            if(dcard1 == 11)
                dcard1 = 10;
            else if(dcard1 == 12)
                dcard1 = 10;
            else if(dcard1 == 13)
                dcard1 = 10;
            if(dcard2 == 11)
                dcard2 = 10;
            else if(dcard2 == 12)
                dcard2 = 10;
            else if(dcard2 == 13)
                dcard2 = 10;
            pscore = pcard1 + pcard2;
            dscore = dcard1 + dcard2; // dealers card to check BlackJack
            if(pscore == 21)
                System.out.println("You win. You have BLACKJACK!");
            else if(dscore == 21)
                System.out.println("Dealer BlackJack. You lose");
            else if(pscore < 21)
                System.out.println("Your score is " + (pscore));
                System.out.println("Press 1 to hit or 2 to stand");
                cont = 0;
                cont = console.readInt();
            // Player goes first:
            // This loop does not need to be concerned about dscore.
            // The player has selected a hit so we will stay in this
            // loop as long as the player continues to select another hit.
            while(cont == 1)
                int pcard3 = 1 + generator.nextInt(13);
                if(pcard3 == 1)
                    System.out.println("You got an A. Would you like it to be 1 or 11?");
                    int ace = console.readInt();
                    System.out.println("Your ace is now " +ace);
                    pcard3 = ace;
                else if(pcard3 == 11)
                    System.out.println("You drew a Jack");
                    pcard3 = 10;
                else if(pcard3 == 12)
                    System.out.println("You drew a Queen");
                    pcard3 = 10;
                else if(pcard3 == 13)
                    System.out.println("You drew a King");
                    pcard3 = 10;
                else //if (pcard3 <= 10 || pcard3 != 1)
                    System.out.println("You drew a " + (pcard3));
                pscore += pcard3;
                if(pscore > 21)
                    System.out.println("Busted. You went over 21.");
                if(pscore >= 21)
                    break;
                System.out.println("Your total is " + (pscore));
                System.out.println("Dealer total is " + (dscore));
                System.out.println("Press 1 to hit or 2 to stand");
                cont = 0;  // I don't see the need for this line.
                cont = console.readInt();
            // The player has finished their turn.
            // Now it's the dealer's turn:
            // The dealer only plays if the player is still in the game.
            if(pscore <= 21)
                while(dscore < 17)
                    int dcard4 = 1 + generator.nextInt(14);
                    System.out.println("Deaer total is " + ( dscore ));
                    if(dcard4 == 11)
                        System.out.println("Dealer drew a Jack");
                        dcard4 = 10;
                    else if(dcard4 == 1)
                        System.out.println("Dealer drew an ACE and used it as a 1");
                        dcard4 = 1;
                    else if(dcard4 == 14)
                        System.out.println("Dealer drew an ACE and used it as a 11");
                        dcard4 = 11;
                        /* Used Random ACE Selection for Computer without AI to make it
                           slightly easier for the player to win */
                    else if(dcard4 == 12)
                        System.out.println("Dealer drew a Queen");
                        dcard4 = 10;
                    else if(dcard4 == 13)
                        System.out.println("Dealer drew a King");
                        dcard4 = 10;
                    else if(dcard4 <= 10)
                        System.out.println("Dealer drew a " +(dcard4));
                    dscore += dcard4;
                    if(dscore > 21)
                        System.out.println("Dealer is Busted. It went over 21.");
            // The dealer has finsihed it's turn.
            // Now, if the game is still on, we evaluate the scores for each.
            if(pscore <= 21 && dscore <= 21)
                if(pscore > dscore)
                    System.out.println("You win");
                    System.out.println("Dealer has " +(dscore));
                else if(dscore > pscore)
                    System.out.println("You lose!");
                    System.out.println("Dealer has " +(dscore));
                else if(dscore == pscore)
                    // used pscore just to be safe.
                    System.out.println("It's a Draw. Dealer also had " +(pscore));
    }

  • Advice for problem

    I'm having trouble with an inheritance problem. I'm trying to use menu-based inheritance on a problem. Can someone look at this and give me some input. In particular when I try to pass user input to savings or checking, what am I doing wrong.
    Here is the code
    public class Account extends Object
        // Fields
       protected String customerName;
       protected String acctID;
       protected double balance;
       // Three-parameter constructor
             public Account(String name, String id, double bal)
              setFields( name, id, bal );
             public void setFields( String s, String ss, double b )
              setCustomerName( s );
              setAccountID( ss );
              setBalance( b );
             public void setCustomerName(String s)
              customerName = s;
         public void setAccountID(String s)
              acctID = s;
            public void setBalance(double bal)
              balance = bal;
             public String getCustomerName()
            return customerName;
             public String getAccountID()
            return acctID;
             public double getBalance()
            return balance;
             public void printBalance()
         System.out.println("\nBalance: " + balance );      
             public String toString()
           return "\nCustomer: " + customerName + "  AcctID: " + acctID + "  Balance: " + balance;
        public void withdraw(double balance)
         balance=balance-balance;
        public void deposit(double balance)
              balance=balance +balance;
        // Display a menu and read selection from console
        private int accountMenu()
              String s =  "\n1 Deposit" +
                             "\n2 Withdraw" +
                             "\n3 Balance" +
                             "\n4 Print toString" +
                             "\n5 Quit\n\nSelect from menu:";
             return Console.readInt( s );
        // manipulate the account
        public void manipulate()
              int choice = accountMenu();
              while( choice != 5 )
                   switch( choice )  {
                        case 1: deposit(balance);
                        String Dprompt=Console.readString("Choose 1 for savings and 2 for checking");
                             {if(Dprompt=="1")
                                  SavingsAccount.deposit(balance);
                             else
                                  CheckAccount.deposit(balance);
                        break;
                        case 2: withdraw(balance);
                        String Wprompt=Console.readString("Choose 1 for savings and 2 for checking");
                             {if(Wprompt=="1")
                                  SavingsAccount.withdraw(balance);
                             else
                                  CheckAccount.withdraw(balance);
                        break;
                        case 3: printBalance();
                        break;
                        case 4: System.out.println( toString() );
                        break;
                        case 5: return;
                        default: System.out.println("Select from menu.");
                        break;
                   choice = accountMenu();
    } // END OF CLASS
    public SavingsAccount extends Account
         private double intRate;
         private int interest;
         public SavingsAccount(String a,String b,int c)
              super(a,b,c);
           public void deposit(double balance)
              double intDeposit=Console.readInt("Enter amount to deposit");     
              balance=balance+intDeposit;
              balance=balance+interest;
           public void addInterest()
         intRate=Console.readDouble("Enter interest rate:);
             double interest = super.getBalance() * intRate/100.0;
             super.deposit(interest);
    }//end of savings
    class CheckAccount extends Account
              private int transCount=0;
           private static final int Free_Transactions=5;
           private static final double Transaction_Fee=5.0;
         public CheckAccount(String a, String b, int c)
              super(a,b,c);
         public  void deposit(double amt)
                transCount++;
              super.deposit(amt);
         public void withdraw(double amt)
              transCount++;
              super.withdraw(amt);
              deductFees();
         public void deductFees()
              if (transCount>Free_Transactions)
                   double fees=Transaction_Fee*(transCount-Free_Transactions);
                   super.withdraw(fees);
                 transCount=0;
    }//end of checking
    public class TestAccount
         public static void main( String[] args )
              Account [] accts = new Account [ 6 ];
              accts[0] = new Account( "Smith", "SMI00189", 1000 );
              accts[1] = new Account( "Brooks", "BRO00524", 2000 );
              accts[2]=new SavingsAccount("Millner","MIL5679", 3000);
              accts[3]=new SavingsAccount("Millner","MIL5699", 6000);
              accts[4]=new CheckAccount("Webber","WEb9612", 3000);
              accts[5]=new CheckAccount("Bibby","Bib1489", 5000);
              for( int i = 0; i < accts.length; i++ )
                   accts.manipulate();
    }     // end of class TestAccount
    thanks

    Updated code:
    public class Account extends Object
        // Fields
       protected String customerName;
       protected String acctID;
       protected double balance;
          // Three-parameter constructor
          public Account(String name, String id, double bal)
              setFields( name, id, bal );
             public void setFields( String s, String ss, double b )
              setCustomerName( s );
              setAccountID( ss );
              setBalance( b );
             public void setCustomerName(String s)
              customerName = s;
         public void setAccountID(String s)
              acctID = s;
            public void setBalance(double bal)
              balance = bal;
             public String getCustomerName()
            return customerName;
             public String getAccountID()
            return acctID;
             public double getBalance()
            return balance;
             public void printBalance()
         System.out.println("\nBalance: " + balance );      
             public String toString()
           return "\nCustomer: " + customerName + "  AcctID: " + acctID + "  Balance: " + balance;
        public void withdraw()
         double witAmount=Console.readDouble("Enter amount to withdraw:");
              if(balance>witAmount)
                   balance=balance-witAmount;
              else
                   System.out.println("Insufficient Funds you only have "+balance+ "available");
                    witAmount=Console.readDouble("Enter amount to withdraw");
                   balance=balance-witAmount;
        public void deposit()
        {          double amtDeposit=Console.readDouble("Enter amount to deposit");
              balance+=amtDeposit;
        // Display a menu and read selection from console
        private int accountMenu()
              String s =  "\n1 Deposit" +
                       "\n2 Withdraw" +
                       "\n3 Balance" +
                       "\n4 Print toString" +
                       "\n5 Quit\n\nSelect from menu:";
                 return Console.readInt( s );
        // manipulate the account
        public void manipulate()
              int choice = accountMenu();
              while( choice != 5 )
                   switch( choice )  {
                        case 1: deposit();
                        break;
                        case 2: withdraw();
                        break;
                        case 3: printBalance();
                        break;
                        case 4: System.out.println( toString() );
                        break;
                        case 5: return;
                        default: System.out.println("Press enter to quit.");
                        break;
                   choice = accountMenu();
    } // END OF CLASS
    public SavingsAccount extends Account
         private int intRate;
         private int interest;
         public SavingsAccount(String a,String b,double c)
              super(a,b,c);
              intRate=0.0;
           public double addInterest()
         intRate=Console.readDouble("Enter interest rate:");
             interest = super.getBalance() * intRate/100.0;
            super.deposit(interest);
    }//End of savingsaccount
    class CheckAccount extends Account
              private int transCount=0;
           private static final int Free_Transactions=5;
           private static final double Transaction_Fee=5.0;
         public CheckAccount(String a, String b, double c)
              super(a,b,c);
         public  void deposit()
                transCount++;
              super.deposit();
         public  void withdraw()
              transCount++;
              super.withdraw();
         public void deductFees()
              if (transCount>Free_Transactions)
                   double fees=Transaction_Fee*(transCount-Free_Transactions);
                   balance=balance-fees;
                 transCount=0;
    }//end of checking account
    public class TestAccount
         public static void main( String[] args )
              Account [] accts = new Account [ 6 ];
              accts[0] = new Account( "Smith", "SMI00189", 1000 );
              accts[1] = new Account( "Brooks", "BRO00524", 2000 );
              accts[2]=new SavingsAccount("Millner","MIL5679", 3000);
              accts[3]=new SavingsAccount("Millner","MIL5699", 6000);
              accts[4]=new CheckAccount("Webber","WEb9612", 3000);
              accts[5]=new CheckAccount("Bibby","Bib1489", 5000);
              for( int i = 0; i < accts.length; i++ )
                   accts.manipulate();
    }     // end of class TestAccount
    I'm still getting the two errors about wrong number of arguments
    in constructor. I don't know why it keeps telling me this when I
    only have 3 arguments in the SavingsAccount contstructor.
    Any suggestions on how I can remedy this problem.
    Thanks

  • Non graphical Applications

    Hi
    A lot of classes exist for helping creating Graphical Applications. But can anyone tell if there's classes for creating non Graphical Applications - that is 'good old' character based user interfaces meant to run through a telnet session.
    Regards
    Hans Peter

    I dont know general classes for that, sure you will spend more time trying to find it, that writing it. Maybe this could be an example:
    public class Class
    /** Here you variables */
    int op = 0;
    int op1= 0;
    public static void main (String args[])
    while( op!=N)
         menuPrincipal();
         op = Console.readInt( " Seleccion: " );
         System.out.println();
         switch( op )
         case 1:
         /** some method */          
         break;
         case 2:
         /** some method */
         break;
         case N:
         op1 = 0;
         while( op1 != M )
              menu2();
              op1 = Console.readInt( " Seleccion: " );
              System.out.println();     
              switch( op1 )
              case 1:
              /* some method */
    break;
              case 2:
              /* some method */          
         break;
         break;
              public static void menu1()
              System.out.print("\n");
              System.out.println(" Flechado de Villa Euler " );
              System.out.println("--------------------------");
              System.out.println();
              System.out.println(" 1. Cargar Grafo");
              System.out.println(" 2. Mostrar Grafo");
              System.out.println(" 3. Mostrar Alcances " );
              System.out.println(" 4. Imprimir Conjunto de Nodos y Lados " );
              System.out.println(" 5. Recorridos " );
              System.out.println(" 6. Salir " );
              System.out.println();
              public static void menu2()
              System.out.print("\n");
              System.out.println(" Recorridos >>> " );
              System.out.println();
              System.out.println(" 1. Circuito Euleriano");
              System.out.println(" 2. DFS ");
              System.out.println(" 3. BFS " );
              System.out.println(" 4. DFS con costos " );
              System.out.println(" 5. BFS con costos " );
              System.out.println(" 6. Dijkstra Secuencial " );
              System.out.println(" 7. Dijkstra HEAP " );
              System.out.println(" 8. A* (opcion a)" );
              System.out.println(" 9. A* (opcion b) ");
              System.out.println(" 10. Volver al menu principal");
         System.out.println();
    /** the implemention of your methods ... or whatever*/
    Regards, JTWN

  • Help how to simplify this problem code.

    Is there a way to edit the code to enable that i don have so many if statements..
    what can do to improve pls help.
    my code is:
    public class tradeFair1 {
         public static void main(String[]arguments){
              double studentM=1.00, studentA=1.20, studentE=3.50;
              double SnrCitizenM=1.20,SnrCitizenA=1.50, SnrCitizenE=3.50;
              double GenPubM=2.00, GenPubA=2.50, GenPubE=3.50;
              boolean weekDays = false;
              double price, status;
         int day = Console.readInt("Enter 1 for Monday, 2 for Tuesday.....6 for Saturday, 7 for Sunday: ");
         int buyer = Console.readInt("Enter 1 for Student, 2 for SnrCitizen, and 3 for GeneralPublic: ");
    int timeOfDay = Console.readInt("Enter the timeOfDay 1 for Morning, 2 for afternoon, 3 for evening: ");
              int numOfTickets = Console.readInt("Enter the number of Tickets");
                   if (day >= 1 && day <= 5) {
                        weekDays = true;
                        if (buyer==1 && timeOfDay==1) {
                             status = studentM;
                             price = numOfTickets*status;;
                             if (numOfTickets >=10 && numOfTickets <=15)
                                  price = price -(price*0.1);
                                  if (numOfTickets >15)
                                  price = price - (price*0.15);
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (buyer==1 && timeOfDay==2) {
                             status = studentA;
                             price = numOfTickets*status;;
                             if (numOfTickets >=10 && numOfTickets <=15)
                                  price = price - (price*0.1);
                                  if (numOfTickets >15)
                                  price = price - (price*0.15);
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (buyer==1 && timeOfDay==3) {
                             status = studentE;
                             price = numOfTickets*status;;
                             if (numOfTickets >=10 && numOfTickets <=15)
                                  price = price - (price*0.1);
                                  if (numOfTickets >15)
                                  price = price - (price*0.15);
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (buyer==2 && timeOfDay==1) {
                             status = SnrCitizenM;
                             price = numOfTickets*status;;
                             if (numOfTickets >=10 && numOfTickets <=15)
                                  price = price - (price*0.1);
                                  if (numOfTickets >15)
                                  price = price - (price*0.15);
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (buyer==2 && timeOfDay==2) {
                             status = SnrCitizenA;
                             price = numOfTickets*status;;
                             if (numOfTickets >=10 && numOfTickets <=15)
                                  price = price - (price*0.1);
                                  if (numOfTickets >15)
                                  price = price - (price*0.15);
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (buyer==2 && timeOfDay==3) {
                             status = SnrCitizenE;
                             price = numOfTickets*status;;
                             if (numOfTickets >=10 && numOfTickets <=15)
                                  price = price - (price*0.1);
                                  if (numOfTickets >15)
                                  price = price - (price*0.15);
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (buyer==3 && timeOfDay==1) {
                             status = GenPubM;
                             price = numOfTickets*status;;
                             if (numOfTickets >=10 && numOfTickets <=15)
                                  price = price - (price*0.1);
                                  if (numOfTickets >15)
                                  price = price - (price*0.15);
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (buyer==3 && timeOfDay==2) {
                             status = GenPubA;
                             price = numOfTickets*status;;
                             if (numOfTickets >=10 && numOfTickets <=15)
                                  price = price - (price*0.1);
                                  if (numOfTickets >15)
                                  price = price - (price*0.15);
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (buyer==3 && timeOfDay==3) {
                             status = GenPubE;
                             price = numOfTickets*status;
                             if (numOfTickets >=10 && numOfTickets <=15)
                                  price = price - (price*0.1);
                                  if (numOfTickets >15)
                                  price = price - (price*0.15);
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                   else if (weekDays = false) {
                        if (timeOfDay ==1) {
                             status = GenPubM;
                             price = numOfTickets*status+0.50;
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (timeOfDay ==2) {
                             status = GenPubA;
                             price = numOfTickets*status+0.50;
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);
                        if (timeOfDay ==3) {
                             status = GenPubE;
                             price = numOfTickets*status+0.50;
                             price = price + (price*0.05);
                             System.out.println("The price is: $" +price);

    this is total aircode - just to give you an idea
    class TradeFair1
      double[][] prices = {{1.00,1.20,3.50},{1.20,1.50,3.50},{2.00,2.50,3.50}};
      double cost = 0;
      public TradeFair1()
        int buyer = Console.readInt("Enter 1 for Student, 2 for SnrCitizen, and 3 for GeneralPublic: ") - 1;
        int timeOfDay = Console.readInt("Enter the timeOfDay 1 for Morning, 2 for afternoon, 3 for evening: ") - 1;;
        int numOfTickets = Console.readInt("Enter the number of Tickets");
        int day = Console.readInt("Enter 1 for Monday, 2 for Tuesday.....6 for Saturday, 7 for Sunday: ");
        double disc;
        if(numOfTickets < 10) disc = 1.00;
        else if(numOfTickets < 16) disc = 0.90;
        else disc = 0.85;
        if(day < 6) cost = numOfTickets * prices[buyer][timeOfDay] * disc;
        else cost = numOfTickets * prices[2][timeOfDay] + 0.50;
      public static void main(String[]arguments){new TradeFair1();}
    }

Maybe you are looking for

  • Utl file in report

    hai all, I have to develop a report using utl file. Like when the report is given a parameter some four columns are displayed, at the same time i want to write the data in a text file in the server path /usr/tmp. used formula column for utl file open

  • Some files not showing up in iPhoto

    I used the Grand Perspective app on my iPhoto library package to find large video files I could reduce to save space. In the process, I've found some files that are in the package but aren't displayed in iPhoto. If I do a search for the file in iPhot

  • Data not retrieved although it exist in the database

    Hi I have the following sql statements. Am supposed to find the no. of lots per dept and the percentage which is from the same table. Table is PWRKF2MV. The problem is that when one of the query (eq. from c) has no data the following query will resul

  • After updating ios7.0.3 on my ipad 4 I found I can't use imessage. How do I fix it?

    After updating my ipad4 with ios 7.0.3 i found I can no longer send messages through imessage. It worked fine before. Any ideas

  • Unable to login / create account / receive a new p...

    hello, i have following problem: my emailadress is luxuspur _at_ gmail dot com  i register my email in the beta phase of messaging. after the release i want to try the app again and try to login.. i can't remember so password so i try to get a new on