Parsing a date error.help with small program

I would like to read from a file which the user can choose on start of program. I want to read line for line, checking if the format of each is ok. if it is , I add it to ArrayList of good books, if not I add it to ArrayList of error books. The date isnt parsing correctly.
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Book {
    String isbn;
    int copyNumber;
    String title;
    String author;
    int statistics;
    Date borrowDate = new Date();
    Date returnDate = new Date();
    int libraryCardNumber;
    DateFormat formatter = new SimpleDateFormat("yy/mm/dd");
public Book(String newIsbn, int newCopyNumber, String newTitle, String newAuthor,
        int newStatistics, Date newBorrowDate, Date newReturnDate, int newLibraryCardNumber)
    isbn = newIsbn;
    copyNumber = newCopyNumber;
    title = newTitle;
    author = newAuthor;
    statistics = newStatistics;
    borrowDate = newBorrowDate;
    returnDate = newReturnDate;
    libraryCardNumber = newLibraryCardNumber;
public Book(){
public Book(String newRow) throws ParseException
    String[] token = newRow.split("#");
                isbn = token[0];
                copyNumber = Integer.parseInt(token[1]);
                title = token[2];
                author = token[3];
                statistics = Integer.parseInt(token[4]);
                borrowDate = (Date)formatter.parse(token[5]);
                returnDate = (Date)formatter.parse(token[6]);
                libraryCardNumber = Integer.parseInt(token[7]);
public String getIsbn()
     return isbn;
public void setIsbn(String isbn)
    this.isbn = isbn;
public int getCopyNumber()
    return copyNumber;
public void setCopyNumber(int copyNumber)
    this.copyNumber = copyNumber;
public String getTitle()
    return title;
private void setTitle(String title)
    this.title = title;
public String getAuthor()
    return author;
private void setAuthor(String author)
    this.author = author;
public int getStatistics()
    return statistics;
public void setStatistics(int statistics)
    this.statistics = statistics;
public Date setBorrowDate()
    return borrowDate;
public void getBorrowDate(Date borrowDate)
    this.borrowDate = borrowDate;
public Date getReturnDate()
    return returnDate;
public void setReturnDate (Date returnDate)
    this.returnDate = returnDate;
public int getLibraryCardNumber()
    return libraryCardNumber;
public void setLibraryNumber(int libraryCardNumber)
    this.libraryCardNumber = libraryCardNumber;
import java.io.*;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
public class WriteFromBookFile {
    private static Pattern pattern;
    public static void main(String[] args) throws FileNotFoundException, ParseException, IOException {
        JFileChooser fileChooser = new JFileChooser();
        if(fileChooser.showOpenDialog(null)
                == JFileChooser.APPROVE_OPTION){
        ArrayList<Book> newBooks = new ArrayList<Book>();
        ArrayList<Book> errorBooks = new ArrayList<Book>();
        java.io.File file = fileChooser.getSelectedFile();
    //  try{  BufferedReader reader = new BufferedReader(new FileReader("books.txt"));
       Scanner input = new Scanner(file);
       String line = input.nextLine();
        while (line != null) {
            Book newBook = new Book(line);
            String[] newToken = line.split("#");
            pattern = Pattern.compile("ISBN\\x20(?=.{13}$)\\d{1,5}([- ])\\d{1,7}\\1\\d{1,6}\\1(\\d|X)$");
            Matcher matchIsbn = pattern.matcher(newToken[0]);
            pattern = Pattern.compile("[\\d]+");
            Matcher matchCopyNumber = pattern.matcher(newToken[1]);
            pattern = Pattern.compile("[\\D&&\\w]+");
            Matcher matchTitle = pattern.matcher(newToken[2]);
            pattern = Pattern.compile("[\\D&&\\w]+");
            Matcher matchAuthor = pattern.matcher(newToken[3]);
            pattern = Pattern.compile("[\\d]+");
            Matcher matchStatistics = pattern.matcher(newToken[4]);
            pattern = Pattern.compile("YY/MM/DD");
            Matcher matchBorrowDate = pattern.matcher(newToken[5]);
            pattern = Pattern.compile("YY/MM/DD");
            Matcher matchReturnDate = pattern.matcher(newToken[6]);
            pattern = Pattern.compile("[\\d]+");
            Matcher matchLibraryCardNumber = pattern.matcher(newToken[7]);
            /*  if(matchIsbn.matches(newBook.getIsbn()) && matchCopyNumber.matches(newBook.getCopyNumber())
            && matchTitle.matches(newBook.getTitle()) && matchAuthor.matches(newBook.getAuthor())
            && matchStatistics.matches(newBook.getStatistics()) && matchBorrowDate.matches(newBook.getBorrowDate())
            && matchReturnDate.matches(newBook.getReturnDate()) && matchLibraryCardNumber.matches(newBook.getLibraryCardNumber()));*/
            if (matchIsbn.matches() && matchCopyNumber.matches() && matchTitle.matches() && matchAuthor.matches()
                    && matchStatistics.matches() && matchBorrowDate.matches() && matchReturnDate.matches() && matchLibraryCardNumber.matches())
                newBooks.add(newBook);
                   else
                errorBooks.add(newBook);
line = input.nextLine();
input.close();
       java.io.File newBookFile = new java.io.File("newBook.txt");
    if(newBookFile.exists()){
        System.out.println("File exists.");
        System.exit(0);
    java.io.PrintWriter output = new java.io.PrintWriter(newBookFile);
    for(int i = 0; i < newBooks.size(); i++)
        output.print(newBooks.get(i));
        output.close();
}

My program seems to work, the thing I cant work out is that because I try to match 8 fields using split
String[] newToken = line.split("#");
            pattern = Pattern.compile("ISBN\\x20(?=.{13}$)\\d{1,5}([- ])\\d{1,7}\\1\\d{1,6}\\1(\\d|X)$");
            Matcher matchIsbn = pattern.matcher(newToken[0]);
            pattern = Pattern.compile("[\\d]+");
            Matcher matchCopyNumber = pattern.matcher(newToken[1]);
            pattern = Pattern.compile("[\\D&&\\w]+");
            Matcher matchTitle = pattern.matcher(newToken[2]);
            pattern = Pattern.compile("[\\D&&\\w]+");
            Matcher matchAuthor = pattern.matcher(newToken[3]);
            pattern = Pattern.compile("[\\d]+");
            Matcher matchStatistics = pattern.matcher(newToken[4]);
            pattern = Pattern.compile("YYMMDD");
            Matcher matchBorrowDate = pattern.matcher(newToken[5]);
            pattern = Pattern.compile("YYMMDD");
            Matcher matchReturnDate = pattern.matcher(newToken[6]);
            pattern = Pattern.compile("[\\d]+");
            Matcher matchLibraryCardNumber = pattern.matcher(newToken[7]);because some lines dont have 8 tokens, there is an array out of bounds error.
How can it just move to the next token if there isnt a token to match or to the next line if there aren't enough tokens?

Similar Messages

  • Help with small program

    hey every time i compile i get errors with the JOptionPane.showMessageDialog(s) in the switch statement any help would be great
    ""incompatible types
    found : void""
    here is the code
    import java.util.Random;
    import javax.swing.*;
    public class Fish{
    String size;
    String type;
    String location;
    public String Fish(String type, String location, String size){
    String input = JOptionPane.showInputDialog("Press:" + "\n" + "1 for Bass" + "\n" + "2 for White perch" + "\n" + "3 for Yellow cat fish"
    + "\n" + "4 for Spec Trout" + "\n" + "5 for Red fish" + "\n" + "6 for Grouper");
    int choice = Integer.parseInt(input);
    switch (choice){
    case 1: String input1 = JOptionPane.showInputDialog("what is the size(length) of your bass?");
    String input2 = JOptionPane.showInputDialog("where did you catch your bass?");
    double siz = Double.parseDouble(input1);
    double loc = Double.parseDouble(input2);
    String output = JOptionPane.showMessageDialog(null, "Sorry but you bass is not big enough to keep so through it back or i will tell on you");
    String output1 = JOptionPane.showMessageDialog(null, "You caught a fresh water bass that is " + siz + "inches long and you caught it in " + loc);
    if (siz <= 13)
    return output;
    else
    return output1;
    break;
    case 2: String input3 = JOptionPane.showInputDialog("what is the size(length) of your White perch?");
    String input4 = JOptionPane.showInputDialog("where did you catch your White perch?");
    double siz1 = Double.parseDouble(input3);
    double loc1 = Double.parseDouble(input4);
    String output2 = JOptionPane.showMessageDialog(null, "Sorry but you White perch is not big enough to keep so through it back or i will tell on you");
    String output3 = JOptionPane.showMessageDialog(null, "You caught a fresh water White perch that is " + siz1 + "inches long and you caught it in " + loc1);
    if (siz1 <= 0)
    return output2;
    else
    return output3;
    break;
    case 3:String input5 = JOptionPane.showInputDialog("what is the size(length) of your Yellow cat fish?");
    String input6 = JOptionPane.showInputDialog("where did you catch your Yellow cat fish?");
    double siz2 = Double.parseDouble(input5);
    double loc2 = Double.parseDouble(input6);
    String output4 = JOptionPane.showMessageDialog(null, "Sorry but you Yellow cat fish is not big enough to keep so through it back or i will tell on you");
    String output5 = JOptionPane.showMessageDialog(null, "You caught a fresh water Yellow cat fish that is " + siz2 + "inches long and you caught it in " + loc2);
    if (siz1 <= 10)
    return output4;
    else
    return output5;
    break;
    case 4:String input7 = JOptionPane.showInputDialog("what is the size(length) of your Spec Trout?");
    String input8 = JOptionPane.showInputDialog("where did you catch your Spec Trout?");
    double siz3 = Double.parseDouble(input7);
    double loc3 = Double.parseDouble(input8);
    String output6 = JOptionPane.showMessageDialog(null, "Sorry but you Spec Trout is not big enough to keep so through it back or i will tell on you");
    String output7 = JOptionPane.showMessageDialog(null, "You caught a salt water Spec Trout that is " + siz3 + "inches long and you caught it in " + loc3);
    if (siz1 <= 0)
    return output6;
    else
    return output7;
    break;
    case 5:String input9 = JOptionPane.showInputDialog("what is the size(length) of your Red fish?");
    String input10 = JOptionPane.showInputDialog("where did you catch your Red fish?");
    double siz4 = Double.parseDouble(input9);
    double loc4 = Double.parseDouble(input10);
    String output8 = JOptionPane.showMessageDialog(null, "Sorry but you Red fish is not big enough to keep so through it back or i will tell on you");
    String output9 = JOptionPane.showMessageDialog(null, "You caught a salt water Red fish that is " + siz4 + "inches long and you caught it in " + loc4);
    if (siz1 <= 0)
    return output8;
    else
    return output9;
    break;
    case 6:String input11 = JOptionPane.showInputDialog("what is the size(length) of your Grouper?");
    String input12 = JOptionPane.showInputDialog("where did you catch your Grouper?");
    double siz5 = Double.parseDouble(input11);
    double loc5 = Double.parseDouble(input12);
    String output10 = JOptionPane.showMessageDialog(null, "Sorry but you Grouper is not big enough to keep so through it back or i will tell on you");
    String output11 = JOptionPane.showMessageDialog(null, "You caught a salt water Grouper that is " + siz4 + "inches long and you caught it in " + loc4);
    if (siz1 <= 0)
    return output10;
    else
    return output11;
    break;
    public boolean caught(){
    if (Math.random()*(2)+(1)==1){
    return true;
    else
    return false;
    public int hooked(String lure, String time){
    String input = JOptionPane.showInputDialog("What lure did you use?");
    String input1 = JOptionPane.showInputDialog("What time did you catch your fish at? include P.M or A.M");
    double lur = Double.parseDouble(input);
    double tim = Double.parseDouble(input1);
    JOptionPane.showMessageDialog(null, "You hooked you fish with a " + lur + "at " + tim);
    Message was edited by:
    skullker232

    i get errors on all the String outputs in the switch it says
    "incompatible types
    found : void"
    <code>
    import java.util.Random;
    import javax.swing.*;
    public class Fish{
    String size;
    String type;
    String location;
    public String Fish(String type, String location, String size){
    String input = JOptionPane.showInputDialog("Press:" + "\n" + "1 for Bass" + "\n" + "2 for White perch" + "\n" + "3 for Yellow cat fish"
    + "\n" + "4 for Spec Trout" + "\n" + "5 for Red fish" + "\n" + "6 for Grouper");
    int choice = Integer.parseInt(input);
    switch (choice){
    case 1: String input1 = JOptionPane.showInputDialog("what is the size(length) of your bass?");
    String input2 = JOptionPane.showInputDialog("where did you catch your bass?");
    double siz = Double.parseDouble(input1);
    double loc = Double.parseDouble(input2);
    String output = JOptionPane.showMessageDialog(null, "Sorry but you bass is not big enough to keep so through it back or i will tell on you");
    String output1 = JOptionPane.showMessageDialog(null, "You caught a fresh water bass that is " + siz + "inches long and you caught it in " + loc);
    if (siz <= 13)
    return output;
    else
    return output1;
    break;
    case 2: String input3 = JOptionPane.showInputDialog("what is the size(length) of your White perch?");
    String input4 = JOptionPane.showInputDialog("where did you catch your White perch?");
    double siz1 = Double.parseDouble(input3);
    double loc1 = Double.parseDouble(input4);
    String output2 = JOptionPane.showMessageDialog(null, "Sorry but you White perch is not big enough to keep so through it back or i will tell on you");
    String output3 = JOptionPane.showMessageDialog(null, "You caught a fresh water White perch that is " + siz1 + "inches long and you caught it in " + loc1);
    if (siz1 <= 0)
    return output2;
    else
    return output3;
    break;
    case 3:String input5 = JOptionPane.showInputDialog("what is the size(length) of your Yellow cat fish?");
    String input6 = JOptionPane.showInputDialog("where did you catch your Yellow cat fish?");
    double siz2 = Double.parseDouble(input5);
    double loc2 = Double.parseDouble(input6);
    String output4 = JOptionPane.showMessageDialog(null, "Sorry but you Yellow cat fish is not big enough to keep so through it back or i will tell on you");
    String output5 = JOptionPane.showMessageDialog(null, "You caught a fresh water Yellow cat fish that is " + siz2 + "inches long and you caught it in " + loc2);
    if (siz1 <= 10)
    return output4;
    else
    return output5;
    break;
    case 4:String input7 = JOptionPane.showInputDialog("what is the size(length) of your Spec Trout?");
    String input8 = JOptionPane.showInputDialog("where did you catch your Spec Trout?");
    double siz3 = Double.parseDouble(input7);
    double loc3 = Double.parseDouble(input8);
    String output6 = JOptionPane.showMessageDialog(null, "Sorry but you Spec Trout is not big enough to keep so through it back or i will tell on you");
    String output7 = JOptionPane.showMessageDialog(null, "You caught a salt water Spec Trout that is " + siz3 + "inches long and you caught it in " + loc3);
    if (siz1 <= 0)
    return output6;
    else
    return output7;
    break;
    case 5:String input9 = JOptionPane.showInputDialog("what is the size(length) of your Red fish?");
    String input10 = JOptionPane.showInputDialog("where did you catch your Red fish?");
    double siz4 = Double.parseDouble(input9);
    double loc4 = Double.parseDouble(input10);
    String output8 = JOptionPane.showMessageDialog(null, "Sorry but you Red fish is not big enough to keep so through it back or i will tell on you");
    String output9 = JOptionPane.showMessageDialog(null, "You caught a salt water Red fish that is " + siz4 + "inches long and you caught it in " + loc4);
    if (siz1 <= 0)
    return output8;
    else
    return output9;
    break;
    case 6:String input11 = JOptionPane.showInputDialog("what is the size(length) of your Grouper?");
    String input12 = JOptionPane.showInputDialog("where did you catch your Grouper?");
    double siz5 = Double.parseDouble(input11);
    double loc5 = Double.parseDouble(input12);
    String output10 = JOptionPane.showMessageDialog(null, "Sorry but you Grouper is not big enough to keep so through it back or i will tell on you");
    String output11 = JOptionPane.showMessageDialog(null, "You caught a salt water Grouper that is " + siz4 + "inches long and you caught it in " + loc4);
    if (siz1 <= 0)
    return output10;
    else
    return output11;
    break;
    public boolean caught(){
    if (Math.random()*(2)+(1)==1){
    return true;
    else
    return false;
    public int hooked(String lure, String time){
    String input = JOptionPane.showInputDialog("What lure did you use?");
    String input1 = JOptionPane.showInputDialog("What time did you catch your fish at? include P.M or A.M");
    double lur = Double.parseDouble(input);
    double tim = Double.parseDouble(input1);
    JOptionPane.showMessageDialog(null, "You hooked you fish with a " + lur + "at " + tim);
    </code>

  • Error parsing enveloped data (Error Code: 101): Cannot decrypt request

    When my player requests http://<server>:8080/flashaccessserver/<tenant>/flashaccess/license/v1 the following happens:
    - HTTP 500 is returned
    - in the log file, an ERROR is appended, copied below:
    [#:10] 2011-01-14 12:19:37,381 DEBUG [[Partition(flashaccessserver)].com.adobe.flashaccess.server.license.engine.LicenseEngine ] Started processing request...
    [#:10] 2011-01-14 12:19:37,385 ERROR [[Partition(flashaccessserver)].com.adobe.flashaccess.server.license.engine.LicenseEngine ]
    Error occurred processing license acquisition request
    com.adobe.flashaccess.sdk.protocol.HandlerParsingException: com.adobe.flashaccess.core.pkcs7.PKCS7Exception: Error parsing enveloped data (Error Code: 101):
    Cannot decrypt request
            at com.adobe.flashaccess.sdk.protocol.AbstractHandler.parseRequest(AbstractHandler.java:73)
            at com.adobe.flashaccess.server.license.engine.LicenseEngine.parseRequest(LicenseEngine.java :193)
            at com.adobe.flashaccess.server.license.engine.LicenseEngine.parseRequest(LicenseEngine.java :63)
            at com.adobe.flashaccess.server.generic.engine.AbstractEngine.processLicenseRequest(Abstract Engine.java:70)
            at com.adobe.flashaccess.server.license.servlet.LicenseEngineDelegatorServlet.doPost(License EngineDelegatorServlet.java:53)
            etc...
    The Validator says that the config is ok, but I can't get this /license/v1 url to work.
    Can you help?
    Thank you!

    I have managed to get past that 101 error, but now there is another error... and I have no idea where to continue... can you help?
    Thank you in advance!
    This is my log file:
    [#:3] 2011-01-14 16:38:53,623 INFO  [[Partition(flashaccessserver)].com.adobe.flashaccess.server.license.context.SimpleContex tFactory] Creating class loader for partition 'flashaccessserver' with libraries '[file:/opt/adobe/flashaccess/tomcat/licenseserver/flashaccessserver/libs/, file:/opt/adobe/flashaccess/tomcat/licenseserver/flashaccessserver/libs/flashaccess-licen se-server-ext-sample.jar]'
    [#:3] 2011-01-14 16:38:53,626 DEBUG [[Partition(flashaccessserver)].com.adobe.flashaccess.server.license.engine.LicenseEngine ] Started processing request...
    [#:3] 2011-01-14 16:40:26,933 ERROR [[Partition(flashaccessserver)].com.adobe.flashaccess.server.license.engine.LicenseEngine ] Error occurred processing license acquisition request
    java.lang.UnsatisfiedLinkError: com.rsa.Native.JN_SHA1.NativeDigestInit([B)[B
            at com.rsa.Native.JN_SHA1.NativeDigestInit(Native Method)
            at com.rsa.cryptoj.n.fN.a(Unknown Source)
            at com.rsa.cryptoj.n.qE.a(Unknown Source)
            at com.rsa.cryptoj.n.qE.f(Unknown Source)
            at com.rsa.cryptoj.n.bA.a(Unknown Source)
            at com.rsa.jsafe.JSAFE_Signature.verifyInit(Unknown Source)
            at com.rsa.jsafe.JSAFE_Signature.verifyInit(Unknown Source)
            at com.adobe.flashaccess.core.crypto.jsafe.RSASigVerifier_JSAFE.<init>(RSASigVerifier_JSAFE. java:46)
            at com.adobe.flashaccess.core.crypto.RSASigVerifier.getInstance(RSASigVerifier.java:30)
            at com.adobe.flashaccess.core.pkcs7.SignedDataVerifier.verify(SignedDataVerifier.java:82)
            at com.adobe.flashaccess.core.pkcs7.SignedDataVerifier.verify(SignedDataVerifier.java:164)
            at com.adobe.flashaccess.core.pkcs7.SignedData.verifySignature(SignedData.java:335)
            at com.adobe.flashaccess.core.media.drm.keys.v2.V2ContentMetadataImpl.parseMetadata(V2Conten tMetadataImpl.java:189)
            at com.adobe.flashaccess.core.media.drm.keys.v2.V2ContentMetadataImpl.<init>(V2ContentMetada taImpl.java:155)
            at com.adobe.flashaccess.sdk.protocol.license.LicenseRequestMessage.parseLicenseMessage(Lice nseRequestMessage.java:565)
            at com.adobe.flashaccess.sdk.protocol.license.LicenseRequestMessage.<init>(LicenseRequestMes sage.java:137)
            at com.adobe.flashaccess.sdk.protocol.license.LicenseHandler.parseRequestMessages(LicenseHan dler.java:128)
            at com.adobe.flashaccess.sdk.protocol.AbstractBatchHandler.parseRequestMessage(AbstractBatch Handler.java:124)
            at com.adobe.flashaccess.sdk.protocol.AbstractHandler.parseRequest(AbstractHandler.java:75)
            at com.adobe.flashaccess.server.license.engine.LicenseEngine.parseRequest(LicenseEngine.java :193)
            at com.adobe.flashaccess.server.license.engine.LicenseEngine.parseRequest(LicenseEngine.java :63)
            at com.adobe.flashaccess.server.generic.engine.AbstractEngine.processLicenseRequest(Abstract Engine.java:70)
            at com.adobe.flashaccess.server.license.servlet.LicenseEngineDelegatorServlet.doPost(License EngineDelegatorServlet.java:53)
            etc.

  • Help with Paint program.

    Hello. I am somewhat new to Java and I was recently assigned to do a simple paint program. I have had no trouble up until my class started getting into the graphical functions of Java. I need help with my program. I am supposed to start off with a program that draws lines and changes a minimum of 5 colors. I have the line function done but my color change boxes do not work and I am able to draw inside the box that is supposed to be reserved for color buttons. Here is my code so far:
    // Lab13110.java
    // The Lab13 program assignment is open ended.
    // There is no provided student version for starting, nor are there
    // any files with solutions for the different point versions.
    // Check the Lab assignment document for additional details.
    import java.applet.Applet;
    import java.awt.*;
    public class Lab13110 extends Applet
         int[] startX,startY,endX,endY;
         int currentStartX,currentStartY,currentEndX,currentEndY;
         int lineCount;
         Rectangle red, green, blue, yellow, black;
         int numColor;
         Image virtualMem;
         Graphics gBuffer;
         int rectheight,rectwidth;
         public void init()
              startX = new int[100];
              startY = new int[100];
              endX = new int[100];
              endY = new int[100];
              lineCount = 0;
              red = new Rectangle(50,100,25,25);
              green = new Rectangle(50,125,25,25);
              blue = new Rectangle(50,150,25,25);
              yellow = new Rectangle(25,112,25,25);
              black = new Rectangle(25,137,25,25);
              numColor = 0;
              virtualMem = createImage(100,600);
              gBuffer = virtualMem.getGraphics();
              gBuffer.drawRect(0,0,100,600);
         public void paint(Graphics g)
              for (int k = 0; k < lineCount; k++)
                   g.drawLine(startX[k],startY[k],endX[k],endY[k]);
              g.drawLine(currentStartX,currentStartY,currentEndX,currentEndY);
              g.setColor(Color.red);
              g.fillRect(50,100,25,25);
              g.setColor(Color.green);
              g.fillRect(50,125,25,25);
              g.setColor(Color.blue);
              g.fillRect(50,150,25,25);
              g.setColor(Color.yellow);
              g.fillRect(25,112,25,25);
              g.setColor(Color.black);
              g.fillRect(25,137,25,25);
              switch (numColor)
                   case 1:
                        g.setColor(Color.red);
                        break;
                   case 2:
                        g.setColor(Color.green);
                        break;
                   case 3:
                        g.setColor(Color.blue);
                        break;
                   case 4:
                        g.setColor(Color.yellow);
                        break;
                   case 5:
                        g.setColor(Color.black);
                        break;
                   case 6:
                        g.setColor(Color.black);
                        break;
              g.setColor(Color.black);
              g.drawRect(0,0,100,575);
         public boolean mouseDown(Event e, int x, int y)
              currentStartX = x;
              currentStartY = y;
              if(red.inside(x,y))
                   numColor = 1;
              else if(green.inside(x,y))
                   numColor = 2;
              else if(blue.inside(x,y))
                   numColor = 3;
              else if(yellow.inside(x,y))
                   numColor = 4;
              else if(black.inside(x,y))
                   numColor = 5;
              else
                   numColor = 6;
              repaint();
              return true;
         public boolean mouseDrag(Event e, int x, int y)
              int Rectheight = 500;
              int Rectwidth = 900;
              currentEndX = x;
              currentEndY = y;
              Rectangle window = new Rectangle(0,0,900,500);
              //if (window.inside(Rectheight,Rectwidth))
                   repaint();
              return true;
         public boolean mouseUp(Event e, int x, int y)
              int Rectheight = 500;
              int Rectwidth = 900;
              startX[lineCount] = currentStartX;
              startY[lineCount] = currentStartY;
              endX[lineCount] = x;
              endY[lineCount] = y;
              lineCount++;
              Rectangle window = new Rectangle(0,0,900,500);
              if (window.inside(Rectheight,Rectwidth))
                   repaint();
              return true;
         public void Rectangle(Graphics g, int x, int y)
              g.setColor(Color.white);
              Rectangle screen = new Rectangle(100,0,900,600);
    }If anyone could point me in the right direction of how to go about getting my buttons to work and fixing the button box, I would be greatly appreciative. I just need to get a little bit of advice and I think I should be good after I get this going.
    Thanks.

    This isn't in any way a complete solution, but I'm posting code for a mouse drag outliner. This may be preferable to how you are doing rectangles right now
    you are welcome to use and modify this code but please do not change the package and make sure that you tell your teacher where you got it from
    MouseDragOutliner.java
    package tjacobs.ui;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Stroke;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    * See the public static method addAMouseDragOutliner
    public class MouseDragOutliner extends MouseAdapter implements MouseMotionListener {
         public static final BasicStroke DASH_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL, 10.0f, new float[] {8, 8}, 0);
         private boolean mUseMove = false;
         private Point mStart;
         private Point mEnd;
         private Component mComponent;
         private MyRunnable mRunner= new MyRunnable();
         private ArrayList mListeners = new ArrayList(1);
         public MouseDragOutliner() {
              super();
         public MouseDragOutliner(boolean useMove) {
              this();
              mUseMove = useMove;
         public void mouseDragged(MouseEvent me) {
              doMouseDragged(me);
         public void mousePressed(MouseEvent me) {
              mStart = me.getPoint();
         public void mouseEntered(MouseEvent me) {
              mStart = me.getPoint();
         public void mouseReleased(MouseEvent me) {
              Iterator i = mListeners.iterator();
              Point end = me.getPoint();
              while (i.hasNext()) {
                   ((OutlineListener)i.next()).mouseDragEnded(mStart, end);
              //mStart = null;
         public void mouseMoved(MouseEvent me) {
              if (mUseMove) {
                   doMouseDragged(me);
         public     void addOutlineListener(OutlineListener ol) {
              mListeners.add(ol);
         public void removeOutlineListener(OutlineListener ol) {
              mListeners.remove(ol);
         private class MyRunnable implements Runnable {
              public void run() {
                   Graphics g = mComponent.getGraphics();
                   if (g == null) {
                        return;
                   Graphics2D g2 = (Graphics2D) g;
                   Stroke s = g2.getStroke();
                   g2.setStroke(DASH_STROKE);
                   int x = Math.min(mStart.x, mEnd.x);
                   int y = Math.min(mStart.y, mEnd.y);
                   int w = Math.abs(mEnd.x - mStart.x);
                   int h = Math.abs(mEnd.y - mStart.y);
                   g2.setXORMode(Color.WHITE);
                   g2.drawRect(x, y, w, h);
                   g2.setStroke(s);
         public void doMouseDragged(MouseEvent me) {
              mEnd = me.getPoint();
              if (mStart != null) {
                   mComponent = me.getComponent();
                   mComponent.repaint();
                   SwingUtilities.invokeLater(mRunner);
         public static MouseDragOutliner addAMouseDragOutliner(Component c) {
              MouseDragOutliner mdo = new MouseDragOutliner();
              c.addMouseListener(mdo);
              c.addMouseMotionListener(mdo);
              return mdo;
         public static interface OutlineListener {
              public void mouseDragEnded(Point start, Point finish);
         public static void main(String[] args) {
              JFrame f = new JFrame("MouseDragOutliner Test");
              Container c = f.getContentPane();
              JPanel p = new JPanel();
              //p.setBackground(Color.BLACK);
              c.add(p);
              addAMouseDragOutliner(p);
              f.setBounds(200, 200, 400, 400);
              f.addWindowListener(new WindowClosingActions.Exit());
              f.setVisible(true);
    }

  • Errors with small program

    Ok, I'm trying to get a small program to compile on my windows box. I'm a student and in the lab (on a linux box) the program compiled fine. I keep getting this error:
    Easypieces.java:52: cannot resolve symbol
    symbol : variable volume
    location: class EasyPieces
    System.out.println("Volume:" + volume);
    ^
    2 errors
    Here's the code:
    * Student should complete the five methods, document the class
    * and the methods, and test this well. You may remove the instructor
    * comments.
    public class EasyPieces {
    * Student should complete and document this method
    public void waterBalloons(int radius) {
         double cubedRadius = Math.pow(radius, 3);
         double volume;
         double volume = 4/3 * Math.PI * cubedRadius ;
    * Student should complete and document this method
    public void upsLoad(double computer, double monitor, double other) {
    * Student should complete and document this method
    public void carpool(int people) {
    * Student should complete and document this method
    public void checksum(int number, int base) {
    * Student should complete and document this method
    public void combinationLock() {
    * Instructor provided test cases. Student should add additional
    * test cases as necessary to make sure the program functions as
    * intended.
    public static void main(String[] args) {
    //Create an object of type EasyPieces to use for the testing
    EasyPieces testPiece = new EasyPieces();
    //Instructor provided test for waterBalloons
    testPiece.waterBalloons(6);
    System.out.println("Volume:" + volume);
    //Instructor provided test for upsLoad
    //testPiece.upsLoad(1.2,0.8,1.4);
    //System.out.println("----------------------------------------------------------------------");
    //Instructor provided test for carpool
    //testPiece.carpool(15);
    //System.out.println("----------------------------------------------------------------------");
    //Instructor provided test for checksum
    //testPiece.checksum(156,7);
    //System.out.println("----------------------------------------------------------------------");
    //Instructor provided test for combinationLock
    //testPiece.combinationLock();
    //System.out.println("----------------------------------------------------------------------");
    For some reason it doesn't want to print the variable out...
    Any help?
    Thanks, Greg

    << That code didn't compile on your linux box, guaranteed. :o) >>
    This program didn't but one similiar to it did, and I get the same error message when I try to compile it on my windows box:
    public class zeller {
         public static void main(String args[]) {
              int month = 2;
              int day = 29;
              int year = 2000;
              if (month == 2) {
                   year = year -1;
                   day = day +3;
              if (month == 1) {
                   year = year -1;
                   day = day;
              if (month == 3) {
                   year = year;
                   day = day + 2;
              if (month == 4) {
                   day = day + 5;
              if (month == 5) {
                   day = day;
              if (month == 6) {
                   day = day + 3;
              if (month == 7) {
                   day = day + 5;
              if (month == 8) {
                   day = day +1;
              if (month == 9) {
                   day = day +4;
              if (month == 10) {
                   day = day +6;
              if (month == 11) {
                   day = day +2;
              if (month == 12) {
                   day = day +4;
              int sum = year + year/4 - year/100 + year/400 + day;
              int dayOfWeek = sum % 7;
              System.out.println(dayofweek);
    I get this error in windows (the same error I get with the other program):
    D:\JAVA\jdk142\bin>javac zeller.java
    zeller.java:67: cannot resolve symbol
    symbol : variable dayofweek
    location: class zeller
    System.out.println(dayofweek);
    ^
    1 error
    Greg

  • Help with Payroll program

    Hello I need help with the following code for a Payroll program.
    //CheckPoint: Payroll Program Part 3
    //Java Programming IT215
    //Arianne Gallegos
    //05/02/2007
    //Payroll3.java
    //Payroll program that calculates the weekly pay for an employee.
    import java.util.Scanner; // program uses class Scanner
    public class Payroll3
         private string name;
         private double rate;
         private double hours;
         // Constructor to store Employee Data
         public EmployeeData( String nameOfEmployee, double hourlyRate, double hoursWorked )
              name = nameOfEmployee;
              rate = hourlyRate;
              hours = hoursWorked;
         } // end constructor
    } //end class EmployeeData
       // main method begins execution of java application
       public static void main( String args[] )
          System.out.println( "Welcome to the Payroll Program! " );
          boolean quit = false; // This flag will control whether we exit the loop below
          // Loop until user types "quit" as the employee name:
          while (!quit)
           // create scanner to obtain input from command window
            Scanner input = new Scanner ( System.in );
            System.out.println();  // outputs a blank line
            System.out.print( "Please enter the employee name or quit to terminate program: " );
            // prompt for and input employee name
            String nameOfEmployee = input.nextLine(); // read what user has inputted
            if ( nameOfEmployee.equals("quit")) // Check whether user indicated to quit program
              System.out.println( "Program has ended" );
              quit = true;
    else
              // User did not indicate to stop, so continue reading info for this iteration:
              float hourlyRate; // first number to multiply
              float hoursWorked; // second number to multiply
              float product; // product of hourlyRate and hoursWorked
              System.out.print( "Enter hourly rate: " ); // prompt
              hourlyRate = input.nextFloat(); // read first number from user
              while (hourlyRate <= 0) // prompt until a positive value is entered
                 System.out.print( "Hourly rate must be a positive value. " +
                   "Please enter the hourly rate again: " ); // prompt for positive value for hourly rate
                  hourlyRate = input.nextFloat(); // read first number again
              System.out.print( "Enter hours worked: " ); // prompt
              hoursWorked = input.nextFloat(); // read second number from user
              while (hoursWorked <= 0) // prompt until a positive value is entered
                 System.out.print( "Hours worked must be a positive value. " +
                   "Please enter the hours worked again: " ); // prompt for positive value for hours worked
                  hoursWorked = input.nextFloat(); // read second number again
              product = (float) hourlyRate * hoursWorked; // multiply the hourly rate by the hours worked
              // Display output for this iteration
              System.out.println(); // outputs a blank line
              System.out.print( nameOfEmployee ); // display employee name
              System.out.printf( "'s weekly pay is: $%,.2f\n", product);  // display product
              System.out.println(); // outputs a blank line
          // Display ending message:
          System.out.println( "Thank you for using the Payroll program!" );
          System.out.println(); // outputs a blank line
       } // end method main
    } // end class Payroll3I am getting the following errors:
    Payroll3.java:18: invalid method declaration; return type required
    public EmployeeData( String nameOfEmployee, double hourlyRate, double hours
    Worked )
    ^
    Payroll3.java:28: class, interface, or enum expected
    public static void main( String args[] )
    ^
    Payroll3.java:33: class, interface, or enum expected
    boolean quit = false; // This flag will control whether we exit the loop b
    elow
    ^
    Payroll3.java:36: class, interface, or enum expected
    while (!quit)
    ^
    Payroll3.java:42: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:43: class, interface, or enum expected
    System.out.print( "Please enter the employee name or quit to terminate p
    rogram: " );
    ^
    Payroll3.java:45: class, interface, or enum expected
    String nameOfEmployee = input.nextLine(); // read what user has inputted
    ^
    Payroll3.java:48: class, interface, or enum expected
    if ( nameOfEmployee.equals("quit")) // Check whether user indicated to q
    uit program
    ^
    Payroll3.java:51: class, interface, or enum expected
    quit = true;
    ^
    Payroll3.java:52: class, interface, or enum expected
    ^
    Payroll3.java:57: class, interface, or enum expected
    float hoursWorked; // second number to multiply
    ^
    Payroll3.java:58: class, interface, or enum expected
    float product; // product of hourlyRate and hoursWorked
    ^
    Payroll3.java:60: class, interface, or enum expected
    System.out.print( "Enter hourly rate: " ); // prompt
    ^
    Payroll3.java:61: class, interface, or enum expected
    hourlyRate = input.nextFloat(); // read first number from user
    ^
    Payroll3.java:64: class, interface, or enum expected
    while (hourlyRate <= 0) // prompt until a positive value is entered
    ^
    Payroll3.java:68: class, interface, or enum expected
    hourlyRate = input.nextFloat(); // read first number again
    ^
    Payroll3.java:69: class, interface, or enum expected
    ^
    Payroll3.java:72: class, interface, or enum expected
    hoursWorked = input.nextFloat(); // read second number from user
    ^
    Payroll3.java:75: class, interface, or enum expected
    while (hoursWorked <= 0) // prompt until a positive value is entered
    ^
    Payroll3.java:79: class, interface, or enum expected
    hoursWorked = input.nextFloat(); // read second number again
    ^
    Payroll3.java:80: class, interface, or enum expected
    ^
    Payroll3.java:86: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:87: class, interface, or enum expected
    System.out.print( nameOfEmployee ); // display employee name
    ^
    Payroll3.java:88: class, interface, or enum expected
    System.out.printf( "'s weekly pay is: $%,.2f\n", product); // display
    product
    ^
    Payroll3.java:89: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:91: class, interface, or enum expected
    ^
    Payroll3.java:96: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:98: class, interface, or enum expected
    } // end method main
    ^
    The problem I am having is getting the constructor to work with the rest of the program can someone please point out to me how to correct this. I have read my textbook as well as tutorials but I just don't seem to get it right. Please help.
    P.S. I have never taken a programming class before so please be kind.

    Ok, I changed the name of the constructor:
    //CheckPoint: Payroll Program Part 3
    //Java Programming IT215
    //Arianne Gallegos
    //04/23/2007
    //Payroll3.java
    //Payroll program that calculates the weekly pay for an employee.
    import java.util.Scanner; // program uses class Scanner
    public class Payroll3
         private string name;
         private float rate;
         private float hours;
         // Constructor to store Employee Data
         public void Payroll3( string nameOfEmployee, float hourlyRate, float hoursWorked )
              name = nameOfEmployee;
              rate = hourlyRate;
              hours = hoursWorked;
         } // end constructor
    } //end class EmployeeData
       // main method begins execution of java application
       public static void main( String args[] )
          System.out.println( "Welcome to the Payroll Program! " );
          boolean quit = false; // This flag will control whether we exit the loop below
          // Loop until user types "quit" as the employee name:
          while (!quit)
           // create scanner to obtain input from command window
            Scanner input = new Scanner ( System.in );
            System.out.println();  // outputs a blank line
            System.out.print( "Please enter the employee name or quit to terminate program: " );
            // prompt for and input employee name
            String nameOfEmployee = input.nextLine(); // read what user has inputted
            if ( nameOfEmployee.equals("quit")) // Check whether user indicated to quit program
              System.out.println( "Program has ended" );
              quit = true;
    else
              // User did not indicate to stop, so continue reading info for this iteration:
              float hourlyRate; // first number to multiply
              float hoursWorked; // second number to multiply
              float product; // product of hourlyRate and hoursWorked
              System.out.print( "Enter hourly rate: " ); // prompt
              hourlyRate = input.nextFloat(); // read first number from user
              while (hourlyRate <= 0) // prompt until a positive value is entered
                 System.out.print( "Hourly rate must be a positive value. " +
                   "Please enter the hourly rate again: " ); // prompt for positive value for hourly rate
                  hourlyRate = input.nextFloat(); // read first number again
              System.out.print( "Enter hours worked: " ); // prompt
              hoursWorked = input.nextFloat(); // read second number from user
              while (hoursWorked <= 0) // prompt until a positive value is entered
                 System.out.print( "Hours worked must be a positive value. " +
                   "Please enter the hours worked again: " ); // prompt for positive value for hours worked
                  hoursWorked = input.nextFloat(); // read second number again
              product = (float) hourlyRate * hoursWorked; // multiply the hourly rate by the hours worked
              // Display output for this iteration
              System.out.println(); // outputs a blank line
              System.out.print( nameOfEmployee ); // display employee name
              System.out.printf( "'s weekly pay is: $%,.2f\n", product);  // display product
              System.out.println(); // outputs a blank line
          // Display ending message:
          System.out.println( "Thank you for using the Payroll program!" );
          System.out.println(); // outputs a blank line
       } // end method main
    } // end class Payroll3I still get the following error codes:
    C:\IT215\Payroll3>javac Payroll3.java
    Payroll3.java:28: class, interface, or enum expected
    public static void main( String args[] )
    ^
    Payroll3.java:33: class, interface, or enum expected
    boolean quit = false; // This flag will control whether we exit the loop b
    elow
    ^
    Payroll3.java:36: class, interface, or enum expected
    while (!quit)
    ^
    Payroll3.java:42: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:43: class, interface, or enum expected
    System.out.print( "Please enter the employee name or quit to terminate p
    rogram: " );
    ^
    Payroll3.java:45: class, interface, or enum expected
    String nameOfEmployee = input.nextLine(); // read what user has inputted
    ^
    Payroll3.java:48: class, interface, or enum expected
    if ( nameOfEmployee.equals("quit")) // Check whether user indicated to q
    uit program
    ^
    Payroll3.java:51: class, interface, or enum expected
    quit = true;
    ^
    Payroll3.java:52: class, interface, or enum expected
    ^
    Payroll3.java:57: class, interface, or enum expected
    float hoursWorked; // second number to multiply
    ^
    Payroll3.java:58: class, interface, or enum expected
    float product; // product of hourlyRate and hoursWorked
    ^
    Payroll3.java:60: class, interface, or enum expected
    System.out.print( "Enter hourly rate: " ); // prompt
    ^
    Payroll3.java:61: class, interface, or enum expected
    hourlyRate = input.nextFloat(); // read first number from user
    ^
    Payroll3.java:64: class, interface, or enum expected
    while (hourlyRate <= 0) // prompt until a positive value is entered
    ^
    Payroll3.java:68: class, interface, or enum expected
    hourlyRate = input.nextFloat(); // read first number again
    ^
    Payroll3.java:69: class, interface, or enum expected
    ^
    Payroll3.java:72: class, interface, or enum expected
    hoursWorked = input.nextFloat(); // read second number from user
    ^
    Payroll3.java:75: class, interface, or enum expected
    while (hoursWorked <= 0) // prompt until a positive value is entered
    ^
    Payroll3.java:79: class, interface, or enum expected
    hoursWorked = input.nextFloat(); // read second number again
    ^
    Payroll3.java:80: class, interface, or enum expected
    ^
    Payroll3.java:86: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:87: class, interface, or enum expected
    System.out.print( nameOfEmployee ); // display employee name
    ^
    Payroll3.java:88: class, interface, or enum expected
    System.out.printf( "'s weekly pay is: $%,.2f\n", product); // display
    product
    ^
    Payroll3.java:89: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:91: class, interface, or enum expected
    ^
    Payroll3.java:96: class, interface, or enum expected
    System.out.println(); // outputs a blank line
    ^
    Payroll3.java:98: class, interface, or enum expected
    } // end method main
    ^
    27 errors
    Any other suggestions?

  • Need some help with a program Please.

    Well, im new here, im new to java, so i need your help, i have to make a connect four program, my brother "Kind of" helped me and did a program for me, but the problem is i cant use some of those commands in the program and i have to replace them with what ive learned, so i will post the program and i will need your help to modify it for me.
    and for these programs, also i want help for:
    They have errors and i cant fix'em
    the commands that i've leaned:
    If statements, for loops, while loops,do while, strings, math classes, swithc statement, else if,logical operators,methods, one and two dimensional arrays.
    Thanx in advance,
    truegunner
    // Fhourstones 3.0 Board Logic
    // Copyright 2000-2004 John Tromp
    import java.io.*;
    class Connect4 {
    static long color[]; // black and white bitboard
    static final int WIDTH = 7;
    static final int HEIGHT = 6;
    // bitmask corresponds to board as follows in 7x6 case:
    // . . . . . . . TOP
    // 5 12 19 26 33 40 47
    // 4 11 18 25 32 39 46
    // 3 10 17 24 31 38 45
    // 2 9 16 23 30 37 44
    // 1 8 15 22 29 36 43
    // 0 7 14 21 28 35 42 BOTTOM
    static final int H1 = HEIGHT+1;
    static final int H2 = HEIGHT+2;
    static final int SIZE = HEIGHT*WIDTH;
    static final int SIZE1 = H1*WIDTH;
    static final long ALL1 = (1L<<SIZE1)-1L; // assumes SIZE1 < 63
    static final int COL1 = (1<<H1)-1;
    static final long BOTTOM = ALL1 / COL1; // has bits i*H1 set
    static final long TOP = BOTTOM << HEIGHT;
    int moves[],nplies;
    byte height[]; // holds bit index of lowest free square
    public Connect4()
    color = new long[2];
    height = new byte[WIDTH];
    moves = new int[SIZE];
    reset();
    void reset()
    nplies = 0;
    color[0] = color[1] = 0L;
    for (int i=0; i<WIDTH; i++)
    height[i] = (byte)(H1*i);
    public long positioncode()
    return 2*color[0] + color[1] + BOTTOM;
    // color[0] + color[1] + BOTTOM forms bitmap of heights
    // so that positioncode() is a complete board encoding
    public String toString()
    StringBuffer buf = new StringBuffer();
    for (int i=0; i<nplies; i++)
    buf.append(1+moves);
    buf.append("\n");
    for (int w=0; w<WIDTH; w++)
    buf.append(" "+(w+1));
    buf.append("\n");
    for (int h=HEIGHT-1; h>=0; h--) {
    for (int w=h; w<SIZE1; w+=H1) {
    long mask = 1L<<w;
    buf.append((color[0]&mask)!= 0 ? " @" :
    (color[1]&mask)!= 0 ? " 0" : " .");
    buf.append("\n");
    if (haswon(color[0]))
    buf.append("@ won\n");
    if (haswon(color[1]))
    buf.append("O won\n");
    return buf.toString();
    // return whether columns col has room
    final boolean isplayable(int col)
    return islegal(color[nplies&1] | (1L << height[col]));
    // return whether newboard lacks overflowing column
    final boolean islegal(long newboard)
    return (newboard & TOP) == 0;
    // return whether newboard is legal and includes a win
    final boolean islegalhaswon(long newboard)
    return islegal(newboard) && haswon(newboard);
    // return whether newboard includes a win
    final boolean haswon(long newboard)
    long y = newboard & (newboard>>HEIGHT);
    if ((y & (y >> 2*HEIGHT)) != 0) // check diagonal \
    return true;
    y = newboard & (newboard>>H1);
    if ((y & (y >> 2*H1)) != 0) // check horizontal -
    return true;
    y = newboard & (newboard>>H2); // check diagonal /
    if ((y & (y >> 2*H2)) != 0)
    return true;
    y = newboard & (newboard>>1); // check vertical |
    return (y & (y >> 2)) != 0;
    void backmove()
    int n;
    n = moves[--nplies];
    color[nplies&1] ^= 1L<<--height[n];
    void makemove(int n)
    color[nplies&1] ^= 1L<<height[n]++;
    moves[nplies++] = n;
    public static void main(String argv[])
    Connect4 c4;
    String line;
    int col=0, i, result;
    long nodes, msecs;
    c4 = new Connect4();
    c4.reset();
    BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
    for (;;) {
    System.out.println("position " + c4.positioncode() + " after moves " + c4 + "enter move(s):");
    try {
    line = dis.readLine();
    } catch (IOException e) {
    System.out.println(e);
    System.exit(0);
    return;
    if (line == null)
    break;
    for (i=0; i < line.length(); i++) {
    col = line.charAt(i) - '1';
    if (col >= 0 && col < WIDTH && c4.isplayable(col))
    c4.makemove(col);
    By the way im using Ready to program for the programming.

    You can't really believe that his brother did this
    for him...I did miss that copyright line at the beginning when
    I first looked it over, but you know, if it had been
    his brother, I'd be kinda impressed. This wasn't a
    25 line program. It actually would have required
    SOME thought. I doubt my brother woulda done that
    for me (notwithstanding the fact that I wouldn't need
    help for that program, and my brother isn't a
    programmer).I originally missed the comments at the top but when I saw the complexity of what was written then I knew that it was too advanced for a beginner and I relooked through the code and saw the comments.

  • Help with a Program I am writing!  Please!

    Hello All,
    This is my first post...I hope to find some answers to my program I am writing! A couple things first - I am 17, and have designed a comp. science class for myself to take while a senior in high school, since there was not one offered. My end of the 2nd term project is to write a program that encompasses the information I have learned about for the past two terms. I know the very basics, if that. Please help!
    My program involves the simple dice throwing program, 'Dice Thrower' by Kevin Boone. The full text/program write out can be found at:
    http://www.kevinboone.com/PF_DiceThrower-java.html
    I am hoping to add a part to this program that basically tells the program if the dice show doubles, pop up a little GUI window that says "You are a Winner! You Got Doubles!"
    I was thinking as I finished chapter 7 in my text book, that either an 'if/else' or 'switch' statement might be the right place to start.
    Could someone please write me a start to the program text that I need to add to 'Dice Thrower', or explain what I need to do to get started! Thank you so much, I really appreciate it.
    Erick DeVore - Eroved Kcire

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JLabel;
    import javax.swing.JFrame;
    import java.awt.FlowLayout;
    import java.awt.Color;
    public class DiceThrower extends Applet
    Die die1;
    Die die2;
    public void paint (Graphics g)
         die1.draw(g);
         die2.draw(g);
         g.drawString ("Click mouse anywhere", 55, 140);
         g.drawString ("to throw dice again", 65, 160);
    public void init()
         die1 = new Die();
         die2 = new Die();
         die1.setTopLeftPosition(20, 20);
         die2.setTopLeftPosition(150, 20);
         throwBothDice();
         // Erick's Program Insert below
         public class WinnerGui extends JFrame;
      public WinnerGui();
        super ("You Are The Winner with GUI");
        Container c = getContentPane();
        c.setBackground(Color.lightGray);
        c.setLayout(new FlowLayout());
        c.add(new JLabel("You're a Winner! You Got Doubles!"));
            //End Erick's Program insert
         DiceThrowerMouseListener diceThrowerMouseListener =
              new DiceThrowerMouseListener();
         diceThrowerMouseListener.setDiceThrower(this);
         addMouseListener(diceThrowerMouseListener);
    public void throwBothDice();
         die1.throwDie();
         die2.throwDie();
         repaint();
    class Die
    int topLeftX;
    int topLeftY;
    int numberShowing = 6;
    final int spotPositionsX[] = {0, 60,  0, 30, 60,  0,  60};
    final int spotPositionsY[] = {0,  0, 30, 30, 30,  60, 60};
    public void setTopLeftPosition(final int _topLeftX, final int _topLeftY)
         topLeftX = _topLeftX;
         topLeftY = _topLeftY;
    public void throwDie()
         numberShowing = (int)(Math.random() * 6 + 1);
    public void draw(Graphics g)
         switch(numberShowing)
              case 1:
                   drawSpot(g, 3);
                   break;
              case 2:
                   drawSpot(g, 0);
                   drawSpot(g, 6);
                   break;
              case 3:
                   drawSpot(g, 0);
                   drawSpot(g, 3);
                   drawSpot(g, 6);
                   break;
              case 4:
                   drawSpot(g, 0);
                   drawSpot(g, 1);
                   drawSpot(g, 5);
                   drawSpot(g, 6);
                   break;
              case 5:
                   drawSpot(g, 0);
                   drawSpot(g, 1);
                   drawSpot(g, 3);
                   drawSpot(g, 5);
                   drawSpot(g, 6);
                   break;
              case 6:
                   drawSpot(g, 0);
                   drawSpot(g, 1);
                   drawSpot(g, 2);
                   drawSpot(g, 4);
                   drawSpot(g, 5);
                   drawSpot(g, 6);
                   break;
    void drawSpot(Graphics g, final int spotNumber)
         g.fillOval(topLeftX + spotPositionsX[spotNumber],
              topLeftY + spotPositionsY[spotNumber], 20, 20);
    class DiceThrowerMouseListener extends MouseAdapter
    DiceThrower diceThrower;
    public void mouseClicked (MouseEvent e)
         diceThrower.throwBothDice();
    public void setDiceThrower(DiceThrower _diceThrower)
         diceThrower = _diceThrower;
    }That was what I have dwindled it down to, using my knowledge, as well as others' expertise...however I am listening to what you say, and get these messages when I try to compile in the CMD:
    line 63 - illegal start of expression (carrot at p in public)
    line 63 - ; expected (carrot at c in class)
    line 63 - { expected (carrot at ; at end of line)
    line 65 - illegal start of expression (carrot at p in public)
    line 83 - <identifier> expected (carrot as: (this) ) -- I don't even know what that means ^
    line 84 - invalid method declaration; return type required (carrot at a in add)
    line 84 - <identifier> expected (carrot like this: [see below])
    addMouseListener(diceThrowerMouseListener);
    ^
    line 84 - ) expected (carrot is one place over from previous spot [see above]
    line 93 - illegal start of expression (carrot at p in public)
    I know this seems like a lot of errors, but believe it or not, I actually had it up in the high teens and was able to fix some of them myself from going by previous examples, as well as looking things up in my text book. If anyone has any suggestions concerning the syntax errors of the code, please please let me know and I will work my hardest to fix them...thank you all so much for helping.
    Erick

  • Help with RFKPYL00_MASS program/payment run transaction

    program  RFKPYL00_MASS is for payment run transaction.
    transactional record is t_payh / i_payh   with structure PAYH.
    In this program i see the statement GET PAYH.
    I need to know from which table  the data is populated to this structure/t_payh especially name and the code how value is assigned.I don't see this here.
    Any help?Thanks.

    Hello,
    The following are data base tables for payment program
    DPAYC            Payment program - administrative records
    DPAYCHKH      Header: Accounting Using Creation of Payme
    DPAYCHKH1    Supplemental Assignments with Creation of
    DPAYCHKNUM  Check Number Lot: Header
    DPAYCHKNUMP:Check Number Lot: Single Numbers
    DPAYCHKP       Header: Accounting Using Creation of Payme
    DPAYCHKSET   Check: Settings for Check Creation for Hou
    DPAYG              Payment program - payment group
    DPAYH              Payment program - data for payment
    DPAYN              Sequential Number Assignment
    DPAYP              Payment program - data on paid item
    DPAYV         Payment program: Variants for payment medium
    DFKKCR      Repository For Checks
    DFKKCR2P       Check Repository: Additional Payees
    DFKKCRCASH  CR: Cashed Checks Not Yet Entered in Register
    DFKKCRCL  :   Table for Checks To Be Clarified
    DFKKCRCL_DOCS:  Table for Checks To Be Clarified
    DFKKCRDELD2   Check Register: Deleted Payment Media
    DFKKCRDOC2    Check Management: Partial Encashments
    Rgds
    Rajendra

  • Help with Dice program.

    Hi People!
    This is the homework my professor assigned for me.
    Assignment 2: Write a program that rolls two dice 1000 times, counting the number of box cars (two sixes) that occur, in object-oriented way. (In other words, do not make all your code in one main() method. Use classes and objects.) Use a overloaded constructors.
    I have to use two classes for it. One of is the Dice(Below), and the other would be the client
    This is what I have for the dice part so far.
    public class DiceServer {
    public static void main (String[] args)
    final int ROLLS = 1000;
    int Boxcars = 0, num1, num2;
    Die die1 = new Die();
    Die die2 = new Die();
    for (int roll = 1; roll <= ROLLS; roll++)
    num1 = die1.roll();
    num2 = die2.roll();
    if (num1 == 6 && num2== 6)
    Boxcars++;
    System.out.println("Number of rolls: " + ROLLS);
    System.out.println("Number of Box Cars: " + Boxcars);
    I'm getting an error about the symbol not being resolved, and it's pointing at "Die die1 = new Die();". Can someone please help me. Thank you.
    Also, can someone plaese get me started on the Client Class. Thanks

    Hi,
    I've gotten pretty far with this program thanks to all your help but I've got another question.
    My program so far has been able to display the result of rolling 2 six sided dice 1000 times. I've used Boxcars.java as my Client and Die.java as my overloaded constructor. Now I want to display the number of Boxcars(Double six)by rolling a six-sided die and a 20 sided die together.
    My question is would I code that in Boxcars.java or Die.java.
    Thank you!!!
    Boxcars.java
    public class BoxCars {
    public static void main (String[] args)
    final int ROLLS = 1000;
    int Boxcars = 0, num1, num2;
    Die die1 = new Die();
    Die die2 = new Die();
    for (int roll = 1; roll <= ROLLS; roll++)
    num1 = die1.roll();
    num2 = die2.roll();
    if (num1 == 6 && num2== 6)
    Boxcars++;
    System.out.println("Number of rolls: " + ROLLS);
    System.out.println("Number of Box Cars: " + Boxcars);
    Die.java
    public class Die {
    private final int MIN_FACES = 4;
    private int numFaces;
    private int faceValue;
    public Die ()
    numFaces = 6;
    faceValue = 1;
    public Die (int faces)
    if (faces < MIN_FACES)
    numFaces = 6;
    else
    numFaces = faces;
    faceValue = 1;
    public int roll ()
    faceValue = (int) (Math.random() * numFaces) + 1;
    return faceValue;
    public int getFaceValue()
    return faceValue;
    ************************************************************

  • Help with simple programming

    Hello everyone.
    First time posting, i hope someone would be able to help me out. There are 5 classes that i have to do, but i only need help with one of them. I've been stuck on this one pretty long and can't continue without it.
    Instructions:
    •     Has boolean data member face, either HEADS or TAILS.
    •     Has a Random data member flipper which is instantiated in the constructor.
    •     Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    •     Method getFace() returns the face showing on the coin.
    •     void method flip() randomly selects HEADS or TAILS.
    package coinflip;
    import java.util.Random;
    * @author Blank
    public class Coin {
        boolean face = false;
        int flip_coin;
        Random flipper = new Random();
        int getFace() {
            return flip_coin;
          Coin() {
            if (flip_coin == 0) {
                face = true;
            } else {
                face = false;
        public void flip() {
            flip_coin = flipper.nextInt(2);
    }i really don't know why the random isn't working. I hope someone would be able to find my errors and instruct me on how to fix them. I would be able to continue the rest of the classes as soon as i got this figured out.
    Oh and can someone teach me how to import this class into a main one? So i can test it out. This is what i have for it.public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
         Coin flipCoin = new Coin();
         for(int i=0;i<6;i++){
         System.out.println(flipCoin.getFace());
    }Many Thanks!
    Edited by: Java_what on Feb 16, 2009 2:26 PM

    Constructors are only executed once. What im confused about is:
    • Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    I thought i would flip() into the constructor. Mind helping me out on the whole class because it seems i am clueless about this whole class.
    Edit:
    public class Coin {
        boolean face = false;
        int flip_coin;
        Random flipper = new Random();
        int getFace() {
            flip();
            return flip_coin;
        Coin() {
           //flip();
        public void flip() {
            flip_coin = flipper.nextInt(2);
    }K i reread what you wrote about the constructor and method. So i placed flip() method in getFace(); because its being called in the main(it gives me random numbers). The problem now is following the directions.
    I just dont understand this description. • Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
    What do you think it means.
    Edited by: Java_what on Feb 16, 2009 4:14 PM

  • Help with Recurrsion program

    I seem to be having a little problem with my program. In my main program, depending on which method comes first, the other methods wont work for example the way my main program is not, with occurance method before removeLetter method, the occurance method works fine, but my removeLetter meth won't remove the letter. But if i switch the two and have removeLetter first then it will remove the letter, but my occurance method will come back say the letter is not in the word even when it is...can someone help me? Thanx in advance...
    class CharacterRecurrance{
         private int i=0;
         private int occur=0;
         void inString(String s, char n){
              if(i<s.length()){
                   if(s.charAt(i)==n)
                        System.out.println("Yes, the letter" + " " + n + " " + "is present");
                   else{
                        i++;
                        inString(s,n);
              else System.out.println("No, the letter" + " " + n + " " + "is not present");
         void occurance(String s, char n){
              if(i < s.length()){
                   if(s.charAt(i)==n){
                        occur++;
                        i++;
                        occurance(s,n);
                   else{
                        i++;
                        occurance(s,n);
              else System.out.println("The letter" + " " + n + " " + "appears" + " " + occur + " " + "times");
         void removeLetter(String s, char n){
              if(i < s.length()){
                   if(s.charAt(i)==n){
                        s = s.replace(s.charAt(i),' ');
                        i++;
                        removeLetter(s,n);
                   else{
                        i++;
                        removeLetter(s,n);
              else System.out.println(s);
    class Program3_10{
         public static void main(String[] a) {
              CharacterRecurrance find = new CharacterRecurrance();
              String word = "mississippi";
              char letter = 's';
              find.inString(word, letter);
              System.out.println();
              find.occurance(word, letter);
              System.out.println();
              find.removeLetter(word, letter);
    }

    Or make it zero in the last step of each function. Like this-void occurance(String s, char n){
              if(i < s.length()){
                   if(s.charAt(i)==n){
                        occur++;
                        i++;
                        occurance(s,n);
                   else{
                        i++;
                        occurance(s,n);
              else{
                   System.out.println("The letter" + " " + n + " " + "appears" + " " + occur + " " + "times");
                   i=0; // reset to zero.
         }

  • Help with pathfinding program

    hi,
    i study java at school and i need help with my project.
    im doing a simple demonstration of a pathfinding program whose algoritm i read off Wikipedia (http://en.wikipedia.org/wiki/Pathfinding)where the co-ordinates of the start and end points
    are entered and the route is calculated as a list of co-ordinates. Here is the section of code i am having trouble with-
    void find_path(int x,int y,int p,int q)
    int t1;int t2;
    int temp_pool[][]=new int[4][3];//stores contagious cells of elements in grid pool
    int grid_pool[][]= new int[100000][3];
    int pass_pool[][]=new int[4][3];//stores the pool of squares which can be added to the list of direction
    int path[][]= new int[10000][3];//stores actual path
    int count=1;int note=10;int kk=0;
    int curx,cury;
    //the above arrays contain 3 columns - to store x and y co-ordinate and a counter variable(the purpose of which will become clear later)
    grid_pool[0][0]=p;
    grid_pool[0][1]=q;
    grid_pool[0][2]=0;
    int counter=grid_pool[0][2];
    for(int i=0;i<=100;i++)
    counter++;
    curx=grid_pool[0];
    cury=grid_pool[i][1];
    temp_pool[0][0]=curx-1;
    temp_pool[0][1]=cury;
    temp_pool[0][2]=counter;
    temp_pool[0][0]=curx;
    temp_pool[0][1]=cury-1;
    temp_pool[0][2]=counter;
    temp_pool[0][0]=curx+1;
    temp_pool[0][1]=cury;
    temp_pool[0][2]=counter;
    temp_pool[0][0]=curx;
    temp_pool[0][1]=cury+1;
    temp_pool[0][2]=counter;
    int pass=0;
    for(int j=0;j<=3;j++)
    int check=0;
    int in=temp_pool[j][0];
    int to=temp_pool[j][1];
    if(activemap[in][to]=='X')
    {check++;}
    if(linear_search(grid_pool,in,to)==false)
    {check++;}
    if(check==2)
    pass_pool[pass][0]=in;
    pass_pool[pass][1]=to;
    pass++;
    }//finding which co-ordinates are not walls and which are not already present
    for(int k=0;k<=pass_pool.length-1;k++)
    grid_pool[count][0]=pass_pool[k][0];
    grid_pool[count][1]=pass_pool[k][1];
    count++;
    if(linear_search(grid_pool,x,y)==true)
    break;
    //in this part we have isolated the squares which run in the approximate direction of the goal
    //in the next part we will isolate the exact co-ordinates in another array called path
    int yalt=linear_searchwindex(grid_pool,p,q);
    t1=grid_pool[yalt][2];
    int g1;int g2;int g3;
    for(int u=yalt;u>=0;u--)
    g3=find_next(grid_pool,p,q);
    g2=g3/10;
    g1=g3%10;
    path[0]=g2;
    path[u][1]=g3;
    path[u][2]=u;
    for(int v=0;v<=yalt;v++)
    System.out.println(path[v][0]+','+path[v][1]);
    ill be grateful if anyone can fix it. im done with the rest though

    death_star12 wrote:
    hi,
    i study java at school and i need help with my project.
    im doing a simple demonstration of a pathfinding program whose algoritm i read off Wikipedia (http://en.wikipedia.org/wiki/Pathfinding)where the co-ordinates of the start and end points
    are entered and the route is calculated as a list of co-ordinates. Here is the section of code i am having trouble with-
    ...The part "i am having trouble with" means absolutely nothing to the people who are answering questions here. It's like going to the doctor with a broken rib and just saying "doc, I don't feel so well". Get my point?
    Also, please take the trouble to properly spell words and use a bit of capitalization. Your question is hard to read as it is, which will most probably cause (some) people not to help you. And lastly, please use code tags when posting code: it makes it so much easier to read (see: [Formatting Messages|http://mediacast.sun.com/users/humanlever/media/forums_text_editor.mp4]).
    Thanks.

  • Need help with basic program.....!

    I've to write a program that generates a random number, which the user has to try and guess, after each guess they're told whether it's too high or too low etc., I've gotten this far, however, the user has only 10 guesses.... In my program I've used a while loop and the user gets an infinite number of guesses, I know I'm supposed to use a for loop, but can't seem to get it to work properly. Also, when the user guesses the number, the program then has to print out how many guesses it took, and I have no idea how to get it to do this AT ALL!!! I'd really appreciate some help with this, thanks v. much!!!!

    I've to write a program that generates a random
    number, which the user has to try and guess, after
    each guess they're told whether it's too high or too
    low etc., I've gotten this far, however, the user has
    only 10 guesses.... In my program I've used a while
    loop and the user gets an infinite number of guesses,
    I know I'm supposed to use a for loop, but can't seem
    to get it to work properly. Also, when the user
    guesses the number, the program then has to print out
    how many guesses it took, and I have no idea how to
    get it to do this AT ALL!!! I'd really appreciate some
    help with this, thanks v. much!!!!Hey not every book covers every aspect of Java (if you haven't got a book and don't want to buy 1 i recommend an online tutorial) If u want the user to have an infinate number of guesses, use an infinate while loop. Put this in a file called app.java:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class app extends Applet implements ActionListener
         JLabel lbl=new JLabel("Guess a number between 0 and 10:");
         JTextField txtfield=new JTextField(20);
         JButton button=new JButton("Guess...");
         JLabel lbl2=new JLabel();
         int randomnumber=Math.round((float)Math.random()*10);
         public void init()
              add(lbl);
              add(txtfield);
              add(button);
              button.addActionListener(this);
         public void actionPerformed (ActionEvent e)
              String s=new String("");
              s+=randomnumber;
              if (e.getSource().equals(button) && txtfield.getText().equals(s))
                   setBackground(Color.white);
                   setForeground(Color.black);
                   lbl2.setText("Got it!");
                   add(lbl2);
                   validate();
              else
                   setBackground(Color.white);
                   setForeground(Color.black);
                   if (Integer.parseInt(txtfield.getText())>randomnumber)
                   lbl2.setText("Too High!");
                   else
                   lbl2.setText("Too Low!");
                   add(lbl2);
                   validate();
    Then create a HTML document in the classes folder:
    <HTML>
    <HEAD>
    <TITLE>APPLET</TITLE>
    </HEAD>
    <BODY>
    <HR>
    <CENTER>
    <APPLET
         CODE=app.class
         WIDTH=400
         HEIGHT=200 >
    </APPLET>
    </CENTER>
    <HR>
    </BODY>
    </HTML>
    It will do what you wish. If you want to have more then 10 numbers to guess, for example 100, do this:
    int randomnumber=Math.round((float)Math.random()*100);
    Does that answer your question?

  • Need help writing small program!

    Hi. I'm learning Java programming, and I need help writing a small program. Please someone help me.
    Directions:
    Create a program called CerealCompare using an if-then-else structure that obtains the price and number of ounces in a box for two boxes of cereal. The program should then output which box costs less per ounce.

    class CerealCompare {
        public static void main(String[] args) {
            // your code goes here
    }Hope that helps.
    P.S. Java does not have an if-then-else statement.

Maybe you are looking for

  • Unable to create a crystal report 2013 on the top of SAP BW 7.00

    Hello Team, We are trying to connect SAP Crystal Reports 2013 to SAP BW 7.00 SP26. This crystal report is being developed on the top of a BEx query accessing through OLAP. 1.  We are getting an error- 'Internal Error: The reports applicatiton server

  • XSLT Transformation Question

    Hi together! Hope anybody can help. I have the follow XML structure : <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">¶ <asx:values>¶ <IMPORT>¶ <Y0DPL_LATAM_INV_FILE_UPLOAD>¶ <DATA>222358   1NU    480350    29102007VENDA DE MERCADORIA 

  • Dialing numbers on the e71

    So here's my setup. When I make international calls from the US, first there's a toll free number I have to call. Let's say 1800-123-4567 Then I have to dial my password, say 1234 after a brief pause.  Finally, I have to dial my destination phone num

  • HTML to PDF converstion

    Hi, I dont know whether this is the right place to ask my question , So Please direct me . In our application we need to convert HTML string to as a PDF document. Our client suggested try in Adobe Acrobat SDK , so i have started exploring in SDK but

  • URGENT!!! Diff SessionId when request come back after completing one task

    Hello, I have a web application that uploads collages done from our site1 to some other site2. To upload to site2 one has authenicate youself....in this process of authenication , sometimes !!!!when the request comes back to site1 after authenticatio