Stack that implements try and catch problem

Hi guys, i'm pretty new to java (and programming all together) , have a difficulties with this calculator i'm working on.
I've got a stack which holds for instance 5 + 6 * 2
which equals 17. What i have is:
Stack<String> expression = new Stack<String>(
while(expression.size() >= 2){
String X = new String();
String Y = new String();
X = expression.pop();
System.out.println("popin stack"+X); //debuggin purposes
try {double x = Double.parseDouble(X);  
               if (X.equals('+')) {
                   Y = expression.pop();
                   double y = Double.parseDouble(Y);
                   String result = Operation.PLUS.eval(x,y);
                   System.out.println(result);
                   expression.push(result);
else if (X.equals('-')) {
Y = expression.pop();
double y = Double.parseDouble(Y);
String result = Operation.MINUS.eval(x,y);
System.out.println(result);
expression.push(result);
else if (X.equals('/')) {
Y = expression.pop();
double y = Double.parseDouble(Y);
String result = Operation.DIVIDE.eval(x,y);
System.out.println(result);
expression.push(result);
else {
Y = expression.pop();
double y = Double.parseDouble(Y);
String result = Operation.TIMES.eval(x,y);
System.out.println(result);
expression.push(result);
catch () { }
My idea behinde this was i'd used the try statement
to prevent the element being converted to a double if it isn't a String which this can be done to i.e any integer. I'm not sure if i've gone about this right. And have not idea of what i'm suppose to be catchin i.e the throwable?. Any input/direction would be great, thanks.

Hi guys, i'm pretty new to java (and programming all together) , have a difficulties with this calculator i'm working on.
I've got a stack which holds for instance 5 + 6 * 2
which equals 17. What i have is:
Stack<String> expression = new Stack<String>(
while(expression.size() >= 2){
     String X = new String();
     String Y = new String();
     X = expression.pop();
     System.out.println("popin stack"+X); //debuggin purposes
     try {double x = Double.parseDouble(X);
     if (X.equals('+')) {
           Y = expression.pop();
           double y = Double.parseDouble(Y);
           String result = Operation.PLUS.eval(x,y);
           System.out.println(result);
           expression.push(result);
      else if (X.equals('-')) {
           Y = expression.pop();
           double y = Double.parseDouble(Y);
           String result = Operation.MINUS.eval(x,y);
           System.out.println(result);
           expression.push(result);
     else if (X.equals('/')) {
           Y = expression.pop();
           double y = Double.parseDouble(Y);
           String result = Operation.DIVIDE.eval(x,y);
           System.out.println(result);
           expression.push(result);
     else {
           Y = expression.pop();
           double y = Double.parseDouble(Y);
           String result = Operation.TIMES.eval(x,y);
           System.out.println(result);
           expression.push(result);
     catch () { }
} My idea behinde this was i'd used the try statement
to prevent the element being converted to a double if it isn't a String which this can be done to i.e any integer. I'm not sure if i've gone about this right. And have not idea of what i'm suppose to be catchin i.e the throwable?. Any input/direction would be great, thanks.
Edited by: javaUser on Dec 30, 2007 5:59 PM

Similar Messages

  • With out try and catch

    with out any try and catch is exception handling is possible in java when doing manupulation with database.
    assume mydatabase is oracle,if i am going to insert a record of a primarykey field, which is already existing.i don't want to put with in try and catch.This is my case.if u have the answer for this please mail me.
    thanks
    rajan

    assume mydatabase is oracle,if i am going to insert a
    record of a primarykey field, which is already existing.
    i don't want to put with in try and catch.why not? i thought the fact that checked exceptions get thrown from methods is a good thing, since you're forced either to deal with the fault immediately, or throw to the next level up, possibly transformed into an application-level exception. if methods were to simply return method-specific error codes, nothing forces anything in the program to deal with errors in a reasonable manner. not that exceptions force sensible handling of the fault--but they do force recognition of the fault.
    what alternative do you desire?
    --p

  • How the try and catch blocks work?

    For the following section of code from the class QueueInheritanceTest...how the try and catch blocks work?
    The Class...
    public class QueueInheritance extends List {
    public QueueInheritance() { super( "queue" ); }
    public void enqueue( Object o )
    { insertAtBack( o ); }
    public Object dequeue()
    throws EmptyListException { return removeFromFront(); }
    public boolean isEmpty() { return super.isEmpty(); }
    public void print() { super.print(); }
    Testing...
    public class QueueInheritanceTest {
    public static void main( String args[] ){
    QueueInheritance objQueue = new QueueInheritance();
    // Create objects to store in the queue
    Boolean b = Boolean.TRUE;
    Character c = new Character( '$' );
    Integer i = new Integer( 34567 );
    String s = "hello";
    // Use the enqueue method
    objQueue.enqueue( b );
    objQueue.enqueue( c );
    objQueue.enqueue( i );
    objQueue.enqueue( s );
    objQueue.print();
    // Use the dequeue method
    Object removedObj = null;
    try { while ( true ) {
    removedObj = objQueue.dequeue();
    System.out.println(removedObj.toString()+" dequeued" );
    objQueue.print();
    catch ( EmptyListException e ) {
    System.err.println( "\n" + e.toString() );

    If you want a basic introduction to try/catch blocks, read any introductory text or the tutorials on this site.
    Here are some:
    Sun's basic Java tutorial
    Sun's New To Java Center.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns."
    In terms of this particular case, it looks like the code is using an exception being thrown to get out of a loop. IMHO that's bad design -- exceptions should be used for exceptional circumstances, and if you use it to get out of a loop, then you're certain it's going to happen, and that means that it's not exceptional.
    When you post code, please wrap it in  tags so it's legible.

  • Is there try and catch in oracle query ?

    hi
    is there try and catch in oracle query ?
    try
    do some update
    catch
    if there was error go to here
    }

    >
    is there try and catch in oracle query ?
    >
    Yes - except it uses BEGIN --- EXCEPTION --- END where BEGIN replaces the try and EXCEPTION replaces the catch.
    BEGIN
    -- Calculation might cause division-by-zero error.
       pe_ratio := stock_price / net_earnings;
       dbms_output.put_line('Price/earnings ratio = ' || pe_ratio);
    EXCEPTION  -- exception handlers begin
    -- Only one of the WHEN blocks is executed.
       WHEN ZERO_DIVIDE THEN  -- handles 'division by zero' error
          dbms_output.put_line('Company must have had zero earnings.');
          pe_ratio := null;
       WHEN OTHERS THEN  -- handles all other errors
          dbms_output.put_line('Some other kind of error occurred.');
          pe_ratio := null;
    END;  -- exception handlers and block end here
    /The multiple WHEN conditions correspond to using multiple 'catch' statements in Java.

  • Try and Catch don't work on powershell module

    Hi everyone,
    i'm tring to create a module with a try and catch, but when i call it, the block of expetion doesn't work as i expect, while if i use the code as a function only it works...
    Here the code
    function global:Process{
    param([string]$Process)
    ######################################MAIL################################
    function global:SendMail(){
    param([string]$Services)
    $Dest="xxx"
    $smtpServer = "xxx"
    $msg = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = "xxx"
    $msg.To.Add($Dest)
    $msg.Subject = "Notification about $Services activity"
    $msg.Body = "xxxx"
    $smtp.Send($msg)
    switch($Process){
    "DSP"{
    if((Get-Service Fax | ForEach-Object {$_.Status}) -eq "Stopped"){
    try
    start-service Fax -ea Stop
    catch
    if ( $error[0].Exception -match "Microsoft.PowerShell.Commands.ServiceCommandException")
    $error[0].Exception | Out-File C:\log.txt
    $SendMail $Process
    elseif((Get-Service Fax | ForEach-Object {$_.Status}) -eq "Running"){
    Stop-Service Fax}
    Export-ModuleMember -Function Process
    Could you help me? Thanks so much
    Cristian

    Hello,
    You should ask in the
    Windows PowerShell forum.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book:
    Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C406F75746C6F6F6B2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • Repost as question for points: What did I do wrong? (Try and Catch program)

    This has to be a try and catch program.
    This is the given output sample:
    OUTPUT SAMPLE #2 for input.txt: 12345 222256 -3 123 -56784 555557 6345678 x x x 81234 121212 x x 123434 x x 1009098 2099
    Please input the name of the file to be opened: input.txt
    For number 12345 the sum of digits is: 15
    For number 222256 the sum of digits is: 19
    Found an integer (-3), but it is negative. Will ignore!
    For number 123 the sum of digits is: 6
    Found an integer (-56784), but it is negative. Will ignore!
    For number 555557 the sum of digits is: 32
    For number 6345678 the sum of digits is: 39
    For number 81234 the sum of digits is: 18
    For number 121212 the sum of digits is: 9
    For number 123434 the sum of digits is: 17
    For number 1009098 the sum of digits is: 27
    For number 2099 the sum of digits is: 20
    Here is what I have so far.
    import java.util.Scanner;
      import java.io.*;// FileNotFoundException
    public class Assignment3b {
      public static void main (String[]args){
        Boolean fileOpened = true; 
        String fileName;
        int n,mod=0,sum=0,t=0;
        Scanner inputFile = new Scanner(System.in);
        System.out.print("Please input the name of the file to be opened: ");
        fileName = inputFile.nextLine();
        System.out.println();
        try {
                inputFile = new Scanner(new File(fileName));
            catch (FileNotFoundException e) {
                System.out.println("--- File Not Found! ---");
                fileOpened = false;
            if (fileOpened) {
              while (inputFile.hasNext()){
                if (inputFile.hasNextInt()){
                  n = inputFile.nextInt();
                  t=n;
                  while(n>0){
                    mod = n % 10;
                    sum = mod + sum;
                    n = n/10;
                  System.out.println ("For number " + t + " the sum of digits is : " + sum);
                  mod = 0;
                  sum = 0;
                  while (n<0) {
                    System.out.println ("Found an integer (" + t + "), but it negative. Will ignore!");
                    inputFile.next();
                    n = inputFile.nextInt();
                else {
                  inputFile.next();
    }Everything seems to work fine until, it is time to deal with negative numbers. How can I fix this. Please put your reply in layman's terms to the best of your ability.
    Thanks and God Bless.

    // COSC 236                                Assignment # 3
    // YOUR NAME: Anson Castelino
    // DUE-DATE:
    // PROGRAM-NAME: Assignment # 3 Prt2
    //import packages
      import java.util.Scanner;
      import java.io.*;// FileNotFoundException
    public class Assignment3b {
      public static void main (String[]args){
        Boolean fileOpened = true; 
        String fileName;
        int n,mod=0,sum=0,t=0;
        Scanner inputFile = new Scanner(System.in);
        System.out.print("Please input the name of the file to be opened: ");
        fileName = inputFile.nextLine();
        System.out.println();
        try {
                inputFile = new Scanner(new File(fileName));
            catch (FileNotFoundException e) {
                System.out.println("--- File Not Found! ---");
                fileOpened = false;
            if (fileOpened) {
              while (inputFile.hasNext()){
                if (inputFile.hasNextInt()){
                  n = inputFile.nextInt();
                  t=n;
                  while(n>0){
                    mod = n % 10;
                    sum = mod + sum;
                    n = n/10;
                  System.out.println ("For number " + t + " the sum of digits is : " + sum);
                  mod = 0;
                  sum = 0;
                  if (n<0) {
                    System.out.println ("Found an integer (" + t + "), but it is negative. Will ignore!");
                    inputFile.next();
                  inputFile.hasNext();
                else {
                  inputFile.next();
    }Updated code.
    current output is as follows:
    Please input the name of the file to be opened: [DrJava Input Box]
    For number 12345 the sum of digits is : 15
    For number 222256 the sum of digits is : 19
    For number -3 the sum of digits is : 0 <-------- this part is not suppose to be here.
    Found an integer (-3), but it is negative. Will ignore!
    For number -56784 the sum of digits is : 0 <-------- this part is not suppose to be here.
    Found an integer (-56784), but it is negative. Will ignore!
    For number 6345678 the sum of digits is : 39
    For number 81234 the sum of digits is : 18
    For number 121212 the sum of digits is : 9
    For number 123434 the sum of digits is : 17
    For number 1009098 the sum of digits is : 27
    For number 2099 the sum of digits is : 20
    >

  • Textfields Try and Catch

    Hi All, just a quick question really...
    Was wondering how I would go about checking user inputs into textfields?
    For example if the user enters the number 12 and you're only allowed to enter numbers between 1-10 how could I send a pop up error message to say "You can only enter numbers between 1-10"
    A way I thought about doing this was with a try and catch method, there could be another way of doing this, all other methods appreciated too.
    function captureNumbers(evt:MouseEvent):void {
    try{
    numberSelect.push(Number(number1.text));
    catch{
    if (numberSelect > 10){
    throw new Error("You must choose a number between 1 - 10");
    button1.addEventListener( MouseEvent.MOUSE_UP, captureNumbers);
    This is what ive got so far which doesn't seem to be working...
    Thanks in advance

    public class userBean(String user) {
         // Loads user preferences
         String fname;
         String lname;
         String greeting;
         void public readDB()
              Connection conn = null;
              PreparedStatement pstmt = null;
              ResultSet result = null;
              try {
                   Class.forName("oracle.jdbc.driver.OracleDriver");
              catch (Exception e) { System.out.println("Can't load JDBC driver:" + e); return; }
                   try{
                   conn = DriverManager.getConnection
                       ("jdbc:oracle:thin:@username.domain.com:1521:adm2", "login", "pass");
                   // @machineName:port:SID,   userid,  password d     
                   stmt = conn.prepareStatement("select fname,lname,greeting from people where userid = ?");
                     stmt.setString(1,user);
                     result= stmt.executeQuery();
                     fname = result.getString(1);
                     lname = result.getString(2);
                     stmt.close();
                   catch (Exception e) { System.out.println("Error with JDBC Connection:" + e); return;}          
    }

  • Help with try and catch

    I know I posted this quesiton earlier,but I am sitll having problems. In the following code, the exception IS caught if the user enters a String instead of a Int. But the Exception is NOT caught if the user enters
    the "Enter" key.
                do
                              flag=false;
                     //set the quantity to user input                                                   
                     System.out.print("Enter the quantity:");
                     try
                       amount = input.nextInt();
                          if (amount > 0)  //executes when amount is less then or equal to zero
                             flag=false; 
                          } //end of if
                          else
                               System.out.println("You must enter a positive quantity");
                                              flag=true;
                     }  //end of try
                     catch (Exception e)
                                      input.nextLine();
                                      System.out.println("You must enter a number");
                                      flag=true;
                }while(flag==true);  //end of do while
                          

    nextInt won't read "just the enter key"... it blocks until reads "something".
    Try something like this instead...
    Note: java.io.Console is new in 1.6
    package krc.utilz.io;
    // usage:
    // import krc.utilz.io.Console;
    // String name = Console.readLine("Enter your name : ");
    // while ( (score=Console.readInteger("Enter a score between 0 and 100 (enter to quit) : ", 0, 100, -1)) != 1) { ... }
    import java.util.Date;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    public abstract class Console
      private static final java.io.Console theConsole = System.console();
      private static final DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
      public static String readLine(String prompt) {
        while(true) {
          try {
            System.out.print(prompt);
            return theConsole.readLine();
          } catch (Exception e) {
            System.out.println("Oops: "+e);
      public static Date readDate(String prompt) {
        while(true) {
          try {
            String response = readWord(prompt+" (dd/mm/yyyy) : ");
            return dateFormatter.parse(response);
          } catch (Exception e) {
            System.out.println("Oops: "+e);
      public static String readWord(String prompt) {
        String response = null;
        while(true) {
          try {
            response = readLine(prompt);
            if( response!=null && response.length()>0 && response.indexOf(' ')<0 ) break;
            System.out.println("A single word is required. No spaces.");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
        return(response);
      public static char readLetter(String prompt) {
        char c = '\0';
        while(true) {
          try {
            String response = readLine(prompt);
            if ( response!=null && response.length()>0 ) {
              c = response.charAt(0);
              if(Character.     isLetter(c)) break;
            System.out.println("A letter (A through Z) is required. Upper or lower case.");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
        return(c);
      public static int readInteger(String prompt) {
        int i = 0;
        String response = null;
        while(true) {
          try {
            response = readLine(prompt);
            if ( response!=null && response.length()>0 ) {
              i = Integer.parseInt(response);
              break;
            System.out.println("An integer is required.");
          } catch (NumberFormatException e) {
            System.out.println("\""+response+"\" cannot be interpreted as an integer!");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
        return(i);
      public static int readInteger(String prompt, int lowerBound, int upperBound) {
        int i = 0;
        while(true) {
          i = readInteger(prompt);
          if ( i>=lowerBound && i<=upperBound ) break;
          System.out.println("An integer between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
        return(i);
      public static int readInteger(String prompt, int defualt) {
        int i = 0;
        String response = null;
        while(true) {
          try {
            response = readLine(prompt);
            return (response!=null && response.trim().length()>0
              ? Integer.parseInt(response)
              : defualt
          } catch (NumberFormatException e) {
            System.out.println("\""+response+"\" cannot be interpreted as an integer!");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
      public static int readInteger(String prompt, int lowerBound, int upperBound, int defualt) {
        int i = 0;
        while(true) {
          i = readInteger(prompt, defualt);
          if ( i==defualt || i>=lowerBound && i<=upperBound ) break;
          System.out.println("An integer between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
        return(i);
      public static double readDouble(String prompt) {
        double d = 0;
        String response = null;
        while(true) {
          try {
            response = readLine(prompt);
            if ( response!=null && response.length()>0 ) {
              d = Double.parseDouble(response);
              break;
            System.out.println("A number is required.");
          } catch (NumberFormatException e) {
            System.out.println("\""+response+"\" cannot be interpreted as a number!");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
        return(d);
      public static double readDouble(String prompt, double lowerBound, double upperBound) {
        while(true) {
          double d = readDouble(prompt);
          if ( d>=lowerBound && d<=upperBound ) return(d);
          System.out.println("A number between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
      public static boolean readBoolean(String prompt) {
        while(true) {
          try {
            String response = readWord(prompt+" (Y/N) : ");
            return response.trim().equalsIgnoreCase("Y");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
    }

  • Test and trust Class.isInstance or try and catch Class.cast ?

    I found this related thread, with no answer to my question.
    In the below code, there is a certain level of redundancy in that I am checking that I can do the Class.cast() prior to doing it, via Class.isInstance().
    I can either omit the isInstance() check and just count on cast() throwing an exception, or I can ignore the ClassCastException (do nothing in the catch block, as shown below).
    Which is better? Is it faster if I just omit the instance check and let cast() detect the errors? Is there a style convention here?
        protected <T extends ParentClass> List<T> getItemsOfType(Class<T> clazz){
            List<T> retval = new ArrayList<T>();
            for(ParentClass t : items.values()){
                if(clazz.isInstance(t)){
                    try{
                        retval.add(clazz.cast(t));
                    catch(ClassCastException cce){
                        // should never happen
        }Thanks for your time

    Derrick.Rice wrote:
    I found this related thread, with no answer to my question.
    In the below code, there is a certain level of redundancy in that I am checking that I can do the Class.cast() prior to doing it, via Class.isInstance().
    I can either omit the isInstance() check and just count on cast() throwing an exception, or I can ignore the ClassCastException (do nothing in the catch block, as shown below).
    Which is better? Is it faster if I just omit the instance check and let cast() detect the errors? Is there a style convention here?Whatever you decide, just keep in mind that there is a semantic difference too:
    if(clazz.isInstance(t)) retval.add(clazz.cast(t));will only add instances of the requested class, whereas
    try { retval.add(clazz.cast(t)); } catch(ClassCastException e) {} will also add null values.

  • Help, try and catch and variables

    I have a private vector in one of my objects, i then add some items to it at the beginning of a method, the program then goes into a try/catch block where i add some more variables.
    However, the variables i add in the try/catch block only seem to exist within that block.
    In another method i refer to the vector again, but it only contains the elements i added before the try/catch block.
    Any suggestions?

    headers = new Vector();
    headers.add("String 1");
    headers.add("String 2");
    connect("database");
    System.out.println("Connected");
    try
    String mySQL = "SELECT * FROM " + table;
    Statement st = c.createStatement();
    System.out.println("Statement Created");
    st.executeQuery(mySQL);
    catch (Exception e)
    try
    StringTokenizer tk = new StringTokenizer(layoutString, "|");
    while (tk.hasMoreTokens())
    String tmpStr = tk.nextToken();
    if (tmpStr.equalsIgnoreCase("ScalePanel"))
    String tmp = tk.nextToken();
    headers.add(tmp);
    headers.add("number");
    else if (tmpStr.equalsIgnoreCase("OptionPanel"))
    String tmp = tk.nextToken();
    headers.add(tmp);
    headers.add("varchar(20)");
    else if (tmpStr.equalsIgnoreCase("InputPanel"))
    String tmp = tk.nextToken();
    headers.add(tmp);
    headers.add("varchar(20)");
    System.out.println("Table Doesn't Exist, creating...");
    String mySQL = "create table " + table + " (";
    for (int i = 0 ; i < headers.size() ; i++)
    if (i == 0)
    mySQL += headers.get(i) + " " + headers.get(++i);
    else
    mySQL += "," + headers.get(i) + " " + headers.get(++i);
    mySQL += ");";
    Statement st = c.createStatement();
    st.execute(mySQL);
    catch (Exception ex)
    System.out.println("Error while creating table");
    System.out.println(ex.getMessage());
    disconnect();
    I then refer to headers in another method, but it only contains the items before the try/catch.

  • Is there a program that finds hardware and OS problems?mid-2012 pro

    What about spywear?... my answering machine turned on then router was accessable to my laptop!!!! I now keep the mac router unplugged when not in use.
    Also, the 10.4.11 pro USB out to a perifferial microprocessor (arduino uno R3) has stopped communicating in either USB port How can I check to see if it works. Both USB ports r/w to flash drives. So what to do now?

    I've never actually done this, but don't think it will work for the purpose of running a task in a regular app like Synk Pro. Launching Synk Pro - even, I would think, from a logout script - will cancel logout. Of course, if Ham1000 is willing and able, he could probably replace Synk Pro with a call to rsync from a logout script:
    http://www.bananica.com/Geek-Stuff/Synchronize-two-folders-on-a-Mac-with-Rsync/
    Interesting idea...

  • My MacBook Pro ran out of battery and shut down ,will power up but goes   to panic screen on start up but nothing else , how can I get past this screen to try  to fix problem?

    MacBook Pro battery ran low and computer shut down , after charging battery I tried to start up and I got an Apple on a gray screen with spinning wheel that went to a panic call out screen and that's as far as it will go. I've tried start up with command keys ,a few got me to a different screen but nothing has let me into any place I can use to try and repair problem. Anybody have an idea of what's wrong with my laptop and a way to fix it ?

    see if you can start up in safe mode.  What is safe mode?

  • Try catch problem

    Here's my code:
    import javax.swing.*;
    import java.io.*;
    public class Customer
         try
              public RandomAccessFile file = new RandomAccessFile("customer.txt", "rw");
         catch(FileNotFoundException fnfe)
         public static void readCustomer(String telp)
         public static void writeCustomer(String telp, String name, String add1, String add2)
    and here's the error msg:
    C:\TEMP\Tar\TestOrder\Customer.java:7: illegal start of type
         try
    ^
    C:\TEMP\Tar\TestOrder\Customer.java:20: <identifier> expected
    ^
    2 errors
    Tool completed with exit code 1
    Can anyone pls tell what i did wrong? btw, i used TextPad to compile it
    Thanks
    Daffy

    hi,
    try and catch should be in a method.
    try this
    public class Customer
    public RandomAccessFile {
         try
    file = new RandomAccessFile("customer.txt", "rw");
         catch(FileNotFoundException fnfe)

  • Txt file read in- StringTokenizer- Try Block Catch for errors

    Hello
    So I am having a few issues with a school project. First is with my ReadWithScanner. It does not read in the file giving me a NullPointerException error on the line <Scanner in = new>. I have tried a few other read in files and they do not seem to be working.
    I am also stuck on the logic on the try block catch statement. How does a person set up a �custom� try block that looks for errors like the ones below? I have attempted to start in the commented code.
    The text file has to read in 1000 individual lines of code and are separated by �;� and should be separated into tokens with the StringTokenizer class what I attempted to do below also. Both are mere attempts and need help�
    This is some what of the logic I thought of doing
    1.Read the first line in first with the scanner class
    2.use delimiter separated by �;�
    3.Tokenizer the line into separate tokens- invoiceCode, fName, lName�
    4.Check classes- check Name, check Date, checkPrice, checkPrice, checkGenre, checkShippingDate invoiceCode = "Error Code" checkInvoiceCode(String invoiceCode)checkName(String name), checkPrice(String price), checkGenre(String genre)
    5.Apply the regular expressions to each try block statement
    a.Assign a letter to each error for example if invoice was to short it would be assigned a letter A
    b.If invoice does have the right characters it would be assigned B
    c.If name has to few words it would be assigned D
    d.�
    This is an example of a good field from the text file
    XYG726;Smith,Mr. John M.;29.96;comedy;101008;100604
    Not so good line
    Lu15;Will, Mark;50.00;Science;030305;030807
    The file should then be printed out in the program not to a text file. It only needs to print the invoice number and error code letter assignment.
    If you have any questions feel free to let me know. Thanks for all or any help you have to offer.
    Invoice
    Three upper case letters followed by three digits
    Regular Expression "[A-Z]{3}[0-9]{3}"
    Customer Name
    Should be in the form: last name followed by a <,> optional title (Mrs. Mrs�) then first name optional middle initial Titles must be
    So regular expression something like �[a-z][A-Z]+([A-Z]{1}?[a-z][./})+[a-z][A-Z]�
    Sale Price
    Two decimal digits to the left of the decimal point. The price should not have a leading zero.
    Regular Expression [0-9]{2}*./[0-9]
    Genre
    The genre should only contain lowercase letters. Regular expression �[a-z]�
    ShipDate and Order Date-
    Must be standard dates- MMDDYY. The order date and shipping date has to be after today�s date. Regular expression �[0-9]{2}+[0-9]{2}+[0-9]{2}�
    package Project3;
    import java.util.StringTokenizer;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.util.Scanner;
    public class ReadWithScanner {
    private final File fFile;
    public static void main (String args[]){
    Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
    Scanner.processLineByLine();
    public ReadWithScanner(String aFileName){
    fFile = new File(aFileName);
    public final void processLineByLine(){
    try {
    //use a Scanner to get each line
    Scanner scanner = new Scanner(fFile);
    while ( scanner.hasNextLine() ){
    processLine( scanner.nextLine() );
    scanner.close();
    catch (IOException ex){
    protected void processLine(String aLine){
    //use a second scanner again to raed the content of each line
    Scanner scanner = new Scanner(aLine);
    scanner.useDelimiter(";");
    if (scanner.hasNext() ){
    //read each file?
    String name = scanner.next();
    String value = scanner.next();
    else {
    scanner.close();
    //Token Names that are seperated
    StringTokenizer st;
    String invoiceCode = st.nextToken();
    String fname = st.nextToken();
    String lname = st.nextToken();
    String price = st.nextToken();
    String genre = st.nextToken();
    String orderDate = st.nextToken();
    String shipDate = st.nextToken();
    String invoiceCode;
    invoiceCode = "A" checkInvoiceCode(String invoiceCode);
    Pattern p = Pattern.compile("[a-z]{6}[A-Z]{6}[0-9]{6}");
    Matcher m = p.matcher(invoiceCode);
    p.matcher(invoiceCode);
    if(m.matches()) {
    System.out.println(invoiceCode);
    else {
    System.out.println ("A");
    try
    invoiceCode = Integer.parseInt(String);
    catch (NumberFormatException e)
    { System.out.println ("B"); System.exit(1); }
    */

    I have made a quite a few updates to my code. Please look it over again. I have also made many comments to help with the logic. Once again if you have any questions please feel free to ask. Sorry about not using the tags before- I was no aware of them. Thanks for the advice sabre150.
    package Project3;
    import java.util.StringTokenizer;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.util.Scanner;
    public class ReadWithScanner {
         private final File fFile;
         public static void main (String args[]){
                   //read in text file from directory currently it can not read the file
                  Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
                  //Scans each line of the text in
                  Scanner.processLineByLine();
                //assigns new file name to file
                public ReadWithScanner(String aFileName){
                  fFile = new File(aFileName); 
                public final void processLineByLine(){
                  try {
                    //use a Scanner to get each line from the processLineByLine
                    Scanner scanner = new Scanner(fFile);
                    while ( scanner.hasNextLine() ){
                      processLine( scanner.nextLine() );
                    scanner.close();
                  catch (IOException ex){
                protected void processLine(String aLine){
                  //use a second scanner again to read the content of each line
                   //delmiter should then break each line in the text file into seperate "tokens"
                  Scanner scanner = new Scanner(aLine);
                  scanner.useDelimiter(";");
                  if (scanner.hasNext() ){
                       //reads each line from scanner
                    String name = scanner.next();
                  else {
                  scanner.close();
               /*Convert Tokens from Scanner into String Tokenizer with assigment to each variable
                * I am missing something
                * Need to convert each line read from the scanner (name variable) to the String
                * Tokenizer class
              //Tokens names now assigned a varaible
              StringTokenizer st;
              String invoice = st.nextToken();
              String name = st.nextToken();
              String price  = st.nextToken();
              String genre = st.nextToken();
              String orderDate = st.nextToken();
              String shipDate = st.nextToken();
          /*If statments (Try Block Statements?) with Regular Expressions
          * This is where I have the most issues on how to set up
          * "custom" try and block errors trying to match what I have
          * in the regular expressions. 
          * I believe try and catch statements
          * make this easier but I have used 'match' and 'pattern' with if
          * statments.  If try block statements are easier please show!
          * Regular Expressions may not be correct either
           invoice = checkInvoiceCode(invoice);
           //Defined cerita for Inovice are:
           //Error A = Invoice code is too short  
           //Error B = Invoice code does not have the right characters 
           //Error C = Invoice code digits are all zero
           //Checks for error A
           //Has at least six characters
            Pattern invoiceShort = Pattern.compile("{6}");
            Matcher shortInvoice = invoiceShort.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice);      
            else {
                 System.out.println ("A");
            //Checks for error B
            //3 Upper Case Letters followed by three numbers,
            Pattern rightChar = Pattern.compile("[A-Z]{3}[0-9]^0{3}");
            Matcher charRight = rightChar.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice);
            else {
                     System.out.println ("B");
            //Checks for error C
            //Where the last three digits are not all zeros
            Pattern notZero = Pattern.compile("*{3}^0{3}");
            Matcher ZeroNot = notZero.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice); 
                 else {
                     System.out.println ("C");
         //name = checkFullName(name);
         //Error D = Name field has fewer than two words
         //Error E = Name field has more than four words
         //Error F = Name field has no comma
         //Error G = Name field has a bad title 
         //Error H = Name field has a bad initial 
        /*Have a lot more to do...
        * Still need to go through the same if statement or Try Block statements with this data:
        *      String fname = st.nextToken();
              String lname = st.nextToken();
              String price  = st.nextToken();
              String genre = st.nextToken();
              String orderDate = st.nextToken();
              String shipDate = st.nextToken();
        * But for now I would like to see an example of an if statement I could use
        * (if mine is even right) or catch statement- the rest of the project we look
        * for similar certia as defined in the reg exp for invoice
         /*Writes to Report in the Console
         * Prints data into two columns:
         * Invoice Code and Error Type
         //Prints both column Headings
         private void columnHeadings ()
         System.out.println (padL("",5) +
         padL("Invoice",20) +padL("",20)+
         padL("Error Code",40));
         //movie is the name of the text file
         private void printMovie(Movie aReport) {
         System.out.println(aReport.getInvoiceCode()+"\t"+
               aReport.getErrorType()+"\t");
      *This method pads the string start to the length newLength leaving the
      *string left justified and returning the result.
      private String padL (String start, int newLength)
         String result = new String (start);
         while (result.length() <= newLength) result += " ";
         return result;
      } // end padL
       * This method pads the string start to the length newLength leaving the
       * string right justified and returning the result.
      private String padR (String start, int newLength)
         String result = new String (start);
         while (result.length() <= newLength) result = " " + result;
         return result;
    // end padRThanks a lot.

  • IOS 7 Update and Configurator Problems

    Since the iOS 7 update, we have been unable to 'Check In' devices with Configurator, and refreshing devices has been difficult.  We have iPad 2s and Configurator 1.3.1 running on Mac OS 10.7.5.  Sometimes the message is, "Could not create a backup", and sometimes the message is, "Unable to fetch a list of installed apps". Is anyone else having the same problems? 
    We have updated all software - OS, Configurator, iTunes, and all iOS Apps.  We have 4 paid apps (iMovie, Pages, Keynote and Configurator), and no free apps for the VPP account on each iPad.  Each iPad is named and assigned to one student.  Students have their own iTunes account to add free apps as needed.  The only way I have found that this works without error is to delete the student name from "Assign", but then I can't transfer any of their information when a device has problems. I have tried this with devices that are not having any problems to make sure it is not related to other problems.  These problems did not exist until the iOS 7 update.  Hopefully a Configurator update will be on the way soon?

    andrewgodin wrote:
    Here is what worked for me in dealing with this hot mess.
    Using iTunes, I went to each individual iPad and restored it to factory settings.  Takes about 5 minutes per iPad. 
    When it was done, I didn't set it up as a new iPad, I simply clicked the "eject" button so it no longer appeared in my list, which prevented me from restoring the same iPad twice and wasting time.
    Once all of them were done, which took an entire day, I opened up the updated version of configurator.  All of the iPads restored and installed the apps that I need and the problem was solved.
    Did this about five minutes ago.  Time will tell if it sticks, but for now, they are fixed.
    You could probably try to downgrade your iOS7 cart back to iOS6, that's what I ended up doing.

Maybe you are looking for