Unexpected type

Why does the following code error?
MyMenuInt.java
import java.awt.*;
import javax.swing.*;
public class MyMenuInt extends JFrame
     private static JTextArea jta=new JTextArea(20,15);
     private Integer count=0;
     public MyMenuInt()
          JPanel jp=new JPanel();
          JMenuBar jmb=new JMenuBar();
          JMenu Count=new JMenu("Count");
          JMenuItem inc=new JMenuItem("Inc");
          JMenuItem dec=new JMenuItem("Dec");
          JMenuItem reset=new JMenuItem("Reset");
          JMenuItem exit=new JMenuItem("Exit");
          jp.setLayout(new BorderLayout());
          jta.setText(String.valueOf(count+"\n"));
          jta.setEditable(false);
          JScrollPane jsp=new JScrollPane(jta);
          jp.add(jsp,BorderLayout.CENTER);
          add(jp);
          Count.add(inc);
          Count.add(dec);
          Count.add(reset);
          Count.add(exit);
          jmb.add(Count);
          MyCountListenerInt incl=new MyCountListenerInt(inc,count);
          MyCountListenerInt decl=new MyCountListenerInt(dec,count);
          MyCountListenerInt resetl=new MyCountListenerInt(reset,count);
          MyCountListenerInt exitl=new MyCountListenerInt(exit,count);
          setJMenuBar(jmb);
          Count.setMnemonic('C');
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setTitle("Practice Exercise Day 17");
          setSize(333,741);
          setVisible(true);
     public static void appendTextArea(String txt)
          jta.append(txt+"\n");
     public static void resetTextArea()
          jta.setText(String.valueOf(0+"\n"));
     public static void main(String args[])
          MyMenuInt mm=new MyMenuInt();
MyCountListenerInt.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyCountListenerInt implements ActionListener
     private static Integer num;
     //Make num static so that all the instances of this class share one reference of count
     //instead of each instance having its own reference which causes unsync'd output.
     //Since this variable is static, when Java does its optimizations and gets to the 2nd, 3rd, etc
     //instantiations of this class it sees that this variable is already in memory with a reference
     //to count so it uses the existing variable in memory instead of creating another reference.
     private JMenuItem jmi1;
     public MyCountListenerInt(JMenuItem jmi,Integer count)
          num=count;
          jmi1=jmi;
          jmi1.addActionListener(this);
     public void actionPerformed(ActionEvent ae)
          if(ae.getActionCommand().equals("Inc"))
               MyMenuInt.appendTextArea(String.valueOf(num+1));
               num+=1;
          if(ae.getActionCommand().equals("Dec"))
               MyMenuInt.appendTextArea(String.valueOf(num-1));
               num-=1;
          if(ae.getActionCommand().equals("Reset"))
               num=0;
               MyMenuInt.resetTextArea();
          if(ae.getActionCommand().equals("Exit"))
               System.exit(0);
}the error:
MyMenuInt.java:43: unexpected type
required: variable
found   : value
          jta.append(txt+"\n");
                    ^
1 errorthis is from:
public static void appendTextArea(String txt)
          jta.append(txt+"\n");
     }thanks! :)

kajbj wrote:
John_Musbach wrote:
Thanks for the replies, the dashes are really in my code to make it beautiful. My friend said it would work.It doesn't, unless you comment them out. E.g this works:
Oh oops, I totally forgot. Thanks for the reminder! :)

Similar Messages

  • Unexpected type error

    I am getting an unexpected type error in the following code:
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    public class Line
       public Line(int aClick, Point2D.Double[] aPoint)
          clicks = aClick;
          points = aPoint;
       public void draw(Graphics2D g2)
          if (clicks == 1)
             double x = points[0].getX();
             double y = points[0].getY();
             final double RADIUS = 5;
             Ellipse2D.Double smallCircle
                = new Ellipse2D.Double(x - RADIUS, y - RADIUS,
                   2 * RADIUS, 2 * RADIUS);
             g2.draw(smallCircle);
          else if (clicks >= 2)
             g2.draw(new Line2D.Double(points[0], points[1]));
             double x1 = points[0].getX();
             double y1 = points[0].getY();
             double x2 = points[1].getX();
             double y2 = points[1].getY();
             double length = Math.sqrt((x1 - x2)(x1 - x2) + (y1 - y2)(y1 - y2));
             message = "length = " + length;
             double mx = (x1 + x2) / 2;
             double my = (y1 + y2) / 2;
             g2.drawString(message, (float)mx, (float)my);
       private int clicks;
       private Point2D.Double[] points;  
    }double length = Math.sqrt((x1 - x2)(x1 - x2) + (y1 - y2)(y1 - y2)); this is the part that the compiler complains.
    here is the second part of the program:
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.Point2D;
    public class ExP10_10 extends Applet
       public ExP10_10()
          clicks = 0;
          points = new Point2D.Double[MAX_CLICKS];
          MousePressedListener listener = new MousePressedListener();
          addMouseListener(listener);
       public void paint(Graphics g)
          Graphics2D g2 = (Graphics2D)g;
          Line l = new Line(clicks, points);
          l.draw(g2);
       class MousePressedListener extends MouseAdapter
          public void mousePressed(MouseEvent event)
             if (clicks >= MAX_CLICKS) return;
             int mouseX = event.getX();
             int mouseY = event.getY();
             points[clicks] = new Point2D.Double(mouseX, mouseY);
             clicks++;
             repaint();
       private int clicks;
       private Point2D.Double[] points;
       private final int MAX_CLICKS = 2;
    }

    double length = Math.sqrt((x1 - x2)(x1 - x2) + (y1 - y2)(y1 - y2));Java doesn't automatically assume that two expressions next to each other are supposed to be multiplied. You need to be explicit:
    double length = Math.sqrt(((x1 - x2)*(x1 - x2)) + ((y1 - y2)*(y1 - y2)));The extra parentheses are not strictly necessary, as operator precedence will still put the multiplications before the addition. But, I always think it is best to be parenthesize things explicitly, so you don't have to worry about operator precedence (especially for things less obvious than multiplication before addition).
    I guess subtraction should be relatively fast, but for repeated operations, you could define:
    double xDiff = x1-x2;
    double yDiff = y1-y2;
    double length = Math.sqrt((xDiff * xDiff) + (yDiff * yDiff));

  • Unexpected type  required: variable   found   : value

    Hello, these are my errors:
    PWC6197: An error occurred at line: 43 in the jsp file: /jsp/ListRedirect.jsp
    PWC6199: Generated servlet error:
    string:///ListRedirect_jsp.java:96: unexpected type
    required: variable
    found : value
    PWC6197: An error occurred at line: 43 in the jsp file: /jsp/ListRedirect.jsp
    PWC6199: Generated servlet error:
    string:///ListRedirect_jsp.java:96: incomparable types: java.lang.String and int
    ==================================
    any suggestions??
    <%      
    if (listData.getListURL()= null || listData.getListInfo() == 0)
              String baseUrl = "/content/listings.html?";
             String listUrl = null;
                  if (userData.isAgentType()) {
                    listUrl = parentPage + baseUrl + "ag_id=" + userData.getAgentID();
                  }  if (userData.isBrokerType()) {
                  listUrl = parentPage + baseUrl + "br_id=" + userData.getAdverID();
                  }  if (userData.isOfficeType()) {
                  listUrl = parentPage + baseUrl + "ag_id="= + userData.getAdverID();
                  } else {
                  listUrl = parentPage + "/content/homefinder.html";
                   if (listData.getListURL() && listData.getListInfo() == 1) {
                       listUrl = listData.getListURL();
               else {
                    listUrl = parentPage + "/content/homefinder.html";
    %>     

    mimsc wrote:
    if (listData.getListURL()= null || listData.getListInfo() == 0)
    The 1st part of this if statement is incorrectly an assignment, not a equation.
    Further on, this code belongs in Java classes like servlets, not in JSPs. This would not only introduce clean code separation, but also greatly improve debugging and maintenance.

  • Unexpected type for field P

    Hi, i´m doing an app and in my device i want insert new row, the field is ZCANT, but when intent
    newValues[2] = "0000";
    worker.setFieldValue(sbdRowDesc.getFieldDescriptor("ZCANT"),newValues[2]);
    Appear this error:
    Unexpected type for field P
    What happend?
    Thanks,

    Hi Victor,
    What type of field is "ZCANT" ..i think you are assigning the wrong type of the value to this field.
    Regards,
    Rajan

  • Log warning "Link from unexpected type of object" ("Possible path leak, unable to purge elements of base")

    Hey,
    I'm getting the following warning after closing my LabVIEW application (see also LabVIEW code snippet attached).
    Can you help me figure out if this may be relevant?
    I don't experience anything unexpected, also no leaking of memory.
    Thanks,
    Peter
    #Date: Mo, 11. Nov 2013 15:14:42
    #OSName: Windows 7 Enterprise Service Pack 1
    #OSVers: 6.1
    #OSBuild: 7601
    #AppName: LabVIEW
    #Version: 12.0 32-bit
    #AppKind: FDS
    #AppModDate: 06/26/2012 19:23 GMT
    #LabVIEW Base Address: 0x00400000
    Processing 1230000708 link to [LinkIdentity "ProcessTaskWrapper.lvclass:" [ Mein Computer]
    <DEBUG_OUTPUT>
    11.11.2013 15:15:35.726
    DWarn 0xC1CF3BB8: Link from unexpected type of object {HeapClass=BDHP,UID=5401,DPId=23,o=0x0de33558} in VI [VI "ProcessPool.lvclass:configure.vi" (0x11646770)]
    e:\builds\penguin\labview\branches\2012\dev\source\linker\HeapLinker.cpp(2852) : DWarn 0xC1CF3BB8: Link from unexpected type of object {HeapClass=BDHP,UID=5401,DPId=23,o=0x0de33558} in VI [VI "ProcessPool.lvclass:configure.vi" (0x11646770)]
    minidump id: 236443a2-84d3-403e-a24a-fb72dd7ff65d
    $Id: //labview/branches/2012/dev/source/linker/HeapLinker.cpp#12 $
    </DEBUG_OUTPUT>
    0x0069DDF3 - LabVIEW <unknown> + 0
    0x10016460 - mgcore_SH_12_0 <unknown> + 0
    0x013E32A5 - LabVIEW <unknown> + 0
    0x00EBECFC - LabVIEW <unknown> + 0
    0x01060FD1 - LabVIEW <unknown> + 0
    0x0106112D - LabVIEW <unknown> + 0
    0x0106A5C9 - LabVIEW <unknown> + 0
    0x0106B6D1 - LabVIEW <unknown> + 0
    0x005C28D3 - LabVIEW <unknown> + 0
    0x005C03FC - LabVIEW <unknown> + 0
    0x005C1BCB - LabVIEW <unknown> + 0
    0x005C20AE - LabVIEW <unknown> + 0
    0x006495BC - LabVIEW <unknown> + 0
    0x009ECF0E - LabVIEW <unknown> + 0
    0x01CC57D4 - LabVIEW <unknown> + 0
    0x01CC5964 - LabVIEW <unknown> + 0
    0x006513E3 - LabVIEW <unknown> + 0
    0x00657C9D - LabVIEW <unknown> + 0
    0x00B87A67 - LabVIEW <unknown> + 0
    0x00B8C606 - LabVIEW <unknown> + 0
    0x00B8DA6D - LabVIEW <unknown> + 0
    0x014A90C2 - LabVIEW <unknown> + 0
    0x014ABA3C - LabVIEW <unknown> + 0
    0x014ADA42 - LabVIEW <unknown> + 0
    0x01B4BE87 - LabVIEW <unknown> + 0
    0x01BF99C5 - LabVIEW <unknown> + 0
    0x01B5DBFC - LabVIEW <unknown> + 0
    0x761D62FA - USER32 <unknown> + 0
    0x761D6D3A - USER32 <unknown> + 0
    0x761D77C4 - USER32 <unknown> + 0
    0x761D788A - USER32 <unknown> + 0
    0x01BF9C4D - LabVIEW <unknown> + 0
    0x01BFA0C7 - LabVIEW <unknown> + 0
    0x042F14D6 - QtManager452_2012 <unknown> + 0
    0x670E7261 - NIQtCore_2012 <unknown> + 0
    0x00000000 - <unknown> <unknown> + 0
    Possible path leak, unable to purge elements of base #0
    Attachments:
    2013-11-11_153125.jpg ‏48 KB

    Hello Peter,
    as you can imagine, it is difficult for us to interpret an error message without a certain amount of information.
    Even more, when you cannot reproduce it yourself every time.
    And, on a side note, we as Application Engineers do not know how exactly the compiler works.
    This could be something for the developers, but: to escalate an issue to the developers, there are some requirements.
    - we have to know exactly when and how the error occurs, i.e. the exact steps which have to be done, so you can force the error to show up
    - exact OS, LabVIEW version, all NI Software which is installed
    - what is the application
    - what has been done as troubleshooting actions, can the issue be avoided somehow
    - we would need your VI or project, or at least a minimal version of them, which can produce the error message
    - one of us should be able to reproduce the procedure and get the same error
    I am sorry, but at this point, it seems like I cannot do much for you in this topic.
    Have a nice day,
    Best regards
    PS: one more question:
    is this even a message from LabVIEW? For me, it seems like a Windows crash report - which we can not fully support.
    Christopher W.
    Intern Application Engineering | NI Certified LabVIEW Associate Developer (CLAD) | NI Germany

  • Recieving unexpected type error.

    This is my code for now and I am recieving an "unexpected type" message. at the line that is in bold. If anyone could lend me a hand that would be great. If i am doing it wrong and you can catch it also please let me know. thanks.
    * This class simulates a person walking through an alley with the potential
    * to take one step in either direction until they reach the end of the alley.
    * @author (Greg Esposito)
    * @version (11-17-06)
    public class AlleyWalker {
    private Die AlleyWalker;
    private int goaldistance;
    private int numSteps;
    private int position;
    public AlleyWalker() {
    this.AlleyWalker = new Die(2);
    this.goaldistance = 10;
    this.numSteps = 0;
    this.position= 0;
    public int getNumSteps() {
    return this.numSteps;
    public int getPosition() {
    return this.position;
    public void reset() {
    this.position = 0;
    public void step () {
    if (this.AlleyWalker.roll() = 1) {
    this.AlleyWalker.step(1);
    this.position = this.position + 1;
    this.numSteps = this.numSteps + 1;
    else if (this.AlleyWalker.roll() = 2) {
    this.AlleyWalker.step(-1);
    this.position = this.position - 1;
    this.numSteps = this.numSteps + 1;
    Message was edited by:
    giocatore83

    Alright that worked out thanks. One last thing. I have to make a method where the program runs through the rolls until it reached 10 or -10. I am not sure how I should do this. If anyone could lend a helping hand on that let me know. Thanks

  • Compiler throws "unexpected type" error

    Hi,
    I am newbie to Generics, I wrote the below program as part of my learning exercise:
    =================
    class One<T> implements Comparable<? extends One<T>>
         T var;
         public void setVal(T val){
              var=val;
         public T getVal(){
              return this.var;
         public int compareTo(One<T> o1){
              if(this.getVal().equals(o1.getVal())){
    return 0;
    }else {
    return 1;
    class Two<T> extends One<T>
         public int compareTo(Two o1){
              // do nothing
              return 0;
    class GenTest
         public static void main(String[] args)
              One<String> obj_01=new One<String>();
              obj_01.setVal("Vinayaka");
              One<String> obj_02=new One<String>();
              obj_02.setVal("Vinayaka");
    =========
    Compilation fails with the below error:
    javac GenTest.java
    GenTest.java:1: unexpected type
    found : ? extends One<T>
    required: class or interface without bounds
    class One<T> implements Comparable<? extends One<T>>
    ^
    1 error
    Can any one please explain me what is wrong with this program ?

    You are mixing syntaxes. Your definition should be:
    class One<T> implements Comparable<One>(PS: please use code tags when posting code)

  • Unexpected type - help

    Hello
    I need some guidens from you.
    I am trying to construct a program who performes Euclides algorithm.
    unfortunately I have had problems. Every time I compile I get the same exception:
    Unexpected type
    java 22\ int sum = a - b = r;
    ^
    hopefully someone can give me some advice.
    Over and out
    Xano
    import javax.swing.*;
    import java.awt.*;
    public class Euclides {
    int a;
    int b;
    public static void main(String[] args) {
           String indata1 = JOptionPane.showInputDialog("write integer A " );
           int a = Integer.parseInt(indata1);
           String indata2 = JOptionPane.showInputDialog("write integer B " );
           int b = Integer.parseInt(indata2);
    int r;
    while(r != 0) {
         a - b = r;
         r = b;
         b = a;
    }//while
         String sgd = JOptionPane.showInputDialog("SGD" + b);
    }//main()
    }//class Euclides

    a - b = r;Try
    r = a - b;
    Assignment is right-to-left.

  • Instanceof Parameterized Type

    Hello,
    I have this function:
    public final int compareTo(Object o)
        else if (o instanceof T)
                return compareTo((T)o);
    }The problem is that the "else if" line gives me the following compilation error:
    unexpected type
    found : T
    required: class or array
    Does somebody know why I'm getting this error? T is a parameterized type so I should not have had any problem using the instanceof operator with it.
    Thanks.

    sorry bcoz I m not writing any reply to your message instead I wanted to contact you for my own problem. about two months ago you posted your problem of IllegalStateException: GL_VERSION I m facing the same one. I hope you have found out its solution kindly can you help me.

  • The pythagoren theorem

    I need help with printing out this formula.
    a^2 + b^2 = hypotenus^2
    heres a code I have been given for a little help, but it doesn't work
    I keep getting an error (unexpected type).
    a = sqrt (hypotenuse2 - b2 )
    I figured it was because the 2's werent written in the power form so i tried...
    a = sqrt (hypotenuse^2 - b^2 )
    an i still get the error. If anyone can help me with nmaking the powers work, that would greatly be appreciated. Thanks!
    Jbinks~ .

    Actually, this will do:
    int a=(int)Math.sqrt(hypotenuse*hypotenuse-b*b);There's an implicit conversion done for you.
    Here's how I'd do it:
    public class Pythagoras
        public static void main(String [] args)
            try
                if (args.length > 1)
                    double c = Double.parseDouble(args[0]);
                    double b = Double.parseDouble(args[1]);
                    double a = Pythagoras.calculateSide(b, c);
                    System.out.println("a: " + a);
                    System.out.println("b: " + b);
                    System.out.println("c: " + c);
            catch (Exception e)
                e.printStackTrace();
        public static double calculateHypotenuse(double a, double b)
            if ((a < 0.0) || (a < 0.0))
                throw new IllegalArgumentException("euclidian space triangle sides must be positive");
            if (a > b)
                double r = b/a;
                return a*Math.sqrt(1.0+r*r);
            else
                double r = a/b;
                return b*Math.sqrt(1.0+r*r);
        public static double calculateSide(double b, double c)
            if ((b < 0.0) || (c < 0.0))
                throw new IllegalArgumentException("euclidian space triangle sides must be positive");
            double r = b/c;
            if (r > 1.0)
                throw new IllegalArgumentException("hypotenuse is longer than either side");
            return c*Math.sqrt(1.0-r*r);
    }%

  • ICal and Exchange Errors

    Hi everyone.  I'm new to Mac but experienced with iPhone and iPad.  I have a brand new iMac running Lion with all the latest updates.  I have my corporate Exchange account configured just like I do with my iOS 5 iPhone and iPad.  On the Mac, Address Book and Mail work fine.  iCal however is having some issues. 
    I have two calendars on my Exchange account, my main one "Calendar" and another one "Team Calendar".  When I fire up iCal it just says "Updating..." for a long time.  Clicking on "Calendars" I see both of my calendars listed.  This is what happens on my iOS devices.  However, only events from "Team Calendar" show in iCal.  Nothing from "Calendar" shows.  Not a single event.  "Team Calendar" is very simple with basic events (not meetings with attendees).  My main "Calendar" has tons of repeating events, meetings with attendees, events that I've yet to respond to, etc.  I'm suspecting something is tripping up iCal.  Like I said, works fine on iPhone and Pad.
    I saw some posts in this community to delete ~/Library/Calendars/Calendar Cache    I did that but it didn't fix the problem.  And like I said, this is a brand new Lion install and this is the first time I've used iCal.  My company runs Exchange 2007 from what I understand.  I checked Console and found this:
    3/1/12 7:40:54.089 PM iCal: Could not find Meta Data for persistent Store
    3/1/12 7:43:02.150 PM iCal: Unexpected type EWSMeetingResponseMessageType for calendar Calendar in account Pega
    Any ideas?
    Thanks.
    Adam

    With 10.7 I could not see either of the mentioned cache files to delete them - which puzzled me (I did not have to unhide Libaries, and I could see other cache entries, so pretty sure it wasn't just hidden?!)
    I changed the port to 443 with SSL on and this allowed the Delegates tab to populate, and could even resolve a name of one of the exchange server users - so I know the connection is good. (And contacts and email are synching to the same work server). And like abfield, the iPhone and iPad sync the calendar perfectly both ways.
    My errors are
    25/06/14 12:38:04.233 PM iCal:  error = Error Domain=CalExchangeErrorDomain Code=-11 "iCal can’t refresh events in the calendar “Calendar”." UserInfo=0x7fcf4cb9af90 {CalFailedOperationKey=<CalExchangeSyncFolderItemsOperation: 0x7fcf3a978fd0>, NSLocalizedDescription=iCal can’t refresh events in the calendar “Calendar”., NSLocalizedFailureReason=The account "work" currently can’t be refreshed.}
    25/06/14 12:37:36.462 PM iCal: Unexpected type EWSMessageType for calendar Calendar in account work
    Apple phone support were apologetic but basically said that connections to Exchange Server were too hard as there were too many settings. Duh.
    Reading others' posts it appears that if a user has Outlook 2013, that there are now some incompatible Status options that can be set for appointments.
    This is similar to the issue in this thread but also an issue reported here https://discussions.apple.com/message/22514700
    I have copied the content here:
    Checked out the Console logs and it throws these three errors below.  There is something with the "LegacyFreeBusyStatus" that is causing the sync to fail.  Outlook 2013 has a new status of "working somewhere else".  I had used it for a few items.  I also found an item that had a Null status (like what it is pointing to in the error).  Removed that item and changed all the others to a valid stauts for previous versions of outlook.  ie. Free, Busy, etc.
    2/12/13 3:29:32.871 PM CalendarAgent[19447]: [com.apple.calendar.store.log.exchange.queue] [-[CalOperationQueue executeOperations] :: [<EWSCalendarItemType 0x7f9dfac9e9b0> setNilValueForKey]: could not set nil as the value for the key LegacyFreeBusyStatus.]
    This all suggests that one or more of my appointments has a status that iCal can't cope with.
    Is there a way to narrow down which these are and to blanket change them in Outlook 2013?

  • How do I check to see if a character is NOT contained in a String?

    I am trying to create a program which will read in user inputted text. If the text contains an email address, then the program will output it to screen. However, I also need to put some sort of fall back in there, in case an email address is not contained in the string.
    This is the part I am having problems with. If I enter an email address, it will output it to screen. Maybe someone can help me with a "no valid mail" message.
    I decided to use the '@' character as a reference point, since it is a unique character and should not be used in normal sentances. Since an email address is a continous block of text with no spaces in it,I created 2 substrings - one from '@' going backwards towards the previous space, and one from '@' going forward to the next space.
    First, I tried the following:
    //if(input.indexOf('@') == -1){
         // System.out.println("-no valid email-");
    The program ran and when I entered text containing an email adress, it displayed it on screen. If I didn't include one, it gave me an error: java.lang.StringIndexOutOfBoundsException: -1
    I'm guessing this is happening because if there is no '@' symbol in the user input, and so there is an error with the indexOf('@') statement. Any way to get around this?
    Then I tried the following, bearing in mind the variable length is defined as "input.length()".
    for(int i = 0; i <= length; i++){
         if(input.charAt(i) = '@'){
              break;
         if(i == length){
         System.out.println("-no valid email-");
    this gives me an "unexpected type" error with the if(input.charAt(i) = '@') statement.
    It says it has found a value, but requires a variable. Is the "i" in the FOR loop not a variable?
    Please can anybody help me. Any suggestions appreciated.

    Whenever I run the program, it is ok if I input an email address among the text. IT displays the email address to screen. However, if no email address is entered (ie. just a string of text), it displays the message "-no valid email". But it still gives me an error:
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
    ex out of range: -1
    at java.lang.String.charAt(String.java:558)
    at CA3a.main(CA3a.java:56)
    Here is my code in full:
    //I decided to use the '@' character as a reference point, since it is a unique character
    //and should not be used in normal sentances. Since an email address is a continous block
    //of text with no spaces in it,I created 2 substrings - one from '@' going
    //backwards towards the previous space, and one from '@' going forward to the next space.
    class CA3a{
       public static void main(String args[]){
    //variable declerations
         String input;
         int indexat, length;
         String part1 = "";
         String part2 = "";
    //prompt user for input
         System.out.println("This program will detect the 1st email address in a string of text.");
         System.out.println("Please enter a string of text");
    //take in input into a stringbuffer
         input = Keyboard.readString();
         StringBuffer buff = new StringBuffer(input);
    //assignments
         length = input.length();
         indexat = input.indexOf('@');
    //check to see if '@' character is present in string
         if(indexat < 0){
            System.out.println("-no valid email-");
    //check for substring part1
         for(int i = indexat; i >= 0; i--){
            if(i == 0){
              part1 = buff.substring(i, indexat);
              break;
            if(input.charAt(i-1) == ' '){
              part1 = buff.substring(i, indexat);
              break;
    //check for substring part2
         for(int i = indexat; i <= length; i++){
            if(i == length){
              part2 = buff.substring(indexat, i);
              break;
            if(input.charAt(i) == ' '){
              part2 = buff.substring(indexat, i);
              break;
    //output the 2 substring variables to screen.
    System.out.println(part1 + part2);
    }

  • Newbie needing help with code numbers and if-else

    I'm 100% new to any kind of programming and in my 4th week of an Intro to Java class. It's also an on-line class so my helpful resources are quite limited. I have spent close to 10 hours on my class project working out P-code and the java code itself, but I'm having some difficulty because the project seems to be much more advanced that the examples in the book that appear to only be partly directly related to this assignment. I have finally come to a point where I am unable to fix the mistakes that still show up. I'm not trying to get anyone to do my assignment for me, I'm only trying to get some help on what I'm missing. I want to learn, not cheat.
    Okay, I have an assignment that, in a nutshell, is a cash register. JOptionPane prompts the user to enter a product code that represents a product with a specific price. Another box asks for the quanity then displays the cost, tax and then the total amount plus tax, formatted in dollars and cents. It then repeats until a sentinel of "999" is entered, and then another box displays the total items sold for the day, amount of merchandise sold, tax charged, and the total amount acquired for the day. If a non-valid code is entered, I should prompt the user to try again.
    I have this down to 6 errors, with one of the errors being the same error 5 times. Here are the errors:
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:50: 'else' without 'if'
    else //if invalid code entered, output message
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:39: unexpected type
    required: variable
    found : value
    100 = 2.98;
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:41: unexpected type
    required: variable
    found : value
    200 = 4.50;
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:43: unexpected type
    required: variable
    found : value
    300 = 6.79;
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:45: unexpected type
    required: variable
    found : value
    400 = 5.29;
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:47: unexpected type
    required: variable
    found : value
    500 = 7.20;
    ^
    And finally, here is my code. Please be gentle with the criticism. I've really put a lot into it and would appreciate any help. Thanks in advance.
    import java.text.NumberFormat; // class for numeric formating from page 178
    import javax.swing.JOptionPane; // class for JOptionOPane
    public class Sales {
    //main method begins execution ofJava Application
    public static void main( String args[] )
    double quantity; // total of items purchased
    double tax; // total of tax
    double value; // total cost of all items before tax
    double total; // total of items including tax
    double totValue; // daily value counter
    double totTax; // daily tax counter
    double totTotal; // daily total amount collected (+tax) counter
    double item; //
    String input; // user-entered value
    String output; // output string
    String itemString; // item code entered by user
    String quantityString; // quantity entered by user
    // initialization phase
    quantity = 0; // initialize counter for items purchased
    // get first code from user
    itemString = JOptionPane.showInputDialog(
    "Enter item code:" );
    // convert itemString to double
    item = Double.parseDouble ( itemString );
    // loop until sentinel value read from user
    while ( item != 999 ) {
    // converting code to amount using if statements
    if ( item == 100 )
    100 = 2.98;
    if ( item == 200 )
    200 = 4.50;
    if ( item == 300 )
    300 = 6.79;
    if ( item == 400 )
    400 = 5.29;
    if ( item == 500 )
    500 = 7.20;
    else //if invalid code entered, output message
    JOptionPane.showMessageDialog( null, "Invalid code entered, please try again!",
    "Item Code", JOptionPane.INFORMATION_MESSAGE );
    } // end if
    } // end while
    // get quantity of item user
    itemString = JOptionPane.showInputDialog(
    "Enter quantity:" );
    // convert quantityString to int
    quantity = Double.parseDouble ( quantityString );
    // add quantity to quantity
    quantity = quantity + quantity;
    // calculation time! value
    value = quantity * item;
    // calc tax
    tax = value * .07;
    // calc total
    total = tax + value;
    //add totals to counter
    totValue = totValue + value;
    totTax = totTax + tax;
    totTotal = totTotal + total;
    // display the results of purchase
    JOptionPane.showMessageDialog( null, "Amount: " + value +
    "\nTax: " + tax + "\nTotal: " + total, "Sale", JOptionPane.INFORMATION_MESSAGE );
    // get next code from user
    itemString = JOptionPane.showInputDialog(
    "Enter item code:" );
    // If sentinel value reached
    if ( item == 999 ) {
    // display the daily totals
    JOptionPane.showMessageDialog( null, "Total amount of items sold today: " + quantity +
    "\nValue of ites sold today: " + totValue + "\nTotal tax collected today: " + totTax +
    "\nTotal Amount collected today: " + totTotal, "Totals", JOptionPane.INFORMATION_MESSAGE );
    System.exit( 0 ); // terminate application
    } // end sentinel
    } // end message
    } // end class Sales

    Here you go. I haven't tested this but it does compile. I've put in a 'few helpful hints'.
    import java.text.NumberFormat; // class for numeric formating from page 178
    import javax.swing.JOptionPane; // class for JOptionOPane
    public class TestTextFind {
    //main method begins execution ofJava Application
    public static void main( String args[] )
         double quantity; // total of items purchased
         double tax; // total of tax
         double value; // total cost of all items before tax
         double total; // total of items including tax
    //     double totValue; // daily value counter
    //     double totTax; // daily tax counter
    //     double totTotal; // daily total amount collected (+tax) counter
    // Always initialise your numbers unless you have a good reason not too
         double totValue = 0; // daily value counter
         double totTax = 0; // daily tax counter
         double totTotal = 0; // daily total amount collected (+tax) counter
         double itemCode;
         double item = 0;
         String itemCodeString; // item code entered by user
         String quantityString; // quantity entered by user
         // initialization phase
         quantity = 0; // initialize counter for items purchased
         // get first code from user
         itemCodeString = JOptionPane.showInputDialog("Enter item code:" );
         // convert itemString to double
         itemCode = Double.parseDouble ( itemCodeString );
         // loop until sentinel value read from user
         while ( itemCode != 999 ) {
    * 1. variable item mightnot have been initialised
    * You had item and itemCode the wrong way round.
    * You are supposed to be checking itemCode but setting the value
    * for item
              // converting code to amount using if statements
              if ( item == 100 )
              {itemCode = 2.98;}
              else if ( item == 200 )
              {itemCode = 4.50;}
              else if ( item == 300 )
              {itemCode = 6.79;}
              else if ( item == 400 )
              {itemCode = 5.29;}
              else if ( item == 500 )
              {itemCode = 7.20;}
              else {//if invalid code entered, output message
                   JOptionPane.showMessageDialog( null, "Invalid code entered, please try again!",
                   "Item Code", JOptionPane.INFORMATION_MESSAGE );
              } // end if
         } // end while
         // get quantity of item user
         itemCodeString = JOptionPane.showInputDialog("Enter quantity:" );
    * 2.
    * You have declared quantityString here but you never give it a value.
    * I think this should be itemCodeString shouldnt it???
    * Or should you change itemCodeString above to quantityString?
         // convert quantityString to int
    //     quantity = Double.parseDouble ( quantityString );  // old code
         quantity = Double.parseDouble ( itemCodeString );
         // add quantity to quantity
         quantity = quantity + quantity;
         // calculation time! value
         value = quantity * itemCode;
         // calc tax
         tax = value * .07;
         // calc total
         total = tax + value;
         //add totals to counter
    * 3. 4. and 5.
    * With the following you have not assigned the 'total' variables a value
    * so in effect you are saying eg. "total = null + 10". Thats why an error is
    * raised.  If you look at your declaration i have assigned them an initial
    * value of 0.
         totValue = totValue + value;
         totTax = totTax + tax;
         totTotal = totTotal + total;
         // display the results of purchase
         JOptionPane.showMessageDialog( null, "Amount: " + value +
         "\nTax: " + tax + "\nTotal: " + total, "Sale", JOptionPane.INFORMATION_MESSAGE );
         // get next code from user
         itemCodeString = JOptionPane.showInputDialog("Enter item code:" );
         // If sentinel value reached
         if ( itemCode == 999 ) {
              // display the daily totals
              JOptionPane.showMessageDialog( null, "Total amount of items sold today: " + quantity +
              "\nValue of ites sold today: " + totValue + "\nTotal tax collected today: " + totTax +
              "\nTotal Amount collected today: " + totTotal, "Totals",           JOptionPane.INFORMATION_MESSAGE );
              System.exit( 0 ); // terminate application
         } // end sentinel
    } // end message
    } // end class SalesRob.

  • Lack of information in JMS based notification message

    Hello,
    I have configured Watch for server log and related JMS Message Notification.
    However, I get only a text like "MapMessage[ID:<589306.1276727319522.0>]" in the JMS message text.
    How can I get the original log message by that ID or the JMS message's text can be extended with content WatchData attribute?
    Very appreciate any help or direction to place where I can read about it.
    Thanks,
    Yuriy

    I have figured out what is going on.
    WLDF notification is written to JMS in the format that WLS Administrative Console can not read it.
    However, when I export message to XML I can see all information that I need:
    <?xml version="1.0" encoding="UTF-8"?>
    <JMSMessageExport>
    <mes:WLJMSMessage xmlns:mes="http://www.bea.com/WLS/JMS/Message">
    <mes:Header>
    <mes:JMSMessageID>ID:&lt;589306.1276788240914.0></mes:JMSMessageID>
    <mes:JMSDeliveryMode>PERSISTENT</mes:JMSDeliveryMode>
    <mes:JMSExpiration>0</mes:JMSExpiration>
    <mes:JMSPriority>4</mes:JMSPriority>
    <mes:JMSRedelivered>false</mes:JMSRedelivered>
    <mes:JMSTimestamp>1276788240914</mes:JMSTimestamp>
    <mes:Properties>
    <mes:property name="JMSXDeliveryCount">
    <mes:Int>0</mes:Int>
    </mes:property>
    </mes:Properties>
    </mes:Header>
    <mes:Body>
    <mes:Map>
    <mes:name-value name="WatchAlarmResetPeriod">
    <mes:String>60000</mes:String>
    </mes:name-value>
    <mes:name-value name="WatchSeverityLevel">
    <mes:String>Notice</mes:String>
    </mes:name-value>
    <mes:name-value name="WatchRule">
    <mes:String>(SUBSYSTEM = 'ousgg.valves')</mes:String>
    </mes:name-value>
    <mes:name-value name="WatchDomainName">
    <mes:String>my_domain</mes:String>
    </mes:name-value>
    <mes:name-value name="WatchData">
    <mes:String>DATE = Jun 17, 2010 11:24:00 AM EDT SERVER = AdminServer MESSAGE = Invalid record ...</mes:String>
    </mes:name-value>
    <mes:name-value name="JMSNotificationName">
    <mes:String>OUSGG-FileValves-Fail-JMS</mes:String>
    </mes:name-value>
    <mes:name-value name="WatchAlarmType">
    <mes:String>None</mes:String>
    </mes:name-value>
    <mes:name-value name="WatchRuleType">
    <mes:String>Log</mes:String>
    </mes:name-value>
    <mes:name-value name="WatchName">
    <mes:String>OUSGG-FileValves</mes:String>
    </mes:name-value>
    <mes:name-value name="WatchServerName">
    <mes:String>AdminServer</mes:String>
    </mes:name-value>
    <mes:name-value name="WatchTime">
    <mes:String>Jun 17, 2010 11:24:00 AM EDT</mes:String>
    </mes:name-value>
    </mes:Map>
    </mes:Body>
    </mes:WLJMSMessage>
    </JMSMessageExport>
    Does anybody know what format the notification is written in?
    I'm trying to read it via JMS transport in OSB and it throwing errors no matter what "Request Message Type" I use:
    Unexpected type of message received: weblogic.jms.common.MapMessageImpl
    Thanks,
    Yuriy
    Edited by: user736637 on Jun 17, 2010 12:15 PM

  • My Exchange Calendar shows an "Exclamation Error" but there is no detail when I click it.

    OSX 10.8.2
    Added an Exchange Account through the wizard, Calendar worked for a number of months but stopped some time recently. 
    Perhaps when I did a password change. 
    Perhaps when I upgraded to Outlook 2013 on my work PC
    Updated my password, Mail works, Contacts work, but Calendar does not sync.  Small Exclamation Mark does not show error when clicked so I can't tell what the real problem it.  Tried to remove and re-add the account, same issue. 
    Checked out the Console logs and it throws these three errors below.  There is something with the "LegacyFreeBusyStatus" that is causing the sync to fail.  Outlook 2013 has a new status of "working somewhere else".  I had used it for a few items.  I also found an item that had a Null status (like what it is pointing to in the error).  Removed that item and changed all the others to a valid stauts for previous versions of outlook.  ie. Free, Busy, etc. 
    2/12/13 3:29:32.871 PM CalendarAgent[19447]: [com.apple.calendar.store.log.exchange.queue] [-[CalOperationQueue executeOperations] :: [<EWSCalendarItemType 0x7f9dfac9e9b0> setNilValueForKey]: could not set nil as the value for the key LegacyFreeBusyStatus.]
    2/12/13 3:29:32.872 PM CalendarAgent[19447]: [com.apple.calendar.store.log.exchange.queue] [error = Error Domain=CalExchangeErrorDomain Code=-1 "Calendar can’t refresh the account “Exchange”." UserInfo=0x999dfaaa0000 {NSLocalizedFailureReason=The account "Exchange" currently can’t be refreshed., CalFailedOperationKey=<CalExchangeSyncFolderItemsOperation: 0x7f9df521de50>, NSLocalizedDescription=Calendar can’t refresh the account “Exchange”.}]
    2/12/13 3:29:33.623 PM CalendarAgent[19447]: Unexpected type EWSMessageType for calendar Calendar in account Exchange

    Whaoo,
       Looks like all I needed to do was ask the question and I would answer it. 
    It is definitely the outlook 2013 calendar item that had the new status.  Even though I changed the item to a valid status, I needed to completely remove the item and add it back in with a valid legacy status from the start. 
    -The Steve

Maybe you are looking for

  • How can I get my itunes purchases to play on any mp3 player?

    I can't get my itunes purchases to play on my other mp3 players.  I don't want to download these programs people suggest on the internet. And really, I shouldn't have to. If I've already paid for the music, why can't I put it on the device I choose? 

  • Short Close a PO

    Dear Friends, I have a doubt. We make purchase orders and in most cases we get only 98% or 99% of items. We dont get balance 1% of items. But after taking GRN, the P.O hangs in there in the system. How can i close these type of P.O's? Regards umamahe

  • Folders last modified time stamp are not updated in Windows 7

    After changing any .cpp file in Visual Studio, the last modified time stamp for the file's folder IS NOT updated. What's happening ? However when I change a Word (.docx) file, the last modified time stamp for the file's folder IS updated ! How come ?

  • Update SharePoint list programatically twice a day with SQL 2008 r2

    How complicate is to sustain the update  SharePoint list programatically twice a day by using SQL job? the data need  to be update twice a day and it is going o be use to feed a share point form...where the user(S) will be choosing by lookup in infop

  • Inserting a splash screen

    I'm thinking of inserting a splash screen before the actual screen to be displayed is available( for wap). This is just like a screen will appear for a few seconds and then straight go to the next page or card. Thanks.