How do I cast a String to an int ?  HELP !

Dear Java People,
If I have a program that outputs a String of the time ie
09:25
How do I code in Java to check this String to see if it is greater than 12 o'clock and if so tack on a String of "PM'.....
I tried
if ((int) hours.getDisplayValue()> 12 )
to attempt to add "PM" at the end of the String
The error message says:
"ClockDisplay.java": Error cannot cast java.lang.String to int at line 88, column 12
below is the program
Thank you in advance
Stan
* The ClockDisplay class implements a digital clock display for a
* European-style 24 hour clock. The clock shows hours and minutes. The
* range of the clock is 00:00 (midnight) to 23:59 (one minute before
* midnight).
* The clock display receives "ticks" (via the timeTick method) every minute
* and reacts by incrementing the display. This is done in the usual clock
* fashion: the hour increments when the minutes roll over to zero.
* @author Michael Kolling and David J. Barnes
* @version 2001.05.26
public class ClockDisplay
private NumberDisplay hours;
private NumberDisplay minutes;
private String displayString; // simulates the actual display
* Constructor for ClockDisplay objects. This constructor
* creates a new clock set at 00:00.
public ClockDisplay()
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
updateDisplay();
* Constructor for ClockDisplay objects. This constructor
* creates a new clock set at the time specified by the
* parameters.
public ClockDisplay(int hour, int minute)
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
setTime(hour, minute);
* This method should get called once every minute - it makes
* the clock display go one minute forward.
public void timeTick()
minutes.increment();
if(minutes.getValue() == 0) { // it just rolled over!
hours.increment();
updateDisplay();
* Set the time of the display to the specified hour and
* minute.
public void setTime(int hour, int minute)
//Exercise 3.19 This condition will insure that it will be a 12 hour clock
if(hour > 12)
hour = hour - 12;
hours.setValue(hour);
minutes.setValue(minute);
updateDisplay();
* Return the current time of this display in the format HH:MM.
public String getTime()
return displayString;
* Update the internal string that represents the display.
private void updateDisplay()
if ((int) hours.getDisplayValue() > 12 )
displayString = hours.getDisplayValue() + ":" +
minutes.getDisplayValue() ;
* The NumberDisplay class represents a digital number display that can hold
* values from zero to a given limit. The limit can be specified when creating
* the display. The values range from zero (inclusive) to limit-1. If used,
* for example, for the seconds on a digital clock, the limit would be 60,
* resulting in display values from 0 to 59. When incremented, the display
* automatically rolls over to zero when reaching the limit.
* @author Michael Kolling and David J. Barnes
* @version 2001.05.26
public class NumberDisplay
private int limit;
private int value;
* Constructor for objects of class Display
public NumberDisplay(int rollOverLimit)
limit = rollOverLimit;
value = 0;
* Return the current value.
public int getValue()
return value;
* Return the display value (that is, the current value as a two-digit
* String. If the value is less than ten, it will be padded with a leading
* zero).
public String getDisplayValue()
if(value < 10)
return "0" + value;
else
return "" + value;
* Set the value of the display to the new specified value. If the new
* value is less than zero or over the limit, do nothing.
public void setValue(int replacementValue)
if((replacementValue >= 0) && (replacementValue < limit))
value = replacementValue;
* Increment the display value by one, rolling over to zero if the
* limit is reached.
public void increment()
value = (value + 1) % limit;
public class TryClockDisplay
public static void main(String[] args)
ClockDisplay clockDisplay_1 = new ClockDisplay();
clockDisplay_1.setTime(17,40);
System.out.println("\nThe time now is " + clockDisplay_1.getTime());
clockDisplay_1.timeTick();
clockDisplay_1.timeTick();
clockDisplay_1.timeTick();
clockDisplay_1.timeTick();
clockDisplay_1.timeTick();
clockDisplay_1.timeTick();
clockDisplay_1.timeTick();
System.out.println("\nThe time now is " + clockDisplay_1.getTime());

String time = "09:25";
String hrs = time.substring(0,2);
int hrsInt = Integer.parseInt(hrs);
if(hrsInt>12){
    time += "PM";
System.out.println(time);                                                                                                                                                                                                                                                                                                                                       

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;
    }

  • How can I cast a String to a char array?

    My code is:
    char []sender = new char[48];
    String senderStr = "event_router_send";
    sender=senderStr.toCharArray();The sender array's size will be changed to the String senderStr's length. Is there a better way to fill a array from a String object and keep the array's size.

    youhaodiyi wrote:
    My code is:
    char []sender = new char[48];
    String senderStr = "event_router_send";
    sender=senderStr.toCharArray();The sender array's size will be changed to the String senderStr's length. Is there a better way to fill a array from a String object and keep the array's size.Here's how:
    int index = 0;
    for(char c: senderStr.toCharArray()) {
        sender[index++] = c;
    }But why do you want to keep the array size in tact? What if the String has more characters in it than the array's size?

  • How to get a string in an int??

    Hi,
    I have a computerport in a String variable(f.i. 8080) and i want to cast it to an int
    I tried ldap_port = (int) ldap_port_str; but the compiler complains.
    I didn't find a method for casting a string to an int
    how can i solve this??
    THX

    Hi,
    I have a computerport in a String variable(f.i. 8080)
    and i want to cast it to an int
    I tried ldap_port = (int) ldap_port_str; but the
    compiler complains.
    I didn't find a method for casting a string to an int
    how can i solve this??
    THX
    int ldap-port=Integer.parseInt(ldap_port_str);
    [\code]
    regards
    kamal

  • How to use type cast change string to number(dbl)?can it work?

    how to use type cast change string to number(dbl)?can it work?

    Do you want to Type Cast (function in the Advanced >> Data Manipulation palette) or Convert (functions in the String >> String/Number Conversion palette)?
    2 simple examples:
    "1" cast as I8 = 49 or 31 hex.
    "1" converted to decimal = 1.
    "20" cast as I16 = 12848 or 3230 hex.
    "20" converted to decimal = 20.
    Note that type casting a string to an integer results in a byte by byte conversion to the ASCII values.
    32 hex is an ASCII "2" and 30 hex is an ASCII "0" so "20" cast as I16 becomes 3230 hex.
    When type casting a string to a double, the string must conform the the IEEE 32 bit floating point representation, which is typically not easy to enter from the keyboard.
    See tha attached LabView 6.1 example.
    Attachments:
    TypeCastAndConvert.vi ‏34 KB

  • How can i cast array of string to int ?

                       while(st.hasMoreTokens()){
                                  test[count] = st.nextToken();
                                  count++;
                          }Since token deal with string, i have to pass them into String of array, but how can i convert all of them to int to perform arithmetic operation?

         public static void main (String[] args) throws IOException{
               DataInputStream dis = null;
                 String dbRecord = null;
                 int tokenCount = 0;
                 int numOfQuestion = 0;
                 int questionnAireNum = 0;
                 int postCode = 0;
                 int age = 0;
                 int gender = 0;
                 String [] response = new String[10];
                    File f = new File("polldata.txt");
                    FileInputStream fis = new FileInputStream(f); 
                    BufferedInputStream bis = new BufferedInputStream(fis); 
                    dis = new DataInputStream(bis);
                    // read the first record of the database
                    while ( (dbRecord = dis.readLine()) != null) {
                       StringTokenizer st = new StringTokenizer(dbRecord, ",");
                       tokenCount = st.countTokens();
                       numOfQuestion = tokenCount-4;
                       String rquestionNum = st.nextToken();
                       questionnAireNum = Integer.parseInt(rquestionNum);
                       String rpostCode = st.nextToken();
                       postCode = Integer.parseInt(rpostCode);
                       String rAge  = st.nextToken();
                       age = Integer.parseInt(rAge);
                       String rGender = st.nextToken();
                       gender = Integer.parseInt(rGender);
                       for(int i=0; i<numOfQuestion;i++){
                            response[i] = st.nextToken();
                       }hi how come when i cast the string as int it prompt me error as shown below ? I wonder what causes this because this is normally how i cast string to int, somehow it won work this way with token.
    Exception in thread "main" java.lang.NumberFormatException: For input string: " 3"
         at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         at java.lang.Integer.parseInt(Integer.java:447)
         at java.lang.Integer.valueOf(Integer.java:553)
         at test.main(test.java:43)

  • How do I copy the string portion of an enum into the string portion of a cluster?

    I want to do this for the an entire array of clusters.  I'm trying to use a for loop.  Can't figure out how to parse the string portion of the enum into the string portion of the cluster.
    Alternatively, I'd be happy if I could figure out some way to tie the enum to the array of clusters, but I figure that gets problematic.
    DH
    Solved!
    Go to Solution.

    Dark Hollow wrote:
    OK, let's say that the enumerated type has N elements.  I want to initialize an N element array of strings.  How do I reference each string in the enumerated type to get to each string?
    Easy way to do this is to use GetNumericInfo.vi, part of the Variant library, found in vi.lib\utility\VariantDataType\GetNumericInfo.vi.  Wire your enumeration to the Variant input; one of the outputs is an array of the strings in the enumerated type.
    The more complicated way is a for loop, in which you typecast the iterator terminal value to the enumerated type, then use Format Value.  You can get the maximum value of the enumeration by casting 0 to the enumerated type, then decrementing; cast that back to a numeric and add one to get the right value to wire to the N terminal.
    EDIT: just thought I'd add, since RavensFan's reply popped up while I was writing mine - I don't like the Strings[] approach because it doesn't work on RT targets, and I lost a lot of time once due to this trying to figure out why my code wouldn't run properly on an RT system but worked great on my development computer.

  • How do I Display a string from a servlet into a JSP Page???? NEED HELP!!!!

    Hi guys,
    How do I Display a string from a servlet into a JSP Page...
    Ive tried so many bloody things!.....
    Simply.
    I get text from JSP. The servlet does what ever it does to the string.
    Now. Ive create sessions and bean things,.... how the hell do I display it in a text box... I can display on the screen.. but not in the text box.!!!
    please help!!!

    hmmm, I dont really like using JSP programming, u should be using JAVA..
    the way to do it is:
    Call and cast to the bean like this:
    <%@ page import="beans.*" %>
    <% //cast to bean get request create object
    userNameBean u= (userNameBean) request.getSession().getAttribute("userNameBean");
    then... all you do is call it like this:
    <input type="text" name="firstName" value="<%= u != null? u.getFirstName(): "" %>">
    this is the real programmers way,,,
    chet.~

  • How to Plot number and string in one row (data logger counter) ?

    hi all i made data log quantity using Digital Counter via modbus to monitoring quantity and reject that has and Name Operator, Machine and Part Number.
    i have problem about plot the number & string in one row, as shown on the picture below :
    how to move that string on one row ? i attach my vi.
    Thanks~
    Attachments:
    MODBUS LIB Counter.vi ‏39 KB

    Duplicate and answered - http://forums.ni.com/t5/LabVIEW/How-to-Plot-number-and-string-in-one-row-data-logger-counter-via/m-p...

  • How can I send multiple string commands into a VISA write?

    Hi Fellow LabVIEW users
    I am very new to LabVIEW (2.5 months) so please forgive me if my lingo is not up to par.
    How can I send multiple string commands to a VISA write. For example each string command looks like this
    1) 3A00 0000 0000 FFFF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0033 (Scenario 1)
    2) 3A01 0000 0000 FFFF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0034 (Scenario 2)
    3) 3A01 0000 0000 33FF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0067 (Scenario 3).
    and so on and so forth. And there are a number of scenarios.
    Each String scenario will give a different string output which will be interpreted differently in the front panel.
    Right now I have to manually change the string commands on the front panel to give me the desired output. How can I do this without manually changing the commands i.e. hard coding each scenario into the block diagram?
    Thanks, any feedback will help.
    mhaque

    Please stick to your original post.

  • How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?

    Hi All,
    Hope to you a very happy new year,
    I have two differnt LAP 1300 and 1200 in my network and I need to add theme to the WLC,
    I successed to add one of theme by the option 60 in the DHCP pool at the Core SW,
    So my quetion is below:
    How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?
    Thanks in Advanced,
    Ahmed,

    To add to Scott's post.  Option 60 would be useful if you needed to put certain types of AP on specific controllers.  Otherwise, no real need to use it for the most part.
    Though, I do recall an issue a few years ago that some windows machines had issues getting DHCP if option 43 is being returned.
    Now, on an IOS switch, you can only configure one option 60 per DHCP scope
    HTH,
    Steve
    Please remember to rate useful posts, and mark questions as answered

  • How to search a special string in txt file and return it's position in txt file?

    How to search a special string in txt file and return it's position in txt file?

    I just posted a solution for a similar question here:  http://forums.ni.com/ni/board/message?board.id=170​&view=by_date_ascending&message.id=362699#M362699
    The top portion can search for the location of a string, while the bottom portion is to locate the position of a character.  Both can search for a character.
    The position of the character within the file is displayed in the indicator(s).
    R

  • How to determine the connection string to a SQLite database, in C# code

    Hello. I'm trying to figure out how to specify the connection string to a SQLite database, I would like to access using the following code:
    string connectionString = null;
    SqlConnection connection;
    SqlCommand command;
    SqlDataAdapter adapter = new SqlDataAdapter();
    DataSet ds1 = new DataSet();
    string sql = "SELECT DataName, Data, Id, UserId, DateLastUpdated FROM MainTable";
    connectionString = "Data Source=C:\\SQLITEDATABASES\\SQLITEDB1.sqlite;Version=3;";
    connection = new SqlConnection(connectionString);
    try
    connection.Open();
    command = new SqlCommand(sql, connection);
    catch
    The value I assigned to the variable connectionString, in the code above, I obtained somewhere from the Internet. It does not work. I'm using Visual Studio 2013, against the file sqlite-netFx451-setup-bundle-x86-2013-1.0.96.0.exe, which
    I installed, and got from
    here.
    My application's App.config file looks as follows:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <configSections>
    </configSections>
    <connectionStrings>
    <add name="DC_Password_Saver.Properties.Settings.DC_Password_SaverConnectionString" connectionString="data source=&quot;C:\Users\patmo_000\Documents\Visual Studio 2013\Projects\DC Password Saver\DC Password Saver\DC Password Saver.db&quot;" providerName="System.Data.SQLite.EF6"/>
    </connectionStrings>
    <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
    </startup>
    </configuration>
    I tried to use the value assigned to connectionString in the XML settings above, replacing single backslash characters with double backslash characters, because the Visual Studio editor flagged them as unrecognizable, and wound up with the
    following.
    SqlDataAdapter adapter = new SqlDataAdapter();
    DataSet ds1 = new DataSet();
    string sql = "SELECT DataName, Data, Id, UserId, DateLastUpdated FROM MainTable";
    connectionString = "data source=&quot;C:\\Users\\patmo_000\\Documents\\Visual Studio 2013\\Projects\\DC Password Saver\\DC Password Saver\\DC Password Saver.db&quot;";
    connection = new SqlConnection(connectionString);
    The above code however does not work either. So again, does anyone know how I can specify in C# code, a connection string to access my SQLite database? Thanks in advance for your reply.

    What does SQLite connection strings has to do with WPF?
    You will find some valid connection strings here:
    https://www.connectionstrings.com/sqlite/
    But you cannot use the SqlConnection class to connect to a SQLite database. You will need to download and add a reference to the System.Data.SQLite library and then use the SQLiteConnection class:
    connection = new System.Data.SQLite.SQLiteConnection(connectionString);
    try
    connection.Open();
    command = new System.Data.SQLite.SQLiteCommand(sql, connection);
    catch
    Please refer to the following article for more information and an example of how to connect and read and write data from an SQLite database using C#:
    http://blog.tigrangasparian.com/2012/02/09/getting-started-with-sqlite-in-c-part-one/.
    There is contains a link where you can download the required assemblies.
    Hope that helps.
    Please remember to mark helpful posts as answer to close your threads and then start a new thread in an approproate forum if you have a new question.

  • Splitting and type casting huge string into arrays

    Hello,
    I'm developing an application which is supposed to read measurement files. Files contain I16 and SGL data which is type casted into string. I16 data is data from analog input and SGL is from CAN-bus data in channel form. CAN and analog data is recorded using same scan rate.
    For example, if we have 6 analog channels and 2 CAN channels string will be (A represents analog and C represents CAN):
    A1 A2 A3 A4 A5 A6 C1 C2 A1 A2 A3 A4 A5 A6 C1 C2 A1 A2 .... and so on
    Anyway, I have problems reading this data fast enough into arrays. Most obvious solution to me was to use shift registers and split string in for loop. I created a for loop with two inner for loops. Number of scans to read from string is wired to N terminal of the outermost loop. Shift register is initialized with string read from file.
    First of the inner loops reads analog input data. Number of analog channels is wired to its N terminal. It's using split string to read 2 bytes at a time and then type casts data to I16. Rest of the string is wired to shift register. When every I16 channel from scan is read, rest of the string is passed to shift register of the second for loop.
    Second loop is for reading CAN channels. It's similar to first loop except data is read 4 bytes at a time and type casted to SGL. When every CAN channel from scan is read, rest of the string is passed to shift register of the outermost loop. Outputs of type cast functions are tunneled out of loops to produce 2D arrays.
    This way reading about 500 KB of data can take for example tens of seconds depending on PC and number of channels. That's way too long as we want to read several megabytes at a time.
    I created also an example with one inner loop and all data is type casted to I16. That is extremely fast when compared to two inner loops!
    Then I also made a test with two inner loops where I replaced shift register and split string with string subset. That's also faster than two inner loops + shift register, but still not fast enough. Any improvement ideas are highly appreciated. Shift register example attached (LV 7.1)
    Thanks in advance,
    Jakke Palonen
    Attachments:
    String to I16 and SGL arrays.vi ‏39 KB

    OK, there is clearly room for improvement. I did some timing and my two above suggestions are already about 100x faster than yours. A few teeaks led to a version that is now over 500x faster than the original code.
    A few timings on my rather slow computer (1GHz PIII Laptop) are shown on the front panel. For example with 10000 scans (~160kB data as 6+2) my new fastest version (Reshape II) takes 14 ms versus the original 7200ms! It can do 100000 scans (1.6MB data) in under 200 ms and 1000000 scans (15MB data) in under 2 seconds.
    I am sure the code could be further improved. I recommend the Reshape II algoritm. It is fastest and can deal with variable channel counts. Modify as needed.
    Attached is a LabVIEW 7.1 version of the benchmarking code, containing all algorithms. I have verified that all algorithms produce the same result (with the limitation that the cluster version only works for 6*I16+2*SGL data, of course). Remember that the reshape function is extremely efficient, because it does not move the data in memory. I have some ideas for further improvements, but this should get you going.
    Message Edited by altenbach on 08-05-2005 03:06 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    StringI16SGLCastingTimer.png ‏48 KB
    StringtoI16andSGLArraysMODTimer.vi ‏120 KB

  • How to Parse XML into String in BPEL?

    Hi,
    Can anyone tell me, how can I parse XML into String?
    I am taking input from File Adapter, File adapter is reading that XML.
    Then in assign activity i am using XPath expression(built functions) using XMLParser(),doTranslateToNative() etc.. many functions I have tried but XML is not getting parsed into String Variable.
    Please help me asap.
    Thanks
    Shikha

    Thanks a lot Eric.
    I am trying this, oraext:get-content-as-string('receiveInput_Read_InputVariable','body','/ns3:orders')
    but getting this error
    <bpelFault><faultType>0</faultType><subLanguageExecutionFault xmlns="http://schemas.oracle.com/bpel/extension"><part name="summary"><summary>XPath expression failed to execute. An error occurs while processing the XPath expression; the expression is oraext:get-content-as-string('receiveInput_Read_InputVariable','body','/ns3:orders'). The XPath expression failed to execute; the reason was: internal xpath error. Check the detailed root cause described in the exception message text and verify that the XPath query is correct. </summary></part><part name="code"><code>XPathExecutionError</code></part></subLanguageExecutionFault></bpelFault>

Maybe you are looking for

  • GR time not taken in MD04

    Hello Everyone, In my project an enhancement been done for running Route Determination at the time of PO save. In order to update GR time in MD04, I am updating field TERMN in EKET table at the time of PO save that finally reflect in MD04 when MRP is

  • SharePoint 2010 SQL Permission Errors

    We occasionally receive errors in the Event Log for SQL permission errors. I am not able to find what exactly is causing the issue and don't want to grant rights to something if I don't know what it is doing. There error is not specific to a particul

  • To implement bar code in print out of form script

    hi can any one tell me steps to implement the bar code for a field in  sap script layout what code should is put and process step by step quick answeres will be rewarded with points kindly let me know asap regards Arora

  • DVI to HMDI - how to make it look better?

    I am hooking up my MBP to a Sony 46" Bravia Z LCD through the HMDI connection - how can you make the external LCD look a little bit better? Seems the MBP picks up the signal and recognizes the Sony screen - but the colors don't look like my MBP scree

  • Backing up a defective MB before returning it to Apple

    I am returning my defective MB to Apple. What's the best way to backup the contents of the hard drive for installation on the new MB when it arrives? Unfortunately I had to do two archive and install procedures, which appear to have used a lot of dis