Converting a String to an Int

Hi,
I am having trouble coding my programming. I need to compare two teams scores, and I believe to do this I have to convert the team name to an int. I am having problems with this.
Any Help Please
Thanks

I'm going to assume that reading the information out of the file is already done so we'll press on with the rest of it.
There's the cheap and easy solution
1. Read the values from the row in the file into four variables
String homeTeamName
int homeTeamScore
String visitingTeamName
int visitingTeamScore
if(homeTeamScore > visitingTeamScore){
    // Deal with the home team winning
else if(homeTeamScore < visitingTeamScore){
    // Deal with the visiting team winning
else{
    // Deal with a tie
}No rocket science involved.
Now, then there's a more tidy and graceful way to do it.
The Team class holds information relevant to the team
public class Team
    private String teamName ;
    private boolean homeTeam ;
    private int score ;
    // Don't forget accessors and mutators
}The Game class holds among other things two instances of the Team class and a method to determine who won.
public class Game
    private Team home ;
    private Team visitor ;
    // Probably lots of other stuff but here's the relevant part
    public Team getWinner() throws TieScoreException
        if(home.getScore() == visitor.getScore())
            throw new TieScoreException() ;
        else if(home.getScore() > visitor.getScore())
            return home ;
        else
            return visitor ;
}Now obviously there would be a lot more to do but this gives you A framework in which to think. I likely wouldn't model it exactly this way but it's the first arrangement that my brain spat up and it gives you something to think about.
Hope this helps,
PS.

Similar Messages

  • How can I convert a String into an int?

    I need to use command-line args. So I enter "java Main 123" and I want to use 123 not as a String but as an int.
    How can I convert it into an int?
    Thank You!!
    Sprocket

    Example method (you don't need to use a method unless you do this a lot)
    private int stringTOInt (String aString)
    int result = 0;
    try
    result = Integer.parseString(aString);
    catch (Exception ex)
    System.out.println ("Failed to convert string " + aString + " to int.");
    return result;
    }

  • Converting a String to an Int????  (Java)

    I am reading in a value from the user as a string. But I need to use that value as an int value. Can you parse a string to an int? Or can someone tell me another way I should be doing this?
    Thanks

    Integer.parseInt()
    Next time, search the forum, this gets asked every day.

  • How to convert a string[] to a int ?

    Hi,
    I'm a beginner in JAVA and I shall create a function that convert a date into a long (this is done), the problem I have is that I retrieve the date from a text field (so it's a string[]), therefore when I put it (as parameter) into my function it's crash and that's normal.
    Is anyone able to help me ?
    Thanks
    //This is my code, my function//
    //Function which convert Date parameter as seconds numeric value
    public long ConvertDateToSec(int day, int month, int year)
    java.util.Date date = new java.util.GregorianCalendar(year, month,day).getTime();
    long seconds = date.getTime() / 1000;
    System.out.println("La date en seconde est " + seconds);
    return seconds;
    //And this is when I retrieve the data and when I put it as parameter
    long begindat;//For storing begin date seconds value
    String daydeb=request.getParameterValues("BeginDay");
    String monthdeb=request.getParameterValues("BeginMonth");
    String yeardeb=request.getParameterValues("BeginYear");
    begindat=ConvertDateToSec(yeardeb,monthdeb,daydeb);

    salut,
    pour r�cuperer UNE VALEUR UNIQUE d'un champ, utilise la m�thode request.getParameter("monChamp") au lieu de request.getParameterValues() qui est plutot utilis�e pour les champs qui peuvent contenir plusieurs valeurs comme les checkbox par exemple :
    dans ton code cela donnera :
    String daydeb=request.getParameter("BeginDay");
    String monthdeb=request.getParameter("BeginMonth");
    String yeardeb=request.getParameter("BeginYear");
    ensuite convertis les chaines que tu as r�cup�r� en int :
    int day = Integer.valueOf(daydeb).intValue();
    int month = Integer.valueOf(monthdeb).intValue();
    int year = Integer.valueOf(yeardeb).intValue();
    enfin, tu utilises ta fonction de conversion :
    long lgDate = ConvertDateToSec(day, month, year);
    bon courage !
    Badr.

  • Converting a string to several int.

    Hi I am having trouble getting a string to several integers. I have a String that looks like this: N163644. I need three integers with the numbers 16, 36 and 44 for further calculations. I have tried converting to char[] and then to int but it most be an easier way.
    thankful for all help.

    It works fine with this code.
    int degLat = Integer.parseInt(lat1.substring(1,3));
    Thanks..

  • How to convert a string to an int?

    Call me stupid but I can't find it in the documentation.
    The String in question will always contain a number between 1 and 100.
    Thanks in advance.

    umm say ur string is CH...
    u'd go...
    ch=br.readLine ();
    int=Integer.parseInt(ch);
    man i feel smart... see if any1 can help me out. hahaha... my question is like a few threads ahead. :D

  • How do I know if I can convert a String value to an int value or not?

    Hi,
    I want to know how to make the judgment that if I can convert a String value to an int value or not? Assume that I don't know the String is number or letters
    Thank you

    Encephalopathic wrote
    Again, why?One of the problems (have been dued) in my codelab asks us to write a class as follow
    Write a class definition of a class named 'Value' with the following:
    a constructor accepting a single integer paramter
    a constructor with no parameters
    a method 'setVal' that accepts a single parameter,
    a boolean method, 'wasModified' that returns true if setVal was ever called for the object.
    a method 'getVal' that returns an integer value as follows: if setVal has ever been called, it getVal returns the last value passed to setVal. Otherwise if the "single int parameter" constructor was used to create the object, getVal returns the value passed to that constructor. Otherwise getVal returns 0.
    The setVal(int y) returns nothing, so how do I know whether it has been called or not?
    Thank you

  • Converting a Hex String to an Int

    I have a quick question. I am attempting to encode an Integer as a Hex String using Integer.toHexString(), which produces a max of eight hex characters.
    I then need to convert this string back to an integer. I tried using Integer.parseInt(string, 16), but this only works for positive integers, because it expects a negative number to be designated with a "-" sign, which is the behavior of Integer.toString(int, 16).
    I do not wish to represent the "-" sign in that manner, because I want to minimize the length of the hex string.
    This method is time-critical, and I would like it to be as simple as possible, so I am looking for a solution in the standard libraries. Does anybody know of a method to convert the eight character hex representation which includes the sign bit as part of the eighth character back to an int using a method provided by the libraries?

    int intVal = (int)Long.parseLong(str, 16);

  • Converting string to an int

    hi,
    is there anyway i can easily convert a string into a long int.
    I have an id string which consists of 11 characters, the first 3 are used to identify the type. the last 8 are numbers that need to go in a sequence.
    Eg, 44400000001, next would be 44400000002 and so on.
    i can break the string into two, but when i convert the last part into an int it does not keep the 0s. i need the length of this int to remain 8.
    thanks
    Shazan
    Edited by: shazan on Apr 24, 2008 11:27 AM

    shazan wrote:
    ...but when i convert the last part into an int it does not keep the 0s. i need the length of this int to remain 8.
    How do you mean, keep the zeros?
    int is short for integer, it doesn't have length as in number of characters...
    What about keeping the last part as String as well and converting it inside the calculations (or whatever you're doing)... or maybe convert it and do what you're doing and then convert it back to String with padded zeros?

  • Convert from String to Int

    Hi,
    I have a question.
    How do I convert from String to Integer?
    Here is my code:
    try{
    String s="000111010101001101101010";
    int q=Integer.parseInt(s);
    answerStr = String.valueOf(q);
    catch (NumberFormatException e)
    answerStr="Error";
    but, everytime when i run the code, i always get the ERROR.
    is the value that i got, cannot be converted to int?
    i've done the same thing in c, and its working fine.
    thanks..

    6kyAngel wrote:
    actually it convert the string value into decimal value.In fact what it does is convert the (binary) string into an integer value. It's the String representation of integer quantities that have a base (two, ten, hex etc): the quantities themselves don't have a base.
    To take an integer quantity (in the form of an int) and convert it to a binary String, use the handy toString() method in the Integer class - like your other conversion, use the one that takes a radix argument.

  • Need help to convert this format of string in a int value?

    public static int isNumber( String number, int defaultValue ) {
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Hi, I have the above method that converts a string Number into a int value. It works fine if the string is a normal number 234 (without spaces) but I have a string in the following format:
    *(space)�23,000(space).*
    That is I have a "space" then a "Pound" sign then two numbers then a comma followed by three numbers and then a space again.
    Is there any way I can convert this format into a simple int value?
    Thanks for any guidance.
    Zub

    Hi, I tried the following code but it don't seem to work
         public static int isNumberTrimSpaces( String number, int defaultValue ) {
              number.trim();
              String parsed = "";
              for (int i = 0 ; i < number.length() && number.charAt(i) != ',' ; i++)
             if (Character.isDigit(number.charAt(i))) {
             parsed += number.charAt(i);}
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Any Ideas? Also will the loop get rid of the pound sign?

  • How to convert String array into int.

    void getSoldSms(Vector vecSoldSms)
         String str[]=new String[vecSoldSms.size()];
         String words[]=new String[str.length]; // String array
              for(int i=0;i< vecSoldSms.size();i++)
                   str=(String)vecSoldSms.get(i);
              }               //End for
              for(int i=0;i<str.length;i++)
              words = str[i].split("\\|\\|");
              System.out.println();
              for(int j=0;j<1;j++)     
              int count[str.length]=Integer.parseInt(words[i]);
              System.out.print(count[j]*advance_count);
              } // end inner for loop
              }          //End for
         }          //End function getSoldSms
    how do i convert words which is a string array into int type. i kno string can be converted into int using interger.parseint. but wat abt string arrays??? plz help me out with the above code.

    i did tht its still giving the same errorFor Heaven's sake, what about taking a second to try to understand the code you're copying first? If you really can't fix the error yourself, you have a more serious problem than just convertingStrings to ints.
    And if you want { "1", "2", "3" } to be 123:
    StringBuffer b = new StringBuffer();
    for (int i = 0; i < array.length; i++) {
      b.append(array);
    int result = Integer.parseIn(b.toString());

  • "Property value is not valid" when PropertyGridView tries to convert a string to a custom object type.

    Hi,
    I have a problem with an PropertyGrid enum property that uses a type converter.
    In general it works, but when I double clicking or using the scoll wheel,  an error message appears:
    "Property value is not valid"
    Details: "Object of type 'System.String' cannot be converted to type 'myCompany.myProject.CC_myCustomProperty."
    I noticed that the CommitValue method (in PropertyGridView.cs) tries to convert a string value to a CC_myCustomProperty object.
    Here is the code that causes the error (see line 33):
    (Using the .net symbols from the PropertyGridView.cs file)
    1
            internal bool CommitValue(GridEntry ipeCur, object value) {   
    2
    3
                Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose,  "PropertyGridView:CommitValue(" + (value==null ? "null" :value.ToString()) + ")");   
    4
    5
                int propCount = ipeCur.ChildCount;  
    6
                bool capture = Edit.HookMouseDown;  
    7
                object originalValue = null;   
    8
    9
                try {   
    10
                    originalValue = ipeCur.PropertyValue;   
    11
    12
                catch {   
    13
                    // if the getter is failing, we still want to let  
    14
                    // the set happen.  
    15
    16
    17
                try {  
    18
                    try {   
    19
                        SetFlag(FlagInPropertySet, true);   
    20
    21
                        //if this propentry is enumerable, then once a value is selected from the editor,   
    22
                        //we'll want to close the drop down (like true/false).  Otherwise, if we're  
    23
                        //working with Anchor for ex., then we should be able to select different values  
    24
                        //from the editor, without having it close every time.  
    25
                        if (ipeCur != null &&   
    26
                            ipeCur.Enumerable) {  
    27
                               CloseDropDown();   
    28
    29
    30
                        try {   
    31
                            Edit.DisableMouseHook = true;  
    32
    /*** This Step fails because the commit method is trying to convert a string to myCustom objet ***/ 
    33
                            ipeCur.PropertyValue = value;   
    34
    35
                        finally {   
    36
                            Edit.DisableMouseHook = false;  
    37
                            Edit.HookMouseDown = capture;   
    38
    39
    40
                    catch (Exception ex) {   
    41
                        SetCommitError(ERROR_THROWN);  
    42
                        ShowInvalidMessage(ipeCur.PropertyLabel, value, ex);  
    43
                        return false;  
    44
    I'm stuck.
    I was wondering is there a way to work around this? Maybe extend the string converter class to accept this?
    Thanks in advance,
    Eric

     
    Hi,
    Thank you for your post!  I would suggest posting your question in one of the MS Forums,
     MSDN Forums » Windows Forms » Windows Forms General
     located here:http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=8&SiteID=1.
    Have a great day!

  • How to convert a String("yyyy-mm-dd") to the same but in Date format ?

    Hi,
    can anyone plz tell me how to convert a String to a date format.I'm using MSACCESS database.I want to store this string in the database.So i need to convert it to a date format since the table is designed such a way with date/time type for date field.I used SimpleDateFormat ,but i can't able to convert.The code is given below:
    coding:
    public String dateconvertion(String strDate)
    try
    SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdfSource.parse(strDate);
    SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd ");
    strDate = sdfDestination.format(date);
    catch(ParseException pe)
    System.out.println("Parse Exception : " + pe);
    return(strDate);
    }

    i used prepared statement even now i am getting error like this.....
    i have included the prepared statement package also...
    my coding:
    ResultSet rsdatetemp = null;
    PreparedStatement ps = null;
    String query ="select distinct itemcode from sales where bill date between ? and ?";
    ps = precon.prepareStatement(query);
    ps.setDate(1,d1);//d1 and d2 are in date format
    ps.setDate(2,d2);
    rsdatetemp = ps.executeQuery();
    error :
    symbol : method setDate(int,java.util.Date)
    location: interface java.sql.PreparedStatement
    ps.setDate(1,d1);
    symbol : method setDate(int,java.util.Date)
    location: interface java.sql.PreparedStatement
    ps.setDate(2,d2);

  • Incompatible types - found java.lang.String but expected int

    This is an extremely small simple program but i keep getting an "incompatible types - found java.lang.String but expected int" error and dont understand why. Im still pretty new to Java so it might just be something stupid im over looking...
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Lab
    public static void main(String []args)
    int input = JOptionPane.showInputDialog("Input Decimal ");
    String bin = Integer.toBinaryString(input);
    String hex = Integer.toHexString(input);
    System.out.println("Decimal= " + input + '\n' + "Binary= " + bin + '\n' + "Hexadecimal " + hex);
    }

    You should always post the full, exact error message.
    Your error message probably says that the error occurred on something like line #10, the JOptionPane line. The error is telling you that the compiler found a String value, but an int value was expected.
    If you go to the API docs for JOptionPane, it will tell you what value type is returned for showInputDialog(). The value type is String. But you are trying to assign that value to an int. You can't do that.
    You will need to assign the showInputDialog() value to a String variable. Then use Integer.parseInt(the_string) to convert to an int value.

Maybe you are looking for

  • Files from IDML or CS5, 5.5 become very slow in InDesign CS6

    Windows 7 64 bit, core 2 duo, 8 gb ram, plenty of open space on the hard drive. Files work just fine in CS5 and CS5.5. Opening one of them in CS6 and working in them when just opened is also fine. After saving the file as a CS6 document, closing, and

  • Disk #2 is 4???

    newcomer to apple slowly getting on top of my new server. it came with 2 disks which i assumed would be in raid_1 but theyre not so all programs and user data is being stored on disk#1. is disk#2 intended for something specific or do i have to set it

  • How to save a video file which uses the setCodecChain method on its video t

    hi! i really need your help please. i got the Code for RotationEffect and i would like to know how to save it to a file instead of playing it simultaneously in a player: Here is the code: Plz Help me!!! am doing my final year project import java.awt.

  • Minor gripe about MacBook Eject CD/DVD button

    I've been too positive about my overall MacBook experiences so far, so thought I'd post a minor gripe Does everyone else's Eject CD/DVD key cause the CD/DVD drive to audibly try to access the drive, even if there is no CD/DVD in the drive? The only r

  • TS4009 How do I cancel upgrade for icloud

    I have bought an annual subscription for more storage in iCloud which I do not need I would like to cancel this how do I email iCloud thanks Lilian Land