JTextField Double java.lang.Math

Hi,
I need to be able to input a double into a JTextField eg. 13.5
do some calculations on it and output its answer as a Double/String to a JLabel
Firstly I know that the following calculation works
double d, e, f g;
d = 10;
e = 14;
f = 13.5;
g = Math.pow(d, -(e - f));
System.out.println(g);
//Outputs 0.31622776601683794 Correct AnswerThe following works if I input of 13, but I get a NumberFormatException if I input 13.5.
double dInput, calc;
String str_calc;
JTextField input = new JTextField();
dInput = Double.parseDouble(input.getText());
calc = Math.pow(d, -(e - dInput));
str_calc = Double.toString(calc);
JLabel label = new JLabel();
label.setText(str_calc);Can anyone tell me where I am going wrong? How can I fix it?
Any help would be grately appreciated

Problem solved.
The issue I was having was not related to changing from printf to GUI, it was elsewhere in my code.
Thanks anyway

Similar Messages

  • How to use Java.lang.Math to calculate; Advice programming

    Hi, all!
    I am trying to teach myself Java, and am using the MindQ CDs to do it. I'm dreadfully stuck on this one exercise, and I could use some help figuring out how to properly call a Math method, store the variables, and print the results. I've programmed other methods successfully before; for some reason I just can't figure this one out. I've tried about fifty different configurations; maybe I can get some good advice here? Thanks!
    import java.io.*;
    import java.util.Random;
    import java.lang.Math;
    public class JavaCalcs {
        public static void main(String args[]) {
            System.out.println("Starting JavaComputations...");
            //main method variable declarations
            int z, y, x, w;
            int A = -12;
            int B = 2;
            z = A & B;
            y = A | B;
            x = A >> B;
            w = A >>> B;
            System.out.println(z + ";" + y + ";" + x + ";" + w + ";");
            Random kickassRNG = new Random();
            double rDOne = kickassRNG.nextDouble() * 90.0;
            double rDTwo = kickassRNG.nextDouble() * 90.0;
            System.out.println("rDOne= " + rDOne);
            System.out.println("rDTwo= " + rDTwo);
    //NOTE-EVERYTHING WORKS FINE UNTIL THIS POINT...
            if (rDOne > rDTwo)
            System.out.println("The larger of the 2 degs. is rDOne");
            //compute ceiling.
            double a=rDOne; //Store the value of rDOne.
            public static double ceil(double a);
            return a;
            System.out.println( "the ceiling of rDOne is " + a );
            //convert degree measurement to radians.     
            public static double toRadians(double b);
            double b = a;
            System.out.println("rDOne in radians is " + b );
            //compute tangent of that result.
            public static double tan(double c);
            double c = b;
            System.out.println("The tangent of rDOne is " + c );
            else
            System.out.println("The larger of the 2 degs. is rDTwo");
            //compute ceiling.
            double a=rDTwo; //Store the value of rDOne.
            public static double ceil(double a);
            return a;
            System.out.println( "the ceiling of rDTwo is " + a );
            //convert degree measurement to radians.     
            public static double toRadians(double b);
            double b = a;
            System.out.println("rDTwo in radians is " + b );
            //compute tangent of that result.
            public static double tan(double c);
            double c = b;
            System.out.println("The tangent of rDTwo is " + c );
        } //end main method.
    }

    VERY useful link..thxYou're welcome. Here are some more:
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.
    James Gosling's The Java Programming Language. Gosling is
    the creator of Java. It doesn't get much more authoratative than this.

  • Re: cannot be applied to (double,java.lang.String)

    It's telling you what the problem is -- you're trying to pass a String in where a double is required. Java is a strongly typed language, which means that you can't expect types to change automatically into other types as needed.
    You could, I suppose, parse the string, assuming that it holds a representation of a double. But if you look at the method in question, you'll see that it doesn't even use its second (double) argument.
    So you should ask yourself:
    1) should that method really take two arguments?
    2) what is the second argument for, if I did use it?
    3) what is the best type to represent the second argument?
    (hint: with a name like "customerType", then an enum seems likely)
    [add]
    Too slow again.
    Though I'll also add: please wrap any code you post in [code][/code] tags. It makes your code much easier to read.
    Message was edited by:
    paulcw

    >  String n ;
    n = JOptionPane.showInputDialog(null, "Enter Month No.:");
    pow(double,double) in java.lang.Math cannot be
    applied to (double,java.lang.String)Read the error diagnostic carefully: the compiler found a pow() method
    in the Math class, but it takes two doubles as its arguments. You,
    however, supplied a double and a String as the parameter types.
    The method found by the compiler cannot be applied to your parameters.
    hint: you have to convert that String to a double,
    kind regards,
    Jos

  • Using java.lang.Math.sin/tan/cos  to make an arc - very simple

    hi all,
    i'm trying to dynamically create an set of numbers in an arch pattern -- going left to right (counter clockwise) --- from 0 degrees to 180 degrees. -- similar to an upside down U
    Any ideas on how i would do a simple loop to put the number 1 in a semicircle.
    I'm guessing that it might look like this
    while(x < 181)
    g.drawString(Integer.toString(x) , java.lang.Math.sin(..), java.lang.Math.cos(...) )
    how may I ask does that work again ?
    s

    The coordinates of the unit circle are given by
    x = cos(t)
    y = sin(t)
    where 0 < t <= 2pi
    You'll want to scale and translate that... Here's a code fragment; play with it a little:for (double t=Math.PI/2; t < 2*Math.PI, t += .05) {
        double x = 100*Math.cos(t) + 100;
        double y = 100*Math.sin(t) + 100;
        g.drawLine((int) x, (int) y, (int) x, (int) y);
    }

  • How can I called java.lang.Math.sqr function from PL/SQL?

    JVM is loaded and I've queried the system table showing there are more than 9000 JAVA class objects.
    When I try something like:
    select java.lang.Math.sqrt(9) from dual;
    I get ORA-00904 (invalid column name) error. How can I invoke standard java.lang.Math methods in PL/SQL?
    tia

    You need to write a PL/SQL wrapper for the java call.
    Then you just call the PL/SQL function..
    -------PL/SQL wrapper
    FUNCTION GetFullName( code varchar2) RETURN NUMBER
    AS LANGUAGE JAVA
    NAME 'ResponseXml.GetPersonFullName(java.lang.String) return java.lang.String';
    Now you can do
    Select GetFullName( 'mycous' ) from dual;

  • Java.lang symbols not found when compiling package classes

    I have a set of classes that I have wrapped up in a package. The package name and
    directory structure follow the standard required for each. These classes contain many
    java.lang.Math functions and java.lang.Double calls.
    Am I correct in that the java.lang functions will be imported automatically? When I
    compile a class that is in the package, it looks for the Math.pow (for example)
    function in the package instead of java.lang. I have tried putting the following include
    at the top:
    include java.lang.*;and I still get the "cannot resolve symbol" error. Only when I use
    include java.lang.Math;
    include java.lang.Double;does it compile properly. Is this indicative of a problem with my classpath? It is
    currently set to look in whatever the current directory is, the directory with src.jar,
    and my dev directory that contains the package I am working on.
    Please advise! Thanks in advance!
    Rodman

    Thanks for the quick reply! I looked in the package directory and found the Math.java and
    Double.java files. I'm not sure why they were there. Thanks again!

  • I still cant get my head around this:  java.lang.NullPointerException

    heres my disgusting amount of code and its error report. please help. its basically the board for a twixt game. if you dont know what that is its not important because the error has nothing to do with the rules of the game.
    Exception in thread "main" java.lang.NullPointerException
         at Board.pcomp(Board.java:81)
         at Board.addremovebridge(Board.java:34)
         at Twixt.main(Twixt.java:21)
    Thanks again for reading this far.
    public class Twixt {
         public static void main(String[] args) {
              Board game = new Board();
              point p = new point();
              p.x = 4;
              p.y = 4;
              p.p = 1;
              point f = new point();
              f.x = 5;
              f.y = 6;
              p.p = 1;
              String s = new String();
              s = game.placetower(p);
              s = game.placetower(p);
              System.out.println(s);
              s = game.placetower(f);
              System.out.println(s);
              s = game.addremovebridge(p,f);
              System.out.println(s);
              s = game.addremovebridge(p,f);
              System.out.println(s);
    public class point {
         int x = 0;
         int y = 0;
         int p = 0;
    import java.lang.Math;
    public class Board{
         public int[][] board1 = new int[26][26];
         public point[][][] board2 = new point[26][26][6];
         private int board3d;
         private int board3e;
         /*Board() {
              for(int x = 0; x<=25; x++){
                   for(int i = 0; i<=25; i++){
                        for(int j = 0; j<=6;j++){
                             pmakezero(board2[x][j]);
         public String placetower(point d){
              if (board1[d.x][d.y] == 0){
                   board1[d.x][d.y] = d.p;
                   return ("Tower placed at "+d.x+", "+d.y+".");
              }else{
                   return ("That space is already taken.");
         public String addremovebridge(point d, point e){
              if(checkplayer(d,e)){
                   boolean removebridge = false;
                   for(int i = 0; i<=5;i++){
                        if(pcomp(board2[d.x][d.y][i], e)){
                             pmakezero(board2[d.x][d.y][i]);
                             removebridge = true;
                        if(pcomp(board2[e.x][e.y][i], d)){
                             pmakezero(board2[e.x][e.y][i]);
                             removebridge = true;
                   if(distance(d,e)&&!intersect(d,e)&&!removebridge&&!full(d,e)){
                        board2[d.x][d.y][board3d] = e;
                        board2[e.x][e.y][board3e] = d;
                        return ("Bridge placed between "+d.x+", "+d.y+" and "+e.x+", "+e.y+".");
                   }else{
                        return ("That is not a valid bridge placement.");
              }else{
                   return ("That tower does not belong to you.");
         private boolean distance(point d, point e){
              double g;
              int f;
              int i;
              f = d.x - e.x;
              i = d.y - e.y;
              f = f*f;
              i = i*i;
              f = f+i;
              g = f;
              if (g>0){
                   g = g * -1;
              g = Math.sqrt(g);
              if(g == Math.sqrt(5)){
                   return true;
              }else{
                   return false;
         private boolean pcomp(point d, point e){
              if(d.x == e.x && d.y == e.y){
                   return true;
              }else{
                   return false;
         private void pmakezero(point d){
              d.x = 0;
              d.y = 0;
              d.p = 0;
         private boolean checkplayer(point d, point e){
              if(board1[d.x][d.y] == d.p && board1[e.x][e.y]==e.p){
                   return true;
              }else{
                   return false;
         private boolean full(point d, point e){
              point x;
              int y;
              int z;
              boolean full = true;
              for(int i=0; i<=5; i++){
                   x = board2[d.x][d.y][i];
                   y = x.x;
                   z = x.y;
                   if(y == 0 && z == 0){
                        board3d = i;
                        i = 3;
                        full = false;
              for(int i=0; i<=3; i++){
                   x = board2[e.x][e.y][i];
                   y = x.x;
                   z = x.y;
                   if(y == 0 && z == 0){
                        board3e = i;
                        i = 3;
                        full = false;
              return full;
         private boolean intersect(point d, point e){
              boolean inter = false;
              int f;
              int h;
              f = d.x - e.x;
              h = d.y - e.y;
              if(f == 2 && h == 1){
                   if(board1[e.x + 1][e.y]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[e.x + 2][e.y + 2][w]==e){
                                  inter = true;
                             }else if(board2[e.x][e.y + 2][w]==e){
                                  inter = true;
                   }else if(board1[d.x - 1][d.y]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[d.x - 2][d.y - 2][w]==d){
                                  inter = true;
                             }else if(board2[d.x][d.y - 2][w]==d){
                                  inter = true;
                   }else if(board1[e.x + 2][e.y]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[e.x + 1][e.y + 2][w]==e){
                                  inter = true;
                   }else if(board1[d.x - 2][d.y]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[d.x - 1][d.y - 2][w]==d){
                                  inter = true;
              }else if(f == -2 && h == -1){
                   if(board1[e.x - 1][e.y]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[e.x - 2][e.y - 2][w]==e){
                                  inter = true;
                             }else if(board2[e.x][e.y - 2][w]==e){
                                  inter = true;
                   }else if(board1[d.x + 1][d.y]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[d.x + 2][d.y + 2][w]==d){
                                  inter = true;
                             }else if(board2[d.x][d.y + 2][w]==d){
                                  inter = true;
                   }else if(board1[e.x - 2][e.y]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[e.x - 1][e.y - 2][w]==e){
                                  inter = true;
                   }else if(board1[d.x + 2][d.y]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[d.x + 1][d.y + 2][w]==d){
                                  inter = true;
              }else if(f == 1 && h == 2){
                   if(board1[e.x][e.y + 1]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[e.x + 2][e.y + 2][w]==e){
                                  inter = true;
                             }else if(board2[e.x + 2][e.y][w]==e){
                                  inter = true;
                   }else if(board1[d.x][d.y - 1]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[d.x - 2][d.y - 2][w]==d){
                                  inter = true;
                             }else if(board2[d.x - 2][d.y][w]==d){
                                  inter = true;
                   }else if(board1[e.x][e.y + 2]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[e.x + 2][e.y + 1][w]==e){
                                  inter = true;
                   }else if(board1[d.x][d.y - 2]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[d.x - 2][d.y - 1][w]==d){
                                  inter = true;
              }else if(f == -1 && h == -2){
                   if(board1[e.x][e.y - 1]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[e.x - 2][e.y - 2][w]==e){
                                  inter = true;
                             }else if(board2[e.x - 2][e.y][w]==e){
                                  inter = true;
                   }else if(board1[d.x][d.y + 1]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[d.x + 2][d.y + 2][w]==d){
                                  inter = true;
                             }else if(board2[d.x + 2][d.y][w]==d){
                                  inter = true;
                   }else if(board1[e.x][e.y - 2]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[e.x - 2][e.y - 1][w]==e){
                                  inter = true;
                   }else if(board1[d.x][d.y + 2]!=0){
                        for(int w=0;w<=5;w++){
                             if(board2[d.x + 2][d.y + 1][w]==d){
                                  inter = true;
              return inter;
    Thank you.

    Exception in thread "main"
    java.lang.NullPointerException
         at Board.pcomp(Board.java:81)
         at Board.addremovebridge(Board.java:34)
         at Twixt.main(Twixt.java:21)
    So the null pointer occurs on the 81st line in the Board.java source code file. I'm not sure, but I expect this is line 81.if(d.x == e.x && d.y == e.y){Here's one way to troubleshoot null pointer problems. First find the line causing the error. Then, use System.out.println() statements to display the values of all the reference variables in that line, one variable at a time. So if I guessed correctly on line 81, you would put these statements just before line 81System.out.println("d " + d);
    System.out.println("e " + e);Because d and e are the only reference variables in that line. When you run the code after putting these lines in, one or both of these will display "null" and that will tell you which variable to trace. You will need to trace backward through your code a find out why d or e or both are null.
    (hint: A statement like Object[] objects = new Object[10];" creates an Object array with 10 elements, each of which is null. You have to use "objects[1] = new Object();" to create an element in the array which is an Object.)

  • Error:java.lang.Double:method parseDouble(Ljava/lang/String;)D not found.

    Hi ,
    oracle apps version : 11.5.10.2 and database version 11.2.0.2.
    OS version Solaris Sparc 64 Bit.
    We were performing a cloing activity on a new server and now while opening forms we are getting the following error :
    error:java.lang.Double:method parseDouble(Ljava/lang/String;)D not found.Please suggest what has to be done.
    Regards
    Kk

    Hi ,
    D:\Documents and Settings\800045916>java -version
    java version "1.6.0_29"
    Java(TM) SE Runtime Environment (build 1.6.0_29-b11)
    Java HotSpot(TM) Client VM (build 20.4-b02, mixed mode, sharing)We have been struggling with the Solaris server for this. Is something needed from there also or just need to have the latest JRE in the windows client machine.
    Regards
    Kk

  • Java.lang.ClassCastException:java.lang.Double

    I am trying to troubleshoot this error but I am not sure what to look for, where to find it, and what to change it to.
    Error: 500
    Location:/jserv/Purchase/Frame6_CreditCardPayment_Step3.jsp Internal Servlet Error:
    javax.servlet.ServletException: java.lang.Double
    Root cause:
    java.lang.ClassCastException: java.lang.Double
    at Purchase._0002fPurchase_0002fFrame_00036_0005fCreditCardPayment_0005fStep_00033_0002ejspFrame6_0005fCreditCardPayment_0005fStep3_jsp_1._jspService(_0002fPurchase_0002fFrame_00036_0005fCreditCardPayment_0005fStep_00033_0002ejspFrame6_0005fCreditCardPay
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java, Compiled Code)

    Hi Dr,
    I followed your suggestion, but there was no casting to double in the JSP code, so I looked at the database and found 3 columns inadvertently created as "double default null" when the MSAccess mdb was exported to MySQL.
    I modified the database to make those columns text, and now the compiler does not throw the error.
    I'm still unclear why the error was thrown.

  • Excel Export - java.lang.NoSuchMethodError: java.math.BigDecimal

    Hi All,
    I am working on the Excel Export example.
    When I am running the application I am getting the foll. error
    java.lang.NoSuchMethodError: java.math.BigDecimal.<init>(I)V
        at com.sap.tut.wd.tutwd_table.tablecomp.TableComp.getProductsTOTAL_PER_ARTICLE(TableComp.java:227)
        at com.sap.tut.wd.tutwd_table.tablecomp.wdp.InternalTableComp.getProductsTOTAL_PER_ARTICLE(InternalTableComp.java:176)
        at com.sap.tut.wd.tutwd_table.tablecomp.wdp.IPublicTableComp$IProductsElement.wdGetObject(IPublicTableComp.java:437)
        at com.sap.tc.webdynpro.progmodel.context.MappedNodeElement.wdGetObject(MappedNodeElement.java:351)
        at com.sap.tc.webdynpro.progmodel.context.AttributePointer.getObject(AttributePointer.java:158)
    Please provide some inputs as how to resolve this problem.
    Regards
    Nikhil Bansal

    Hi Valery,
    I am unable to install anything on my machine due to certain issues. So I shall not be able to implement the solution which you have suggested.
    I have a diff. approach to solve this problem. My intention is to just export some data to excel.
    So I have created a Component (ParentComp) in my application.The view in this comp contains a button Export to Excel 2003. There is an Action associated with this button.
    I have another component ChildComp.
    What I want to do is just call the Interface Controller of ChildComp from the Action ExportToExcel2003.
    I am not passing any data to the ChildComp.Instead I shall be hardcoding some table data in ChildComp itself.
    Please let me know if you are aware of some solution.
    Regards
    Nikhil Bansal

  • Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

    I am getting error:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    Pls tell me where I am wrong:
    import javax.swing.JOptionPane;
    import java.io.File;
    import java.io.*;
    import java.io.IOException;
    import java.util.*;
    class Test {
    String lname, fname, finalLetterGrade, LetterGrade, sub1,sub2,sub3,sub4,sub5,sub;
    int testone = 0;
         int a=0,b,c,d,e, count= 0, abs = 0,j;
    int testtwo = 0;
    int testthree = 0;
    int testfour = 0;
    int testfive = 0;
    int finalExamGrade = 0;
      int i=0;
    int participation = 0;
    int lowScore = 0;
    int abs1,abs2,abs3,abs4,abs5;
    String s="absent";
    Character ch;
    String []name;   
    int []Mark;
    double finalNumericGrade = 0;
    public Test() {
    public void inputGrades()
    int input, row, col;
         Scanner scan = new Scanner(System.in);
         System.out.println("Enter the length of the square matrix: ");
         col = scan.nextInt(); 
    name = new String[col];
            Mark = new int[col];
            for(i = 0; i < col ; i++)
              name=JOptionPane.showInputDialog("Enter Student Name"+(i+1)+" Name: ");
    System.out.println(name[i]);
    for(j=0; j < col;j++)
    Mark[j]=Integer.parseInt(JOptionPane.showInputDialog("Marks "+(j+1)+" Mark: "));
    System.out.println(Mark[j]);
              System.out.println("Average-->"+getAverage());
              System.out.println("Student'-->"+toString());
    public double getAverage()
         if( Mark[0]==0 || Mark[1]==0 || Mark[2]==0 || Mark[3]==0 || Mark[4]==0)
    finalNumericGrade=((((float)(Mark[0])) + ((float)(Mark[1])) + ((float)(Mark[2])) + ((float)(Mark[3])) + ((float)(Mark[4])))/4);
    else
    finalNumericGrade=((((float)(Mark[0])) + ((float)(Mark[1])) + ((float)(Mark[2])) + ((float)(Mark[3])) + ((float)(Mark[4])))/5);;
    return finalNumericGrade;
    private String letterGrade(){
         //System.out.println(" +++ finalNumericGrade " + finalNumericGrade );
    if ((finalNumericGrade >= 3.50) & (finalNumericGrade <= 4))
    finalLetterGrade = "A";
    else
    if ((finalNumericGrade >= 2.50) & (finalNumericGrade < 3.50))
    finalLetterGrade = "B";
    else
    if ((finalNumericGrade >= 2) & (finalNumericGrade < 2.50))
    finalLetterGrade = "C";
    else
    if ((finalNumericGrade >= 1) & (finalNumericGrade < 2))
    finalLetterGrade = "D";
    else
    if (finalNumericGrade == 0)
    finalLetterGrade = "X";
    else finalLetterGrade ="Z";
    return finalLetterGrade;
    public int getAbsentee()
         if(testone == 0)
              abs1=1;
         if(testtwo == 0)
              abs2=1;
         if(testthree == 0)
              abs3=1;
         if(testfour == 0)
              abs4=1;
         if(testfive == 0)
              abs5=1;
         return abs=abs1+abs2+abs3+abs4+abs5;
    public String AbsentSub()
         if((testone < testtwo) & (testone < testthree) & (testone < testfour) & (testone < testfive))          
              sub=sub1;
         if((testtwo < testone) & (testtwo < testthree) & (testtwo < testfour) & (testtwo < testfive))
              sub=sub2;
         if((testthree < testone) & (testthree < testtwo) & (testthree < testfour) & (testthree < testfive))
              sub=sub3;
         if((testfour < testone) & (testfour < testthree) & (testfour < testtwo) & (testfour < testfive))
              sub=sub4;
         if((testfive < testone) & (testfive < testtwo) & (testfive < testthree) & (testfive < testfour))
              sub=sub5;
         return sub;
    public int getLowScore(){
    //Determine and return the lowest score
    lowScore = testone;
    if (testtwo < lowScore) lowScore = testtwo;
    if (testthree < lowScore) lowScore = testthree;
         if (testfour < lowScore) lowScore = testfour;
         if (testfive < lowScore) lowScore = testfive;
    return lowScore;
    public String toString() {
    String studentStringValue="\n\nStudent " sub1 " "+sub2+" "+sub3+" "+sub4+" "+sub5+ " Lowest Final Marks \n\n";
    studentStringValue+= name[i]+"\t";
    if(Mark[0]==0)
         studentStringValue+="" s "\t";
    else
         a=Mark[0];
         ch = new Character(((char) ((69-a))));
    studentStringValue+= Mark[0]+" "+ch+ "\t";
    if(Mark[1]==0)
         studentStringValue+="" s "\t";
    else
         b=Mark[1];
    ch = new Character(((char) ((69-b))));
    studentStringValue+= Mark[1]+" "+ch+ "\t";
    if(Mark[2]==0)
         studentStringValue+="" s "\t";
    else
         c=Mark[2];
    ch = new Character(((char) ((69-c))));
    studentStringValue+=Mark[2] +" "+ch+ "\t";
    if(Mark[3]==0)
         studentStringValue+="" s "\t";
    else
         d=Mark[3];
    ch = new Character(((char) ((69-d))));
    studentStringValue+= Mark[3] +" "+ch+ "\t";
    if(Mark[4]==0)
              studentStringValue+="" s "\t";
    else
         e=Mark[4];
    ch = new Character(((char) ((69-e))));
    studentStringValue+=Mark[4] +" "+ch+ "\t";
    try {
    BufferedWriter out = new BufferedWriter(new FileWriter(".//Marks3.txt", true));
    out.write(studentStringValue);
    out.close();
    } catch (IOException e) {
    //studentStringValue+=" " + abs + " ";
    //studentStringValue+=" " sub"\t";
    studentStringValue+=" " + finalNumericGrade + " \n\n";
    //studentStringValue+=" Final Letter Grade is: " + finalLetterGrade +"\n";
    return studentStringValue;
    }// toString
    public void printName(){
    System.out.print(" "+lname);
    System.out.print(" "+fname);
    public static void main(String[] args)
         Test s = new Test();
         s.inputGrades();
         System.out.println("Average-->" +s.getAverage());
         //System.out.println("Average-->" +s.setAverage());
         //System.out.println("Absent students in each Test-->" + s.getAbsentee());
         // s.getLowScore();
         //System.out.println("Final Letter Grade --> " + s.letterGrade());
         // s.AbsentSub();
         System.out.println(""+ s.toString());

    hi,
    I am getting error on line 232 n 339
    My error is :
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at Test.toString(Test.java:232)
    at Test.main(Test.java:339)
    my code is :
    import javax.swing.JOptionPane;
    import java.io.File;
    import java.io.*;
    import java.io.IOException;
    import java.util.*;
    class Test {
    String lname, fname, finalLetterGrade, LetterGrade, sub1,sub2,sub3,sub4,sub5,sub;
    int testone = 0;
         int a=0,b,c,d,e, count= 0, abs = 0,j,ab,abm=0,abj=0,abn=0,abd=0;
    int testtwo = 0;
    int testthree = 0;
    int testfour = 0;
    int testfive = 0;
    int finalExamGrade = 0;
      int i=0;
    int participation = 0;
    int lowScore = 0;
    int abs1,abs2,abs3,abs4,abs5;
    String s="absent";
    Character ch;
    String []name;
    String[] subj;
    int []Mark;
    double finalNumericGrade = 0;
    public Test() {
    public void inputGrades()
    int input, row, col;
         Scanner scan = new Scanner(System.in);
         System.out.println("Enter the length of Array: ");
         col = scan.nextInt(); 
    name = new String[col];
    subj = new String[5];
            Mark = new int[5];
            for(i = 0; i < col ; i++)
              name=JOptionPane.showInputDialog("Enter Student Name"+(i+1)+" Name: ");
    System.out.println(name[i]);
    for(j=0; j < 5;j++)
                        subj[j]=JOptionPane.showInputDialog("Enter Subject"+(j+1)+" Name: ");
    Mark[j]=Integer.parseInt(JOptionPane.showInputDialog("Marks "+(j+1)+" Mark: "));
                        System.out.println(subj[j]);
    System.out.println(Mark[j]);
                        System.out.println("Student'-->"+toString());
              System.out.println("Average Stu-->"+getAverage());
              getLowScore();
    public double getAverage()
         if( Mark[0]==0 || Mark[1]==0 || Mark[2]==0 || Mark[3]==0 || Mark[4]==0)
    finalNumericGrade=((((float)(Mark[0])) + ((float)(Mark[1])) + ((float)(Mark[2])) + ((float)(Mark[3])) + ((float)(Mark[4])))/4);
    else
    finalNumericGrade=((((float)(Mark[0])) + ((float)(Mark[1])) + ((float)(Mark[2])) + ((float)(Mark[3])) + ((float)(Mark[4])))/5);;
    return finalNumericGrade;
    private String letterGrade(){
         //System.out.println(" +++ finalNumericGrade " + finalNumericGrade );
    if ((finalNumericGrade >= 3.50) & (finalNumericGrade <= 4))
    finalLetterGrade = "A";
    else
    if ((finalNumericGrade >= 2.50) & (finalNumericGrade < 3.50))
    finalLetterGrade = "B";
    else
    if ((finalNumericGrade >= 2) & (finalNumericGrade < 2.50))
    finalLetterGrade = "C";
    else
    if ((finalNumericGrade >= 1) & (finalNumericGrade < 2))
    finalLetterGrade = "D";
    else
    if (finalNumericGrade == 0)
    finalLetterGrade = "X";
    else finalLetterGrade ="Z";
    return finalLetterGrade;
    /*****Java Absentee***/
    public int getAbsenteeJava()
         if((Mark[0]==0))     
              abj=abj+1;
         else
              abj=0;
              return abj;
    public void setAbsenteeJava()
              System.out.println("Absent in Java-->"+abj);
    /***Maths Absentee****/
         public int getAbsenteeMaths()
         if(Mark[1]==0)
              abm=abm+1;
         else
              abm=0;
              return abm;
         public void setAbsenteeMaths()
              System.out.println("Absent in Maths-->"+abm);
    /****Stats Absentee---*/
    public int getAbsenteeStat()
    sub3="Stats";
         if(Mark[2]==0)          
              abs=abs+1;
         else
              abs=0;
              return abs;
         public void setAbsenteeStat()
    System.out.println("Absent in Stats-->"+abs);
    /*****NEt Absentee****/
         public int getAbsenteeNet()
    sub4="Network";
         if(Mark[3]==0)          
              abn=abn+1;
         else
              abn=0;
              return abn;
    public void setAbsenteeNet()
    System.out.println("Absent in Network-->"+abn);
    /*****Database Absentee****/
         public int getAbsenteeData()
    sub5="Database";
         if(Mark[4]==0)          
              abd=abd+1;
         else
              abd=0;
              return abd;
         public void setAbsenteeData()
    System.out.println("Absent in Database-->"+abd);
    public String getLowScore(){
    //Determine and return the lowest score
    if(((subj[0].equals(sub1)) || (Mark[0]==0)))     
              sub="Java";
         else if(((subj[1].equals(sub2)) || (Mark[1]==0)))
              sub="Maths";
         else if(((subj[2].equals(sub3)) & (Mark[2]==0)))
              sub="Stats";
         else if(((subj[3].equals(sub4)) || (Mark[3]==0)))
              sub="Network";
         else if(((subj[4].equals(sub5)) || (Mark[4]==0)))
              sub="Database";
         return sub;
    public String toString() {
    String studentStringValue="\n\nStudent " subj[0] " "+subj[1]+" "+subj[2]+" "+subj[3]+" "+subj[4]+ " Lowest Final Marks \n\n";
         String nm = name[i];
    studentStringValue+= nm+"\t";
    if(Mark[0]==0)
         studentStringValue+="" s "\t";
    else
         {// 232: Line: getting ERROR here
         a=Mark[0];
         ch = new Character(((char) ((69-a))));
    studentStringValue+= Mark[0]+" "+ch+ "\t";
    if(Mark[1]==0)
         studentStringValue+="" s "\t";
    else
         b=Mark[1];
    ch = new Character(((char) ((69-b))));
    studentStringValue+= Mark[1]+" "+ch+ "\t";
    if(Mark[2]==0)
         studentStringValue+="" s "\t";
    else
         c=Mark[2];
    ch = new Character(((char) ((69-c))));
    studentStringValue+=Mark[2] +" "+ch+ "\t";
    if(Mark[3]==0)
         studentStringValue+="" s "\t";
    else
         d=Mark[3];
    ch = new Character(((char) ((69-d))));
    studentStringValue+= Mark[3] +" "+ch+ "\t";
    if(Mark[4]==0)
              studentStringValue+="" s "\t";
    else
         e=Mark[4];
    ch = new Character(((char) ((69-e))));
    studentStringValue+=Mark[4] +" "+ch+ "\t";
    //studentStringValue+=" " + abs + " ";
    studentStringValue+=" " sub"\t";
    studentStringValue+=" " + finalNumericGrade + " \n\n";
    //studentStringValue+=" Final Letter Grade is: " + finalLetterGrade +"\n";
    try {
    BufferedWriter out = new BufferedWriter(new FileWriter(".//Marks3.txt", true));
    out.write(studentStringValue);
    out.close();
    } catch (IOException e) {
    return studentStringValue;
    }// toString
    public void printName(){
    System.out.print(" "+lname);
    System.out.print(" "+fname);
    public static void main(String[] args)
         Test s = new Test();
         s.inputGrades();
         System.out.println("Average-->" +s.getAverage());
         //System.out.println("Average-->" +s.setAverage());
         s.getAbsenteeJava();
         s.setAbsenteeJava();
         s.getAbsenteeMaths();          
    s.setAbsenteeMaths();
         s.getAbsenteeStat();
         s.setAbsenteeStat();
         s.getAbsenteeNet();     
         s.setAbsenteeNet();
         s.getAbsenteeData();          
    s.setAbsenteeData();
         s.getLowScore();
         //System.out.println("Final Letter Grade --> " + s.letterGrade());
         System.out.println(""+ s.toString());

  • Java.lang.StringIndexOutOfBoundsException

    Hello, why does the following program generate a java.lang.StringIndexOutOfBoundsException error when a file is opened:
    Cryptogram.java (main program)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    public class Cryptogram extends JFrame
      private static final Enigma codeMachine = new Enigma();
      private static final String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      private static final String frequentLetters = "JQXZKBVWFUYMPGCLSDHROANITE";
      private static final int numLetters = letters.length();
      private JFrame thisWindow;
      private JMenuItem openItem, saveItem, exitItem;
      private String pathName = "";
      private JTextField subFields[] = new JTextField[numLetters];
      private JLabel hintLabels[] = new JLabel[numLetters];
      private JTextArea textAreaIn, textAreaOut;
      public Cryptogram()
        super("Cryptogram Solver");
        thisWindow = this;
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic('F');
        FileAction fileAction = new FileAction();
        openItem = new JMenuItem("Open...");
        openItem.setMnemonic('O');
        openItem.addActionListener(fileAction);
        saveItem = new JMenuItem("Save...");
        saveItem.setMnemonic('S');
        saveItem.addActionListener(fileAction);
        saveItem.setEnabled(false);
        exitItem = new JMenuItem("Exit");
        exitItem.setMnemonic('x');
        exitItem.addActionListener(fileAction);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);
        JMenu decodeMenu = new JMenu("Decode");
        decodeMenu.setMnemonic('D');
        DecodeAction decodeAction = new DecodeAction();
        JMenuItem decodeItem = new JMenuItem("Decode");
        decodeItem.setMnemonic('D');
        decodeItem.addActionListener(decodeAction);
        JMenuItem clearItem = new JMenuItem("Clear");
        clearItem.setMnemonic('C');
        clearItem.addActionListener(decodeAction);
        JMenuItem encodeItem = new JMenuItem("Encode");
        encodeItem.setMnemonic('R');
        encodeItem.addActionListener(decodeAction);
        decodeMenu.add(decodeItem);
        decodeMenu.add(clearItem);
        decodeMenu.add(encodeItem);
        menuBar.add(fileMenu);
        menuBar.add(decodeMenu);
        setJMenuBar(menuBar);
        JPanel p1 = new JPanel();
        p1.setPreferredSize(new Dimension(100, 81));
        p1.setLayout(new GridLayout(3, 1, 3, 3));
        p1.add(new JLabel("Code letter:", JLabel.RIGHT));
        p1.add(new JLabel("Stands for:", JLabel.RIGHT));
        p1.add(new JLabel("Computer hints:", JLabel.RIGHT));
        int k;
        JPanel p2 = new JPanel();
        p2.setPreferredSize(new Dimension(569, 81));
        p2.setLayout(new GridLayout(3, 26, 3, 3));
        for (k = 0; k < numLetters; k++)
          p2.add(new JLabel(letters.substring(k, k+1), JLabel.CENTER));
        for (k = 0; k < numLetters; k++)
          JTextField tf = new JTextField();
          tf.setBackground(Color.yellow);
          tf.setHorizontalAlignment(JTextField.CENTER);
          p2.add(tf);
          subFields[k] = tf;
        clearSubs();
        for (k = 0; k < numLetters; k++)
          hintLabels[k] = new JLabel(" ", JLabel.CENTER);
          p2.add(hintLabels[k]);
        JPanel p3 = new JPanel();
        p3.setPreferredSize(new Dimension(80, 81));
        p3.setLayout(new GridLayout(3, 1, 3, 3));
        p3.add(new JPanel());   // filler
        JButton refresh = new JButton("Refresh");
        refresh.addActionListener(decodeAction);
        p3.add(refresh);
        Box b1 = Box.createHorizontalBox();
        b1.add(p1);
        b1.add(Box.createHorizontalStrut(10));
        b1.add(p2);
        b1.add(Box.createHorizontalStrut(10));
        b1.add(p3);
        JPanel p123 = new JPanel();
        p123.add(b1);
        Font font = new Font("Monospaced", Font.PLAIN, 16);
        textAreaIn = new JTextArea(20, 30);
        textAreaIn.setFont(font);
        textAreaIn.setLineWrap(true);
        textAreaIn.setWrapStyleWord(true);
        JScrollPane areaScrollPaneIn = new JScrollPane(textAreaIn);
        areaScrollPaneIn.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        textAreaOut = new JTextArea(20, 30);
        textAreaOut.setFont(font);
        textAreaOut.setLineWrap(true);
        textAreaOut.setWrapStyleWord(true);
        textAreaOut.setEditable(false);
        JScrollPane areaScrollPaneOut = new JScrollPane(textAreaOut);
        areaScrollPaneOut.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        Box b2 = Box.createHorizontalBox();
        b2.add(areaScrollPaneIn);
        b2.add(Box.createHorizontalStrut(10));
        b2.add(areaScrollPaneOut);
        Container c = getContentPane();
        c.add(p123, BorderLayout.NORTH);
        c.add(b2, BorderLayout.CENTER);
      private void clearSubs()
        StringBuffer subs = new StringBuffer(numLetters);
        for (int k = 0; k < numLetters; k++)
          subFields[k].setText("-");
          subs.append("-");
        codeMachine.setSubstitutions(subs.toString());
      private void normalSubs()
        StringBuffer subs = new StringBuffer(numLetters);
        for (int k = 0; k < numLetters; k++)
          JTextField tf = subFields[k];
          String s = tf.getText();
          if (s.length() < 1)
            s = "-";
          else
            s = s.substring(0,1).toUpperCase();
            if (!Character.isLetter(s.charAt(0)))
              s = "-";
          tf.setText(s);
          subs.append(s);
        codeMachine.setSubstitutions(subs.toString());
      private void randomSubs()
        StringBuffer subs = new StringBuffer(letters);
        int k, n;
        char ch1, ch2;
        for (n = numLetters; n > 1; n--)
          k = (int)(n * Math.random());
          ch1 = subs.charAt(k);
          ch2 = subs.charAt(n-1);
          subs.setCharAt(k, ch2);
          subs.setCharAt(n-1, ch1);
        String s = subs.toString();
        for (k = 0; k < numLetters; k++)
          subFields[k].setText(s.substring(k, k + 1));
        codeMachine.setSubstitutions(s);
      public void setHints(String text)
        int k;
        codeMachine.countLetters(text);
        for (k = 0; k < numLetters; k++)
          int pos = codeMachine.getFrequencyPos(k);
          hintLabels[k].setText(frequentLetters.substring(pos, pos+1));
      /***************          Action Listeners         ****************/
      private class FileAction implements ActionListener
        public void actionPerformed(ActionEvent e)
          int result;
          String text;
          JMenuItem m = (JMenuItem)e.getSource();
          if (m == openItem)
            JFileChooser fileChooser = new JFileChooser(pathName);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            result = fileChooser.showOpenDialog(thisWindow);
            if (result == JFileChooser.CANCEL_OPTION)
              return;
            File file = fileChooser.getSelectedFile();
            if (file != null)
              pathName = file.getAbsolutePath();
            EasyReader fileIn = new EasyReader(pathName);
            if (fileIn.bad())
              JOptionPane.showMessageDialog(thisWindow, "Invalid File Name",
                          "Cannot open " + pathName, JOptionPane.ERROR_MESSAGE);
            StringBuffer buffer = new StringBuffer((int)file.length());
            char ch;
            while ((ch = fileIn.readChar()) != '\0')
              buffer.append(ch);
            fileIn.close();
            saveItem.setEnabled(true);
            text = buffer.toString();
            textAreaIn.setText(text);
            setHints(text);
            textAreaOut.setText(codeMachine.decode(text));
          else if (m == saveItem)
            JFileChooser fileChooser = new JFileChooser(pathName);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            result = fileChooser.showSaveDialog(thisWindow);
            if (result == JFileChooser.CANCEL_OPTION)
              return;
            File file = fileChooser.getSelectedFile();
            if (file != null)
              pathName = file.getAbsolutePath();
            EasyWriter fileOut = new EasyWriter(pathName);
            if (fileOut.bad())
              JOptionPane.showMessageDialog(thisWindow, "Invalid File Name",
                          "Cannot create " + pathName, JOptionPane.ERROR_MESSAGE);
            text = textAreaOut.getText();
            fileOut.print(text);
            fileOut.close();
          else if (m == exitItem)
            System.exit(0);
      private class DecodeAction implements ActionListener
        public void actionPerformed(ActionEvent e)
          String cmd = ((AbstractButton)e.getSource()).getActionCommand();
          if ("Refresh".equals(cmd) || "Decode".equals(cmd))
            normalSubs();
          else if ("Clear".equals(cmd))
            clearSubs();
          else if ("Encode".equals(cmd))
            randomSubs();
          textAreaOut.setText(codeMachine.decode(textAreaIn.getText()));
      /***************                  main             ****************/
      public static void main(String[] args)
        Cryptogram window = new Cryptogram();
        window.addWindowListener(new WindowAdapter()
          { public void windowClosing(WindowEvent e) { System.exit(0); }});
        window.setBounds(30, 30, 800, 600);
        window.show();
    Enigma.java
    import java.util.*;
    public class Enigma
         private String lookupTable;
         private int[] letterCount;
         private static String frequentLetters="JQXZKBVWFUYMPGCLSDHROANITE";
         public Enigma()
              lookupTable="--------------------------";
              letterCount=new int[26];
         public void setSubstitutions(String lookupTable) {
              this.lookupTable = lookupTable;
         public String decode(String text)
              String decoded="";
              for(int i=0;i<text.length();i++)
                   if(Character.isLetter(text.charAt(i)))
                        decoded+=lookupTable.charAt((int)text.toLowerCase().charAt(i)-97);
                        if(Character.isUpperCase(text.charAt(i)))
                             Character.toUpperCase(decoded.charAt(decoded.length()-1));
                   else
                        decoded+=text.charAt(i);
              return decoded;
         public void countLetters(String text)
              Arrays.fill(letterCount, 0);
              for(int i=0;i<text.length();i++)
                   if(Character.isLetter(text.charAt(i)))
                   letterCount[((int)Character.toLowerCase(text.charAt(i)))-97]++;
         public int getFrequencyPos(int k)
              char letter=(char)(k+97-1);
              return frequentLetters.indexOf(letter);
    }The specific error:
    Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
         at java.lang.String.substring(Unknown Source)
         at Cryptogram.setHints(Cryptogram.java:214)
         at Cryptogram$FileAction.actionPerformed(Cryptogram.java:254)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.AbstractButton.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)and a text file known to generate this issue:
    Okjcwkn Wusln yox ckbogcnwi gs fvffcwx, oki nbws opp yzrnw ck bsizovpcjx. Nbws pctwi ck nbw Xozob Iwxxwzn oki nzotwpwi gs Jofwprn. Nbw jpcfonw re nbw Xozob cx xvjb nbon nbw ckbogcnoknx botw nr pctw wpxwybwzw, xr jwznock ozwox re nbw iwxxwzn ozw jvpnctonwi gs czzcnoncrk. Nbw lszofcix ozw o zokuw re frvknockx gwnywwk Ezokjw oki Xlock. Nbw Wuslncokx gvcpn nbw lszofcix ck nbw xbolw re bvuw nzcokuvpoz jvgw.
    Nbw Uzwwdx ywzw o bcubps xjvplnvzwi lwrlpw, oki ycnbrvn nbwf yw yrvpik'n botw bcxnrzs. Nbw Uzwwdx opxr boi fsnbx. O fsnb cx o ewfopw frnb. Rkw fsnb xosx nbon nbw frnbwz re Ojbcppwx icllwi bcf ck nbw zctwz Xnska vkncp bw gwjofw cknrppwzogpw. Ojbcppwx ollwozx ck Nbw Cpcoi, gs Brfwz. Brfwz opxr yzrnw Nbw Riicns, ck ybcjb Lwkwprlw yox nbw poxn bozixbcl nbon Vpsxxwx wkivzwi rk bcx mrvzkws. Ojnvopps, Brfwz yox krn yzcnnwk gs Brfwz, gvn gs okrnbwz fok re nbon kofw.
    Xrjzonwx yox o eofrvx uzwwd nwojbwz ybr ywkn ozrvki uctcku lwrlpw oitcjw. Nbws dcppwi bcf. Xrjzonwx icwi ezrf ok rtwzirxw re ywiprjd. Oenwz bcx iwonb, bcx jozwwz xveewzwi o izofoncj iwjpckw.
    Ck nbw Rpsflcj Uofwx, Uzwwdx zok zojwx, mvflwi, bvzpwi nbw gcxjvcnx, oki nbzwy moto. Nbw zwyozi nr nbw tcjnrz yox o jrzop yzwonb.
             Ezrf "Okuvcxbwi Wkupcxb" gs Zcjbozi Pwiwzwz.Thanks! :)
    Edited by: John_Musbach on Feb 27, 2008 11:55 AM

    I fixed the funfunction like so:cti
    public int getFrequencyPos(int k)
              //char letter=(char)(k+97-1);
              //return frequentLetters.indexOf(letter);
              int countOfK=letterCount[k];
              Arrays.sort(letterCount);
              for(int i=0;i<letterCount.length;i++)
                   if(countOfK==letterCount)
                        return i;
              return 0;

  • Java.lang.ClassNotFound Exception whenever I include .send()

    Everything runs fine, but when I add the .send(message); [it is in bold] I get a java.lang.ClassNotFound Exception.
    It still compiles, it just won't allow me to launch the program in the emulator. If I take that one piece of code out, everything runs fine again. I've been messing with it, and searching for a long time in an attempt to solve the problem but I've yet to come across a solution.
    I'm also using Bluej
    import java.io.*;
    import java.lang.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;//Add SMS text, Map selection (upload image/altitude-scale)
    import javax.microedition.lcdui.Font;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.Canvas;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.wireless.messaging.*;
       public class cardcanvas extends GameCanvas implements Runnable, CommandListener {
        Image i, Mortar, Target, paintballcharleston, selectimg, Cursor;
        SendSMS sendtext;
        Thread t = new Thread(this);
        Command cmdfire=new Command("Fire", Command.BACK, 1 );
        Command cmdreset=new Command("Reset", Command.ITEM, 2 );
        String text, message;
        static Image Map;
        MessageConnection messageConnection;
        TextMessage textMessage;
        int mortarX=5500, mortarY=5500, targetX=5500, targetY=5500, distanceX, distanceY, delay, mapx=-250, mapy=-250, xvel=115, yvel=130, gameAction=0, timer=0;
        double A, B, C, b, degreeX, degreeY, degreeV, voltageX, voltageY, scale=1.4235, findDegree=90;//get scale of pixel:realtime feet
        boolean paintdown=false, paintup=false, paintright=false, paintleft=false, left, finish, firemor, initiate, click, bottom=true, noYdegree, reset, sms=false;
        public cardcanvas(){
            super(false);
            this.addCommand(cmdfire);
            this.addCommand(cmdreset);
            this.setCommandListener(this);
        public void intit() {}
        public void start() {
            t.start() {}
        public void run()
            try{
                while(true)
                    if(paintright) {
                        timer++;
                        if(timer>1&&timer<4) xvel=xvel+5;
                        if(timer>=4&&timer<6) xvel=xvel+10;
                        if(timer>=6) xvel=xvel+20;
                    if(paintleft) {
                        timer++;
                        if(timer>1&&timer<4) xvel=xvel-5;
                        if(timer>=4&&timer<6) xvel=xvel-10;
                        if(timer>=6) xvel=xvel-20;
                    if(paintup) {
                        timer++;
                        if(timer>1&&timer<4) yvel=yvel-5;
                        if(timer>=4&&timer<6) yvel=yvel-10;
                        if(timer>=6) yvel=yvel-20;
                    if(paintdown) {
                        timer++;
                        if(timer>1&&timer<4) yvel=yvel+5;
                        if(timer>=4&&timer<6) yvel=yvel+10;
                        if(timer>=6) yvel=yvel+20;
                    if(mapy<-320) mapy=-320;
                    if(mapx>0) mapx=0;
                    if(mapy>0) mapy=0;
                    if(mapx>197) mapx=197;
                    if(xvel>225)
                        mapx=mapx-5;
                        targetX=targetX-5;
                        mortarX=mortarX-5;
                        xvel=225;
                    if(xvel<5)
                        mapx=mapx+5;
                        targetX=targetX+5;
                        mortarX=mortarX+5;
                        xvel=5;
                    if(yvel>260)
                        mapy=mapy-5;
                        targetY=targetY-5;
                        mortarY=mortarY-5;
                        yvel=260;
                    if(yvel<5)
                        mapy=mapy+5;
                        targetY=targetY+5;
                        mortarY=mortarY+5;
                        yvel=5;
                        if(reset) {
                            mapx=-250;
                            mapy=-250;
                            xvel=115;
                            yvel=130;
                            left=false;
                            firemor=false;
                            finish=false;
                            initiate=false;
                            click=false;
                            bottom=true;
                            noYdegree=false;
                            reset=false;
                            targetX=5500;
                            targetY=5500;
                            mortarX=5500;
                            mortarY=5500;
                            A=0;
                            B=0;
                            C=0;
                            b=0;
                            degreeX=0;
                        if(initiate) {
                           distanceX=targetX-mortarX;
                           distanceY=targetY-mortarY;
                           A=distanceY;
                           B=distanceX;
                               if(distanceY<0)
                                    A=distanceY*-1;
                                    bottom=false;
                               if(distanceX<0)
                                    B=distanceX*-1;
                                    left=true;
                            A=A*scale;
                            B=B*scale;
                            C=Math.sqrt((A*A)+(B*B));
                                while(((A*(Math.tan(b)))<B+.00002))
                                    b=b+.0001;
                            b=b*180/3.1415926535897932384626435;
                            degreeX=b;
                                if(bottom)
                                    b=90-b;
                                    b=b+90;
                                    degreeX=b;
                                if(left)
                                    degreeX=360-b;
                            initiate=false;
                            text=("DegreeX is "+degreeX+" Range is "+C);
                             sendTextMessage();
                     verifyGameState();
                     paint(getGraphics());
                     Thread.currentThread().sleep(1);
                catch (Exception E) {}
        private void verifyGameState() {}
        public void sendTextMessage()
            try
                String message = " ";
                MessageConnection messageConnection = (MessageConnection)Connector.open("sms://18433036060");
                TextMessage textMessage = (TextMessage)messageConnection.newMessage(
                        MessageConnection.TEXT_MESSAGE, "18433036060");
                textMessage.setPayloadText(message);
                *messageConnection.send(textMessage);*
            catch (Exception e) {}
    }If I remove messageConnection.send(texstMessage); the error is gone.
    Thanks in advance for your time

    cardmidlet:
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    import java.io.IOException;
    import java.lang.*;
    public class cardmidlet extends MIDlet implements CommandListener {
        private Display display; Display map;
        cardmidlet midlet;
        private Form form; Form mapselection;
        private List menuList ;
        String[] elements=new String[]{"Initiate Program","Select Map","Help","About"};
        private Command selectCommand;
        Alert alert;
            private Command fnext=new Command("NEXT",Command.ITEM,1);
            private Command fback=new Command("BACK",Command.BACK,1);
            private Command mapnext=new Command("Next",Command.ITEM,1);
        private TextField uname; TextField mapchoice;
        public String nname, nmap;
        cardcanvas cd;
        protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        protected void pauseApp() {
        public cardmidlet() {
             menuList();
             cd = new cardcanvas();
        public void menuList(){
             display = Display.getDisplay(this);
             menuList = new List("Menu", List.IMPLICIT, elements, null);
             selectCommand=new Command("open",Command.ITEM,1);
             menuList.setSelectCommand(selectCommand);
             menuList.setCommandListener(this);  
        protected void startApp() throws MIDletStateChangeException {
            display.setCurrent(menuList);
        public void about(){
            alert = new Alert("Option Selected", "This program is created by"+"\n"+" Chris Furlong.", null, null);
              alert.setTimeout(Alert.FOREVER);
              alert.setType(AlertType.INFO);
              display.setCurrent(alert);
        public void help() {
            alert = new Alert("Option Selected", "Use the 4 d-pad keys to move the cursor. Press the center button once to select the mortar position, and a second time to select the target position. When both the mortar and the target are on screen, press the upper left key to begin the firing process. If you place one on the map by mistake, simply reset the program with the upper right key and start over.", null, null);
            alert.setTimeout(Alert.FOREVER);
            alert.setType(AlertType.INFO);
            display.setCurrent(alert);
        public void InitiateProgram(){
            display=Display.getDisplay(this);
            uname=new TextField("Enter your name","",50,TextField.ANY);
            form =new Form("New User");
            form.append(uname);
            form.addCommand(fnext);
            form.addCommand(fback);
            form.setCommandListener(this);
            display.setCurrent(form);
        public void selectmap()
           /* display=map.getDisplay(this);
            mapchoice=new TextField("Enter Map Name","",50,TextField.ANY);
            mapselection=new Form("Map Selection");
            mapselection.append(mapchoice);
            mapselection.addCommand(mapnext);
            mapselection.addCommand(fback);
            mapselection.setCommandListener(this);
            display.setCurrent(mapselection);*/
            display = map.getDisplay(this);
            map choose=new map();
        public String name(){
            nname=uname.getString();
            return nname;
    /*   public String mapname() {
            nmap=mapchoice.getString();
            return nmap;
        public void commandAction(Command com, Displayable arg1) {
             if(com==selectCommand)
                if(menuList.getSelectedIndex()==3)
                    about();
                if(menuList.getSelectedIndex()==2)
                    help();
                if(menuList.getSelectedIndex()==1)
                    selectmap();
                if(menuList.getSelectedIndex()==0)
                    InitiateProgram();
            if(com==fback)
                display.setCurrent(menuList);
            if(com==fnext){
                display = Display.getDisplay(this);
                cd.start();
                display.setCurrent(cd);
            if(com==mapnext)
                display = map.getDisplay(this);
                map choose=new map();
                display.setCurrent(choose);
    }

  • Error: Exception in thread "main" java.lang.StringIndexOutOfBounds

    I have to write a program that calculates a monthly mortgage payment from a 10,000 loan, decreases the principle, and displays all of the info (principle payment, interest payment, loan balance) for each month. Since all of that info would scroll off the screen, I have to break it down where it will show a few months, prompt user for input to scroll down, and then show the rest of the info. I keep getting this error:
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String Index Out Of Range: 0
    at java.lang.String.charAt (Unknown Source)
    at Payment2.main (Payment2.java: 20)
    Here is my code:
    import java.text.*;
    import java.lang.*;
    class Payment2 {
         public static void main(String[] arguments) {
              double LoanAmount = 10000;
              int Term = 3;
              double AnnualInterest = .0575;
              double InterestRate = AnnualInterest/12;
              double MonthlyPayment = (LoanAmount*InterestRate)/(1-(Math.pow(1/(1+InterestRate),(Term*12))));
              String UserInput = "";
              double LoanBalance;
         System.out.println("The amount of the loan is $10,000.");
         System.out.println("The annual interest rate is 5.75%.");
         System.out.println("The term of the loan is 3 years.");
         System.out.println("The average monthly payment is $302.");
         System.out.println("Please press Enter to continue, or Q to quit.");
         if((UserInput.toUpperCase().charAt(0)) != 'Q')
         LoanBalance = LoanAmount;
         int DisplayMonth = 1;
         int DisplayLoop = 0;
         while (DisplayMonth <= (Term*12))
         double InterestPayment = LoanBalance*InterestRate;
         double PrinciplePayment = MonthlyPayment-InterestPayment;
         LoanBalance = (LoanBalance-PrinciplePayment);
         NumberFormat nfo;
         nfo = NumberFormat.getCurrencyInstance();
         String MyFormattedInterest = nfo.format(InterestPayment);
         String MyFormattedPrinciple = nfo.format(PrinciplePayment);
         String MyFormattedBalance = nfo.format(LoanBalance);
         System.out.println("For Month " + DisplayMonth + ":");
         System.out.println("The Monthly Payment is " + MonthlyPayment);
         System.out.println("Interest paid is " + MyFormattedInterest);
         System.out.println("Principle applied is " + MyFormattedPrinciple);
         System.out.println("The new loan balance is " + MyFormattedBalance);
         DisplayMonth++;
         DisplayLoop++;
         if (DisplayLoop == 6)
              System.out.println("Press Enter to scroll down...");
    public static String readLine()
    int ch;
    String r = "";
    boolean StringDone = false;
    while (!StringDone)
    try
    ch = System.in.read();
    if (ch < 0 || (char)ch == '\n') StringDone = true;
    else r = r + (char) ch;
    } // end try
    catch(java.io.IOException e)
    StringDone = true;
    } //end catch
    }// end while
    return r;
    } // end Readline
    PLEASE HELP!!! I would greatly appreciate any tips that anyone can give. Thx
    Ryane

    OK, so I fixed that part, it will run now. But, can't figure out how to keep the screen from scrolling down all the way to the bottom of the list. I need it to stop after 3 months, each time, asking the user to press Enter to scroll down (or any input that will work for this). Any hints on that? Also, when I run the program, I have to press Enter to get it to actually start displaying info. Otherwise, I run it and it just sits there. But when I press Enter, it scrolls and prints all information for the entire loan, 36 months. Here's my updated code. Thx
    class Payment2 {
         public static void main(String[] arguments) {
              double LoanAmount = 10000;
              int Term = 3;
              double AnnualInterest = .0575;
              double InterestRate = AnnualInterest/12;
              double MonthlyPayment = (LoanAmount*InterestRate)/(1-(Math.pow(1/(1+InterestRate),(Term*12))));
              String UserInput = readLine();
              double LoanBalance;
         System.out.println("The amount of the loan is $10,000.");
         System.out.println("The annual interest rate is 5.75%.");
         System.out.println("The term of the loan is 3 years.");
         System.out.println("The average monthly payment is $303.09.");
         if((UserInput.toUpperCase().charAt(0)) != 'Q')
         LoanBalance = LoanAmount;
         int DisplayMonth = 1;
         int DisplayLoop = 0;
         while (DisplayMonth <= (Term*12))
         double InterestPayment = LoanBalance*InterestRate;
         double PrinciplePayment = MonthlyPayment-InterestPayment;
         LoanBalance = (LoanBalance-PrinciplePayment);
         NumberFormat nfo;
         nfo = NumberFormat.getCurrencyInstance();
         String MyFormattedPayment = nfo.format(MonthlyPayment);
         String MyFormattedInterest = nfo.format(InterestPayment);
         String MyFormattedPrinciple = nfo.format(PrinciplePayment);
         String MyFormattedBalance = nfo.format(LoanBalance);
         System.out.println("For Month " + DisplayMonth + ":");
         System.out.println("The Monthly Payment is " + MyFormattedPayment);
         System.out.println("Interest paid is " + MyFormattedInterest);
         System.out.println("Principle applied is " + MyFormattedPrinciple);
         System.out.println("The new loan balance is " + MyFormattedBalance);
         DisplayMonth++;
         DisplayLoop++;
         if (DisplayLoop == 3)
              System.out.println("Press Enter to scroll down...");
    public static String readLine()
    int ch;
    String r = "";
    boolean StringDone = false;
    while (!StringDone)
    try
    ch = System.in.read();
    if (ch < 0 || (char)ch == '\n') StringDone = true;
    else r = r + (char) ch;
    } // end try
    catch(java.io.IOException e)
    StringDone = true;
    } //end catch
    }// end while
    return r;
    } // end Readline
    }

  • Java.lang.NoSuchMethod: main - Help pls

    This is the code i got off a book but it seems like it's not working. I got an error which says 'java.lang.NoSuchMethod: main' Help pls...
    import java.io.*;
    import java.util.*;
    class PostfixInterpreter {
         private String postfixString, outputString;
    private boolean isOperator(char c) {
         return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' );
    private boolean isSpace(char c) {
         return (c == ' ');
    }//end isSpace
    public void interpretPostfix() {
         Stack evalStack= new Stack();
         double leftOperand, rightOperand;
         char c;
         StringTokenizer parser = new StringTokenizer(postfixString,"+-*/^ ", true);
         while (parser.hasMoreTokens()){
              String token = parser.nextToken();
              c = token.charAt(0);
              if ((token.length() == 1) && isOperator(c)) {
                   rightOperand = ((Double)evalStack.pop()).doubleValue();
                   leftOperand = ((Double)evalStack.pop()).doubleValue();
                   switch (c) {
                        case'+': evalStack.push(new Double(leftOperand+rightOperand));
                                       break;
                        case'-': evalStack.push(new Double(leftOperand-rightOperand));
                                       break;
                        case'*': evalStack.push(new Double(leftOperand*rightOperand));
                                       break;
                        case'/': evalStack.push(new Double(leftOperand/rightOperand));
                                       break;
                        case'^': evalStack.push(new Double(Math.exp(Math.log(leftOperand)*rightOperand)));
                                       break;
                        default:
                                       break;
                   }//end of switch
              }else if((token.length() == 1)&& isSpace(c)){
              }else {
                   evalStack.push(Double.valueOf(token));
              }//end if
         }//end while
    // remove final result from stack and output it
    output("value of postfix expression = " + evalStack.pop());
    }//end interpretPostfix
    private void output(String input){
         postfixString = input;
         }//end setInput
    public String getOutput(){
         return outputString;
    }//end getOutput
    }//end class PostfixInterpreter
    /*Stack class*/
    class Stack {
         private int count;
         private int capacity;
         private int capacityIncrement;
         private Object[] itemArray;
    //the following defines a no-arg constrcutor for Stack objects
    public Stack() {
         count = 0;
         capacity = 100;
         capacityIncrement = 5;
         itemArray = new Object[capacity];
         public boolean empty() {
              return (count ==0);
         public void push(Object X) {
              //if the itemArray does not have enough capacity
              //expend the itemArray by the capacity increment
                   if(count == capacity) {
                        capacity += capacityIncrement;
                        Object[] tempArray = new Object[capacity];
                        for (int i=0; i<count;i++){
                             tempArray[i] = itemArray;
                   itemArray=tempArray;
              //insert the new item X at the end of the current item sequence
              //and increase the stack's count by one
                   itemArray[count++]=X;
    public Object pop() {
         if(count==0){
              return null;
         }else{
              return itemArray[--count];
    }//end of pop()
    public Object peek() {
         if (count == 0){
              return null;
         }else{
              return itemArray[count-1];
    }//end peek()

    First, when posting code in the future, use the code /code tags. Just highlight the code and click the code. button.
    The error probably occurred when you tried to launch the class as an application by entering "java PostfixInterpreter" The java application launcher looks for a method in the PostfixInterpreter class whose signature is exactly public static void main(String[] args)(except 'args' can be any legal variable name). Since your PostfixInterpreter class doesn't have this method, you get the error. If you want this class to run, you have to include the method and code inside the method that runs the application.

Maybe you are looking for