String equivalent of Integer.parseInt()

Hey..
Integer.parseInt() reads an integer that is being inputted right? what im looking though is some sort of a String equivalent of Integer.parseInt.
ex:
nString = JOptionPane.showInputDialog("Enter number:");
n = Integer.parseInt(nString);
what im looking:
nString = JOptionPane.showInputDialog("Enter text:");
n = ? (nString);
a keyword that reads the text inputted.

how do i reset the counter to 0 if the user tries again? because it doesn't reset and it makes a logical error if the user tries again.
while (trya != 0){
       if ((trya > 1) || (trya < 0))
          break; 
     else{
  z=JOptionPane.showInputDialog("Choose Difficulty:\n[1]BATHROOM SINGER\n[2]MAINSTREAM MUSICIAN\n[3]GRAMMY WINNER");
  x=Integer.parseInt(z);
  switch(x){
       case 1:
            JOptionPane.showMessageDialog(null,"DIFFICULTY: BATHROOM SINGER");
            String stringInput = JOptionPane.showInputDialog(q1);
        if (stringInput.equals(a1)){
        JOptionPane.showMessageDialog(null, "Correct!");
        i++;
        } else {
            j++;
        JOptionPane.showMessageDialog(null,"Wrong");
String stringInput29 = JOptionPane.showInputDialog(q15);
        if (stringInput29.equals(a15)){
        JOptionPane.showMessageDialog(null, "Correct!");
        i++;
        } else {
            j++;
        JOptionPane.showMessageDialog(null,"Wrong");
            JOptionPane.showMessageDialog(null,"Correct answers: "+i+"\nWrong answers: "+j+"\nTHANKS FOR PLAYING");
            break;
     default:
          JOptionPane.showMessageDialog(null,"Press either [1] [2] or [3]", "ERROR",JOptionPane.WARNING_MESSAGE);
          break;
    stry = JOptionPane.showInputDialog("Do you want to PLAY AGAIN? \n Press [1] for YES \n Press [0] for NO");
     trya = Integer.parseInt(stry);
  }

Similar Messages

  • I have jave 7 I'm trying underscore option in String.   as String strNum = "1000_000";System.out.println("..abc..."  Integer.parseInt(strNum)); but getting error. could you please help in this?

    Hi,
    There is a new feature added in java 7 on integer, called as underscore '_" and it is working fine
    if it is a normal int variable  but if it is coming with String jvm throw the error.
    if  any one of you have java8 installed on your PC can you check this is working on that version.
    int a = 1000_000;   
    String strNum = "1000_000";
    // System.out.println("..abc..."+ Integer.parseInt(strNum));
    System.out.println("a..."+a);
    Thank you,
    Shailesh.

    what is your actual question here?
    bye
    TPD

  • Coverting from a string to an integer

    Hi:
    Is it possible to covert a string to an integer?
    For example I want to convert the following string values to integers so that I can develop a method to use java.util.Date to test for overlapping appointments.
    Ex:
    markCalendar.addApp(new Appointment("June 1","3pm","4pm", "dentist"));
    I want to convert the startTime and the endTime to integers. And compare the startTime and endTime to a vector of appointments.
    Should this approch work?
    Thanks.
    Describes a calendar for a set of appointments.
    @version 1.0
    import java.util.Vector;
    public class CalendarTest
    {  public static void main(String[] args)
          Calendar markCalendar = new Calendar("Mark");
          markCalendar.addApp(new Appointment("June 1","3pm","4pm", "dentist"));
           markCalendar.addApp(new Appointment("June 2","3pm","4pm", "doctor"));
           markCalendar.print();
          Appointment toFind = new Appointment("June 2","3pm","4pm", "doctor");
          markCalendar.removeApp(toFind);   
          markCalendar.addApp(new Appointment("June 2","3pm","4pm", "dentist"));
          markCalendar.print();
          Appointment dups = (new Appointment("June 2","3pm","4pm", "dentist"));
          markCalendar.dupsTest(dups);
    Describes a calendar for a set of appointments.
    class Calendar
       Constructs a calendar for the person named.
       public Calendar(String aName)
       {  name = aName;
          appointments = new Vector();
       Adds an appointment to this Calendar.
       @param anApp The appointment to add.
       public void addApp(Appointment anApp)
          appointments.add(anApp);
       Removes an appointment from this Calendar.
       @param anApp The appointment to be removed.
       public void removeApp(Appointment toFind)
          for ( int i = 0; i < appointments.size(); i++)
             if (((Appointment)appointments.get(i)).equals(toFind))
                 appointments.remove(i);
       Tests for duplicate appointment dates.
       public void dupsTest(Appointment app)
          for (int x = 0; x < appointments.size(); x++)
             //Appointment cmp = (Appointment)appointments.elementAt(x);
             //System.out.println("cmp  " + cmp);
             for (int y = appointments.size()-1; y > x; y --)
                Appointment nextApp =(Appointment) appointments.get(y);
                //if (app.equals((Appointment)appointments.elementAt(y)))
                if (app.equals (nextApp))
                {  System.out.println("duplicates  ");
                   nextApp.print();
       Prints the Calendar.
       public void print()
       {  System.out.println(name + "               C A L E N D A R");
          System.out.println();
           System.out.println("Date   Starttime    EndTime   Appointment");
          for (int i = 0; i < appointments.size(); i++)
          {  Appointment nextApp =(Appointment) appointments.get(i);
             nextApp.print();
          //appointments.dupsTest(Appointments anApp);
       private Vector appointments;
       private String name;
       private Appointment theAppointment;
    Describes an appointment.
    class Appointment
       public Appointment(String aDate,String aStarttime,String aEndtime, String aApp)
       {  date = aDate;
          starttime = aStarttime;
           endtime = aEndtime;  
          app = aApp;
    Method to test whether on object equals another.
    @param otherObject  The other object.
    @return true if equal, false if not
    public boolean equals(Object otherObject)
          if (otherObject instanceof Appointment)
          {  Appointment other = (Appointment)otherObject;
             return (date.equals(other.date) && starttime.equals(other.starttime)
                     && endtime.equals(other.endtime) && app.equals(other.app));
           else return false;
       Prints the Date, Starttime, Endtime and a description of the
       appointment.
       public void print()  
       {  System.out.println();
          System.out.println(date + "   " + starttime + "          " + endtime
              + "       " + app );
          System.out.println();
       private String date;
       private String starttime;
       private String endtime;
       private String app;

    Hello,
    First I would like to suggest, DONT use the class names that have already being defined in JAVA, Here you have used, CALENDAR class, this approach should be avoided, If this class is in the same project where you also want to use the JAVA CALENDAR class, then you mite not be able to do so.
    As for the conversion, A simple way is that:
    You already know that the time cannot go more than 2 digits (Specifically not more than 24 hours in case of hours and 60 in case of minutes) and the (am) (pm) takes 2 more places, so what you can do is validate if the string size is 4 or 3, if 4 then take the first 2 substrings i.e. somestring.substring(0,2) and then use the Ineteger.parseInt(some string) method.
    similarly if the String size is 3 then take the first substring
    e.g. somestring.substring(0,1)
    This is how you can convert the string to the Integer and compare it, You can store it as an Integer Object and store it in the Vector If you want to.
    Hope this helps
    Regards
    Rohan

  • Something's wrong with my Integer.parseInt...

    hi...I think something's wrong with my code.
    when i don't add the loop for(int s = h; s > 0; s--) { }, it's correct, but when i do, it shows:
    java.lang.NumberFormatException: 27.0
    at java.lang.Integer.parseInt(Integer.java:414)
    at java.lang.Integer.parseInt(Integer.java:454)
    at chiayaochien3.evaluate.find(evaluate.java:55)
    at chiayaochien3.evaluate.operate(evaluate.java:48)
    at chiayaochien3.Main.main(Main.java:10)
    Exception in thread "main"
    (But i am sure the things in Integer.parseInt is String...)
    public class Main
    public static void main(String[] args)
    String[] data = {"3","+","12","*","27","/","1","-","6", "+", "222"};
    String[] operStack = null;
    String[] numStack = null;
    myStack num1 = new myStack();
    myStack num2 = new myStack();
    myStack oper1 = new myStack();
    myStack oper2 = new myStack();
    int calculateNum1 = 0;
    int calculateNum2 = 0;
    String calculate1 = null;
    String calculate2= null;
    String oper = null;
    double resultNum = 0;
    double result = 0;
    int operSize = 0;
    int numSize = 0;
    int h = 0;
    for(int i = 0; i < data.length; i++) {
    String f = data;
    if(f.compareTo("+") == 0)
    oper1.push(f);
    else if(f.compareTo("-") == 0)
    oper1.push(f);
    else if(f.compareTo("*") == 0) {
    oper1.push(f);
    h++;
    else if(f.compareTo("/") == 0){
    oper1.push(f);
    h++;
    else if(f.compareTo("^") == 0){
    oper1.push(f);
    h++;
    else
    num1.push(f);
    }//end of for
    for(int s = h; s > 0; s--){
    while(!oper1.isEmpty()) {
    calculateNum1 = Integer.parseInt((String)num1.pop());
    oper = (String)oper1.pop();
    if(oper.compareTo("*") == 0) {
    calculateNum2 = Integer.parseInt((String)num1.pop());
    resultNum = calculateNum2*calculateNum1;
    num2.push(String.valueOf(resultNum));
    while(oper1.isEmpty() == false && num1.isEmpty() == false) {
    oper2.push((String)oper1.pop());
    num2.push((String)num1.pop());
    }//end of while
    }//end of if
    else if(oper.compareTo("/") == 0) {
    calculateNum2 = Integer.parseInt((String)num1.pop());
    resultNum = calculateNum2/calculateNum1;
    num2.push(String.valueOf(resultNum));
    while(oper1.isEmpty() == false && num1.isEmpty() == false) {
    oper2.push((String)oper1.pop());
    num2.push((String)num1.pop());
    }//end of while
    }//end of else-if
    else if(oper.compareTo("^") == 0) {
    calculateNum2 = Integer.parseInt((String)num1.pop());
    resultNum = Math.pow(calculateNum2, calculateNum1);
    num2.push(String.valueOf(resultNum));
    while(oper1.isEmpty() == false && num1.isEmpty() == false) {
    oper2.push((String)oper1.pop());
    num2.push((String)num1.pop());
    }//end of while
    }//end of else-if
    else {
    num2.push(String.valueOf(calculateNum1));
    oper2.push(oper);
    }//end of else
    }//end of while
    while(!oper2.isEmpty()){
    oper1.push((String)oper2.pop());
    while(!num2.isEmpty()) {
    num1.push((String)num2.pop());
    while(!num1.isEmpty()) {
    System.out.println(num1.pop());
    while(!oper1.isEmpty())
    System.out.println(oper1.pop());
    }//end of main
    }//end of class

    "27.0" is not an integer. (Well, it is numerically, but it's a representation of a double.)

  • Integer.parseInt() error

    I am writing an applet that reads a file containing groups of 5 lines of which the first 4 hold a number. Then these values are used to draw circles. When I compile, I get this error message: "incompatible types
    found: int, required: java.lang.Integer, ia = Integer.parseInt(a)".
    Suggestions?
    Thanks!
    import java.awt.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.geom.*;
    public class Section2 extends Applet {
    TextField tekst;
    public void init() {
    resize(400,400);
    tekst = new TextField(20);
    add(tekst);
    public void paint(Graphics g) {
    try {
    String a, b, c, d, e;
    Integer ia, ib, ic, id;
    File inputFile = new File(tekst.getText());
    FileReader in = new FileReader(inputFile);
    BufferedReader BR = new BufferedReader(in);
    while (e != null){
    a = BR.readLine();
    b = BR.readLine();
    c = BR.readLine();
    d = BR.readLine();
    e = BR.readLine();
    ia = Integer.parseInt(a);
    ib = Integer.parseInt(b);
    ic = Integer.parseInt(c);
    id = Integer.parseInt(d);
    Graphics2D g2d = (Graphics2D)g;
    Ellipse2D.Double circle = new Ellipse2D.Double(ia, ib, ic, id);     
    g2d.setPaint(Color.blue);
    g2d.draw(circle);
    in.close();
    catch (IOException e) {}

    Ok everything works! I still have some questions:
    *** Can anyone tell me why I get this:
    --------------------Configuration: Section2 - j2sdk1.4.0_01 <Default>--------------------
    Note: C:\Program Files\Xinox Software\JCreator LE\MyProjects\Section textfield\Section2.java uses or overrides a deprecated API.
    Note: Recompile with -deprecation for details.
    Process completed.
    *** Is there a way to go from string to double in one step?
    This is the code:
    import java.awt.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.geom.*;
    public class Section2 extends Applet {
         TextField tekst;
         Button knop;     
         public void init() {
              resize(400,400);
              tekst = new TextField(20);
              add(tekst);
              knop = new Button("teken");
              add(knop);
         public boolean action (Event e, Object o){
              if(e.target.equals(knop)){
                   repaint();
              return true;
         public void paint(Graphics g) {
              try {
                   String a, b, c, d, e;
                   Integer ia, ib, ic, id;
                   File inputFile = new File(tekst.getText());
                   FileReader in = new FileReader(inputFile);
                   BufferedReader BR = new BufferedReader(in);
                   e = "start";
                   if (tekst.getText() != null){
                        while (e != null){
                             a = BR.readLine();
                        b = BR.readLine();
                             c = BR.readLine();
                             d = BR.readLine();
                             e = BR.readLine();
                             ia = Integer.valueOf(a);
                             ib = Integer.valueOf(b);
                             ic = Integer.valueOf(c);
                             id = Integer.valueOf(d);
                             Graphics2D g2d = (Graphics2D)g;
                             Ellipse2D.Double circle = new Ellipse2D.Double(ia.doubleValue(), ib.doubleValue(), ic.doubleValue(), id.doubleValue());     
                             g2d.setPaint(Color.blue);
                             g2d.draw(circle);
                        in.close();
              catch (IOException e) {}

  • Integer.parseInt, NumberFormatException

    Hi,
    I'm trying to convert numbers back and forth with parseInt and toHexString.
    The number that I want to manipulate is 56789abc.
    String str = Integer.toHexString(1450744508);
    int i = 0;
    try
    i = Integer.parseInt(str, 16);
    catch(NumberFormatException e)
    e.printStackInfo();
    I'm not sure why I'm getting NumberFormatException, since I think
    56789ABC doesn't cross the line. It's not out of boundary.
    Any suggestion or help really be appreciated.
    Thanks in advance,

    I don't know what you're talking about.
    Integer.parseInt("56789ABC", 16);gives 1450744508
    Works fine.

  • Integer.parseInt() method

    Hi to all
    I'm trying to write a piece of a lexical analizer in Java and I need the method the does the contrary of Integer.parseInt() method in order to do the following:
    once i have as input an integer and with the Integer.parseInt() method i know it's value I want to count it's digits. I'm sure there is a method that do the contrary of Integer.parseInt() method that I can't remeber.
    Thanks for your help
    Maddy

    Integer.parseInt() takes in a String and returns an int value, so the contrary would take in an int value and return a String. Is this what you want?
    You can use Integer.toString()
    Also, when you call Integer.parseInt(String s), you should already have the number as a String (the argument).
    Maybe I am not understanding the question right. If not, please explain exactly what you need.

  • How to Convert the Stream of strings into ArrayList Integer

    I have a String st = "12 54 456 76ASD 243 646"
    what I want to do is print it like this from the ArrayList<Integer>:
    12
    54
    456
    243
    646
    It should catch the "76ASD" exception as it contain String Character.
    This is how I am doing, which it seems to work but when it reaches the 76ASD it catches the exception so it is not adding the rest to the Arraylist, therefore I could not print in sequence.
      public static void main(String[] args) {
            // TODO code application logic here
            getDatas(testString);
            for (int i = 0; i < at.size(); ++i) {
                System.out.println(at.get(i));
        private static ArrayList<Integer> getDatas(String aString) {
            StringTokenizer st = new StringTokenizer(aString);
            try {
                while (st.hasMoreTokens()) {
                    String sts = "";
                    sts = st.nextToken();
                    at.add(Integer.parseInt(sts));
            } catch (Exception e) {
                System.out.println("Error: " + e);
            return at;
        }Please guide me where I am going
    Thanks

    paulcw wrote:
    This is one of the few cases where I'd say catching an exception as part of the design is acceptable. When parsing, either something parses, or it doesn't. Using parseInt, we're parsing the string and using the result of the parse. By using a regular expression, we're parsing it twice, in two different ways, which may get out of sync. Not only that, if you have a more complicated case, like negative numbers and decimals, the regex gets really ugly.
    I agree this is exactly the case where it is appropriate to try, catch, handle, move on. I sometimes wish there were an Integer.isValid(String) method, but even if there were, we'd call it, and if it returned true, we'd then call parseInt anyway, which would repeat the same work that isValid did. All it would buy us would be an if test instead of a try/catch.

  • How do you turn a string into an integer?

    how do you turn a string into an integer?
    for ex, if i wanted to turn the string "5" into the integer 5, how would i do that?

    String stringNumber="5";
    try{
    int number=Integer.parseInt(stringNumber);
    }catch(NumberFormatException e){
    System.out.println("The string "+stringNumber+" must be a number!");
    }

  • Integer.parseInt problems

    Hi everyone,
    I want to use the Integer.parseInt and Byte.parseByte methods to parse hex strings - the problem is that they don't parse negative 2's complement numbers, they explicitly need a minus sign in front of an otherwise unsigned number to show that it's negative.
    Examples:
    //System.out.println(Integer.parseInt(Integer.toHexString(-1), 16)); //NumberFormatException
    System.out.println(0xffffffff); // but this prints -1
    //System.out.println(Byte.parseByte("ff", 16)); //NumberFormatException
    System.out.println(Byte.parseByte("-1", 16)); // but this worksIs there some other method that will do what I need?
    Regards,
    Jonathan

    Here's a dirty solution:public class Test {
        private static char[] digits = new char[] {
            '0', '1', '2', '3',
            '4', '5', '6', '7',
            '8', '9', 'a', 'b',
            'c', 'd', 'e', 'f'
        public static void main (String[] parameters) {
            String number = Integer.toHexString (parameters[0].equals ("+") ? Integer.MAX_VALUE : parameters[0].equals ("-") ? Integer.MIN_VALUE : Integer.parseInt (parameters[0]));
            if ((number.length () == 8) && (getPosition (number.charAt (0)) >= 8)) {
                String newNumber = "";
                for (int i = 0; i < number.length (); i ++) {
                    newNumber += digits[15 - getPosition (number.charAt (i))];
                number = "";
                boolean carry = true;
                for (int i = 7; i >= 0; i --) {
                    int position = getPosition (newNumber.charAt (i));
                    if (carry) {
                        position = (position + 1) % 16;
                        carry = (position == 0);
                    number = digits[position] + number;
                number = "-" + number;
            int numberAsInt;
            try {
                numberAsInt = Integer.parseInt (number, 16);
            } catch (NumberFormatException exception) {
                // -8000000
                numberAsInt = Integer.MIN_VALUE;
            System.out.println (numberAsInt);
        private static int getPosition (char digit) {
            int position = 0;
            while ((position < digits.length) && (digits[position] != digit)) {
                position ++;
            return position;
    }Start with java Test <yourNumber>: + for Integer.MAX_VALUE, - for Integer.MIN_VALUE.
    I don't claim it's good or efficient: it's working though. There's lots of things to improve.
    Kind regards,
      Levi

  • Converting a string to an integer - NumberFormatException

    Hello,
    I have 2 string arrays, one that olds names and one that holds id numbers. They are both stored in a file as Strings. I then read this file into my program and put split the strings up into an array.
    I then try to convert the id to integer inside my program like so:
    public void make_array(String[] car_info) {
                    // put in arraylist and change variable type to correct ones
                    final int ID_INDEX = 0;
                    final int TYPE = 1;
                    int cust_id = 22;
                    String type;
                    //convert to correct variable types
                    try {
                            //convert to string
                            cust_id = Integer.parseInt(car_info[ID_INDEX]);   
                    } catch (NumberFormatException e) { System.out.println(e); }
                    type = car_info[TYPE];
    }I then get the errors when i try this:
    java.lang.NumberFormatException: For input string: "1"
    So the id was stored as "1", but i want to convert it to an integer value. Any ideas on why this happends? Also before i try to convert i output the id from the array and it is correct, after the conversion it is 0, obviously it is not working. But i'm not sure what is wrong.
    Any ideas?

    only works when the string is a single number suchas
    "1" or "4". If you try to use it with the input
    string as a longer one like "123" or "12" itcreates
    a NumberFormatExceptionYou must be mistaken. The value must not be what you
    think it is. Do some debugging:
    String strVal = car_info[ID_INDEX].trim();
    System.out.println("This is the number to be
    parsed -->" + strVal + "<--");
    customer_id = Integer.parseInt(strVal);That is a good idea, but it seems as though the string is fine: I did:
    gary@linuxbox# cat cars
    this output:
    1,5,Renault Clio,Small Car,25,4,false
    As you can see the number 25 is a two figure number, and it looks good. I also output the number in the java program like this:
    System.out.println("the number is ------>" + twodigitnumber + "<------");This output the number: ------->25<---------- So there doesn't seem to be any wierd spacing or characters there.

  • Converting a String to an integer?

    i need to convert a string to an integer..i searched through the site but i didn't find anything...
    Is this conversion possible?

    You didn't look very hard - it's right in the javadocs:
    String s = "44";
    int x = Integer.parseInt(s);I'll leave the exception handling for you.

  • How to build a fixed-length string representing an integer

    Hi,
    I would like know how can I use the API to get a String representing an int with fixed length. I mean, I would like something similar to Integer.parseInt(), but I need to set the length of that String in such a way that, for instance, if I need the String to be 5 character long, and the int is 37, the String would be 00037
    Thanks in advance and best regards,
    Miguel ?ngel

    I wrote pad() methods in my string helper that can be used for this purpose.
    In particular, you want to prepad with '0' to a length of 5:
    com.Ostermiller.StringHelper.prePad(Integer.toString(37), 5, '0');
    http://ostermiller.org/utils/StringHelper.html

  • Integer.parseInt()

    Hi!
    I have a problem that for an experienced programmer like you should be easy.
    I have in my program:
    int num = Integer.parseInt(numbers);
    And I get:
    Exception in thread "main" java.lang.NumberFormatException: For input string: "195400011111111111111113"
    It (195400011111111111111113) looks like not an integer,and I tried:
    long num = Integer.parseInt(numbers);
    But I get the same error.
    What could I do?
    Thank you,
    Nata

    That number is too big for an int, so Integer.parseInt doesn't like it. It doesn't matter if you put a long on the left side of the equals sign, Integer.parseInt only handles ints.
    Do you know about the Long class? Have you looked at its docs to see if it might have something that can help you?

  • Integer.parseInt(in.readLine()) - "null"

    I just realized that if I don't enter a value in the following:
            System.out.print("Enter the column you'd like to mark in: ");
            int col = Integer.parseInt(in.readLine());I get this error:
    Enter the column you'd like to mark in:
    java.lang.NumberFormatException: For input string: ""
         at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         at java.lang.Integer.parseInt(Integer.java:447)
         at java.lang.Integer.parseInt(Integer.java:476)
         at la5.TicTacToeDriver.main(TicTacToeDriver.java:37)
    Exception in thread "main" Is there a way to prevent this error and prompt the user for a proper input (any integer will work).

    Enclose the parse attempt in a try/catch block.

Maybe you are looking for