Inserting numbers in strings
Back in the good old days of C programming we could use printf to insert a number into a printed string at run time. Just stick "%i" or "%f" in the string where you want the number to appear.
Is there any way to do something similar with Java internationalization? Let's say I want to print out an error message with an integer stuck somewhere in the middle. The position where that integer needs to be inserted can very based on the language. I can create two different Java string resources, one before the number and one after, and then string them together in code. But that seems a little awkward. Is there a better way?
I heard a rumor that "printf" type functionality might be coming in a future JDK release so maybe we just have to wait.
First of all, you SHOULD NOT create two string resources and stick them together - that makes the localisation process very difficult since the localisers can take the two strings separately and not realise they're meant to be together; and what happens if you have 3 variables you want to put in a string? That gets far more complicated.
The class you want to use is java.text.MessageFormat. That takes a 'pattern' and an array of objects and inserts the objects into the pattern in the places that pattern specifies.
Here's an example. Say you want a message to say 'There are X files in the folder called Y' (obviously this needs to be localised). You would store the following pattern as one piece of text in a resource bundle:There are {0} files in the folder called {1}Note the curly braces containing numbers - these are the places where the variables will be inserted.
To use the message, you retrieve it from the resource bundle (I assume you know how to do this) and ask MessageFormat to insert the variables, like this:String pattern = <get the pattern from the ResourceBundle>;
Integer numFiles = new Integer(1234);
String folderName = "MyFolder";
Object[] variables = new Object[] { numFiles, folderName };
String message = MessageFormat.format(pattern, variables);This will format the given pattern using the default Locale.
It may seem vastly more complicated than C's printf, but it's also more flexible and powerful - take a look at the API docs for MessageFormat for more information.
Hope this helps.
Alistair
Similar Messages
-
When I insert numbers in master it has a "1." next to to A
When I insert numbers in master it has a "1." next to "A" and it shows in all my pages, how can I hide it?
Sounds like the paragraph contianing the marker may be styled as a numbered list...
-
Problem when inserting "Thai language" string to MS Access with JSP
Dear sir,
I have the problem when try to insert "Thai langusge" string to MS access database through JDBC in JSP page.
The JSP page is shown in the following.
<HTML><HEAD><TITLE>Personalt Information</TITLE>
<%@ page contentType="text/html; charset=MS874" %>
<%@ page import = "java.io.*" %>
<%@ page import = "java.lang.*"%>
<%@ page import = "java.sql.*"%>
<%
Connection dbconn,conn;
ResultSet results;
String sql;
Statement stmt;
// Creating a conection with a database
String url = "jdbc:odbc:bg3hrDB"; // the database file.
//Statement stmt;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbconn = DriverManager.getConnection(url);
stmt = dbconn.createStatement();
ResultSet rs;
%>
%>
<%
String code=new String(request.getParameter("code").getBytes("ISO8859_1"),"MS874");
String status=new String(request.getParameter("status").getBytes("ISO8859_1"),"MS874");
String fname=new String(request.getParameter("fname").getBytes("ISO8859_1"),"MS874");
sql = "INSERT INTO employee VALUES (' "+ code +" ',' "+ status +" ',' "+ fname +" ')";
stmt.executeUpdate(sql);
%>
<%=fname%> //In this line, "fname" can show "Thai" correctly
But after inserted to database, the record in Access was always show "?????" instead of "Thai"......
How can i solve this?
Thank you for your kindness in advances.
Yongyos K.It's a pain in the butt, but you'll have to write your own character set conversion to handle the problem. Check out the link shown below (just replace BIG5 in the example with MS874):
http://www.geocities.com/siufai6/java/JDBC_Chinese.html
;o)
V.V. -
I downloaded the latest operating system for my iPhone 5. It worked fine for about two minutes then the phone requested a password number to continue. Each time I inserted numbers, which were incorrect, the phone would lock up for a certain period of time. Now, it says “iPhone is Disabled”. It said to “Connect to iTunes” which I did, but iTunes does not recognize my phone. If I scroll the face to the right, it goes to the phone number face and says, "No Service". Can I do something to make the phone work?
Forgot passcode for your iPhone, iPad, or iPod touch, or ...
-
Php form field inserts return empty string
hello -
i've created a form that has multiple inserts. it inserts the data fine if i manually parse the data to it but when i use the form to test the inserts it errors out.
i've used echo $_post variable and the variable is their. but its not being inserted into the database.
it says that the string cannot be null?
where do i go from here for debugging?
thanks, in advance for your help!
theo werntz iiI've tried entering data but it doesn't insert i've change the column type to longblob from varchar and it still doesnt insert.
here is my code: ignore the numbers and line ending with $
1 <?php require_once('Connections/upics.php'); ?>$
2 <?php$
3 if (!function_exists("GetSQLValueString")) {$
4 function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") $
5 {$
6 if (PHP_VERSION < 6) {$
7 $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;$
8 }$
9 $
10 $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);$
11 $
12 switch ($theType) {$
13 case "text":$
14 $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";$
15 break; $
16 case "long":$
17 case "int":$
18 $theValue = ($theValue != "") ? intval($theValue) : "NULL";$
19 break;$
20 case "double":$
21 $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";$
22 break;$
23 case "date":$
24 $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";$
25 break;$
26 case "defined":$
27 $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;$
28 break;$
29 }$
30 return $theValue;$
31 }$
32 }$
33 $
34 $
35 $uname="guest";$
36 $uname_id = '1' ;$
37 $pt="pictures";$
38 $picPath="pt/img_0.gif"; $
39 $picSize="1024";$
40 $
41 $editFormAction = $_SERVER['PHP_SELF'];$
42 if (isset($_SERVER['QUERY_STRING'])) {$
43 $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);$
44 }$
45 $
46 if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {$
47 $
48 $insertSQL_0 = sprintf("INSERT INTO album (album_id, album_nm, album_dt, album_pt) VALUES ( %s, %s, curdate(), '$pt')",$
49 GetSQLValueString($_POST['album_id'], "int"),$
50 GetSQLValueString($_POST['album_nm'], "text"),$
51 GetSQLValueString($_POST['album_dt'], "date"),$
52 GetSQLValueString($_POST['album_pt'], "text"));$
53 $
54 $insertSQL_1 = sprintf("insert into album_has_user (album_album_id, user_user_id, user_admin_id) values (last_insert_id(), '$uname_id', '$uname_id')",$
55 GetSQLValueString($_POST['album_has_user'], "int"),$
56 GetSQLValueString($_POST['user_user_id'], "int"),$
57 GetSQLValueString($_POST['user_admin_id'], "int"),$
58 $
59 $insertSQL_2 = sprintf("insert into title (title_id, title_title, title_dt, album_album_id, title_memo) values (last_insert_id(), %s, curdate(), last_ins ert_id(), %s)",$
60 GetSQLValueString($_POST['title_id'], "int"),$
61 GetSQLValueString($_POST['title_title'], "text"),$
62 GetSQLValueString($_POST['title_dt'], "date"),$
63 GetSQLValueString($_POST['album_album_id'], "int"),$
64 GetSQLValueString($_POST['title_memo'], "text"));$
65 $
66 $
67 $insertSQL_3 = sprintf("insert into picture (picture_id, picture_dp, picture_sz, picture_df, title_title_id) values (last_insert_id(), '$picPath', '$pic Size', 'N', last_insert_id())", $
68 GetSQLValueString($_POST['picture_id'], "int"),$
69 GetSQLValueString($_POST['picture_dp'], "text"),$
70 GetSQLValueString($_POST['picture_sz'], "text"),$
71 GetSQLValueString($_POST['picture_df'], "text"),$
72 GetSQLValueString($_POST['title_title_id'], "int"));$
73 $
74 echo $_POST['title_title'];
75 $
76 //insert users album if null$
77 mysql_select_db($database_upics, $upics);$
78 $Result1 = mysql_query($insertSQL_0, $upics) or die(mysql_error());$
79 $
80 //insert users many data$
81 mysql_select_db($database_upics, $upics);$
82 $Result2 = mysql_query($insertSQL_1, $upics) or die(mysql_error());$
83 $
84 //insert users title and comments $
85 mysql_select_db($database_upics, $upics);$
86 $Result3 = mysql_query($insertSQL_2, $upics) or die(mysql_error());$
87 $
88 //insert users picuter path$
89 mysql_select_db($database_upics, $upics);$
90 $Result4 = mysql_query($insertSQL_3, $upics) or die(mysql_error()); $
91 $
92 $insertGoTo = "picture_edit.php";$
93 if (isset($_SERVER['QUERY_STRING'])) {$
94 $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";$
95 $insertGoTo .= $_SERVER['QUERY_STRING'];$
96 }$
97 header(sprintf("Location: %s", $insertGoTo));$
98 }$
99 ?>$
100 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">$
101 <html xmlns="http://www.w3.org/1999/xhtml">$
102 <head>$
103 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />$
104 <title>Untitled Document</title>$
105 </head>$
106 $
107 <body>$
108 <form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">$
109 <table align="center">$
110 <tr valign="baseline">$
111 <td nowrap="nowrap" align="right">Album Name:</td>$
112 <td><input type="text" name="album_nm" id="album_nm" value="default" size="32" /></td>$
113 </tr>$
114 <tr valign="baseline">$
115 <td nowrap="nowrap" align="center">Title:</td>$
116 <td><input name="title_title" id="title_title" type="text" value="" size="32" /></td>$
117 </tr>$
118 <tr valign="baseline">$
119 <td nowrap="nowrap" align="center">Date:</td>$
120 <td><input name="title_dt" id="title_dt" type="text" value="" size="32" /></td>$
121 </tr>$
122 <tr valign="baseline">$
123 <td nowrap="nowrap" align="center">Comments:</td>$
124 <td><textarea name="title_memo" cols="32" id="title_memo"></textarea></td>$
125 </tr>$
126 <tr valign="baseline">$
127 <td nowrap="nowrap" align="right"> </td>$
128 <td><input type="submit" value="Insert record" /></td>$
129 </tr>$
130 </table>$
131 <input type="hidden" name="album_id" value="" />$
132 <input type="hidden" name="album_dt" value="" />$
133 <input type="hidden" name="album_pt" value="" />$
134 <input type="hidden" name="MM_insert" value="form1" />$
135 </form>$
136 <p> </p>$
137 </body>$
138 </html>$
this is echo: this is the error:
default Column 'title' cannot be null
thanks in advance for you help -
Inserting a PCL string in java Document for paper source control
Got a printer issue here.
I need to set the source printer tray from within the document using PCL because I am printing to a network printer and the driver that is being used always defaults the source tray to the printer default.
I am inserting the String right at the beginning of the document like so:
document.insertString(0, "\u001B&l2H", null);
The "\u001B" is the ASCII escape character used by the control sequence and the "&l2H" is the PCL code for the Manual tray. This does insert the string into the document but when the ,prn file is created (print to file) it does not use the inserted value.
The document type is text/html and I am 'Printing to file' using:
aJobAttrs.add(new javax.print.attribute.standard.Destination(new java.net.URI("file:///C:/temp/out.prn"))); as suggested in another forum. The .prn file that is persisted however still sets the tray to the printer default (&l7H).
Anyone go any suggestions?
Ps The MediaTray.MANUAL does not work because the network print driver overwrites it.No, I does not set the print tray on the .prn file persited by the code. It would appear that the default tray (&l7H) is not overwritten with the tray I set in my document.
It may have something to do with the escape characters? -
How to insert numbers i sms, nokia 6303 Classic
I used to have the Nokia 6300. When writing an sms it was possible to "insert number" when choosing Options. Where is that option in the Nokia 6303 Classic? It is often one need to insert a number in a text message so it ought to be simple?
How do you know which solution the OP as asking for? Pressing and holding the key is more convenient for inputting short numbers because it takes as long to change the keypad mode from alphabetical to numbers and back again.
The solution you require is even easier, press the * key and select number mode but you have to switch back to alpha mode once you are done.
You could try Adobe Reader LE. V 1.5 is free 2.5 you have to pay for. It thought V1.5 comes with all S60 Nokias. If it does not then try looking for it at the www.adobe.com
Message Edited by cjlim on 28-Dec-2009 09:20 AM -
How to insert text to string in c3
hi
we have file name with extension ,now we want add some name to the file name
EX: Testdocument.doc
now we want Testdocument123.doc
How to add 123 before extension(.)
i am using this code
string Val="123";
string FileName = filename.Insert(0, Val);
Out Put is:123Testdocument.docHi PS_L,
You can get the last index of ".", and use that with filename.Insert as a point in the string to insert the new text.
string Val="123";
string FileName = filename.Insert(filename.LastIndexOf("."), Val);
Regards, Matthew
MCPD | MCITP
My Blog
View
Matthew Yarlett's profile
See my webpart on the TechNet Gallery that allows administrative users to upload, crop and format user profile photos. Check it out here:
Upload and Crop User Profile Photos -
TO_NUMBER function on varchar2 column with numbers and strings
I need to create a column in a view that converts a varchar2 column data to number. The problem is that some
of the data have strings and some numbers. I get "ORA-01722: invalid number" error when Oracle tries to covert
strings (e.g. 'ABCD') to number. What I need is to get a NULL value if the data is an invalid number.
How can I rewrite the following to get NULL value is a string is invalid number?
select to_number('abcd') numberColumn
from dual
thanx
AlfredSQL> select * from test_char_num;
ALPHA_NUM
ABC
DEF
123
234
A12
SQL> select decode(NVL(length(trim(translate(alpha_num, '1234567890', ' '))), 0),
2 0, alpha_num, 'NULL') new_alpha_num
3 from test_char_num;
NEW_ALPHA_
NULL
NULL
123
234
NULLP.S I am printing 'NULL' just to show the result, Please replace the 'NULL string with NULL value in SQL.
Thx,
Sri -
Allow operator to insert tabs in string control
I'm trying to allow an operator to insert tabs in a string control with the keyboards tab button. Nothing happens when the tab button is pushed. I tried Skipping the Control in Key Navigation but that didn't work. This is LV 6.1.
6.1 does not have filter events (where you can discard the tab click), but you can use the event structure with the key down event and if you detect that the tab was clicked you can add a tab to the string programmatically and then use the Key Focus property to set the focus back to the string. I think you might be able to play with the text properties to get the cusor to the end.
Of course, you can also use another key and simply tell the operators not to click tab, but that would make for an ackward user experience.
Try to take over the world! -
Extraction of Numbers from string in oracle
Dear All,
I have a AplhaNumeric field in my source table which holds the string with numbers and caharcters .i need to extract only numbers and to load into the target table which of number type.
can any one suggest me about how to do this?
regards
kumarHi ,
I have a table called smitems with column smitmqtyremarks which holds alpha numeric characters .nearly 180 records exists in this table.
i need extract numbers for this field and load into my target tables.
here i am giving sample rows for this field :
smitmqtyremarks
13 قطعة
4 لحاف
31 قطعة
120 قطعة
57 قطعة
110 قطعة
127قطعة
169 قطعة
12 مفرش
10 مفارش
110 قطعة
170 قطعة
20 خرطوشة
28 قطعة
60قطعة
70 قطعة
80 لعبة
70 قطعة
20 قطعة
60 قطعة
50 قطعة
10 رولات
4 رولات
35 دسته
50دستة
7 رول
3 اثواب قماش
خمسة خرطوشة سجائر
50 جاكت حريمى ورجالى
10 رول اقمشة 4 دسته
420 جوارب اطفال
60 خرطوشة سجائر
12 رول
15 خرطوشة
110 علبة
45 قطعة
40 قطعة
44 قطعة
22 قطعة
3 خرطوشة
468 قطعة
38 قطعة
80 رول قماش
2 رول
6 رول اقمشة
13 رول اجنبى الصنع
100 دسته صينى الصنع
18 رولات ملابس
10دسته
90قطعة
33 قطعة
39 قطعة
42 قطعة
300 ايشارب
500 قطعة
19000 ك 0ج
607 قطعة
24 قطعة
45 قطعة
40 اروسه
5 رول اقمشة اجنبية الصنع
75 قطعة
5 قطعة
4 رول
26 قطعة
50قطعة
105 قطعة
650 جرام
65 قطعة
50 خرطوشة
4 خرطوشة
80 قطعة
100 بنطلون
500 قطعة
40 قطعة
42قطعة
1 خرطوشة
14 قطعة
80 قطعة
7 خرطوشة سجائر
230 لمبة
50 قطعة
50قطعة تليفون
14 كرتونة
4 كرتونة احذية
17 كرتونة خزف
22 لحاف
16كرتونة ادوات صحية
8كرتونة
28 كرتونة
2كرتونة
15كرتونة
115 قطعة
6448
1937قطعة
1937 قطعة
2628كجم
6.980طن
9 كرتونة
18 شفاط
صواميل حديد
3كرتونة +20 قطعة
39.480طن ق.غ سيارات
25كرتونة مصنوعات خزفية
50بنطلون
8 كرتونة كلبسات
20كرتونة اكسسوار حريمى
279كرتونة لحوم
38 اطار كاوتش
10كرتونة
4كرتونة
10كيلو
عدد5 ماكينات
41سيارة
سيارة
90 قطعة ملابس
22250كجم
1793كجم
1371كرتونة زجاج
مستندى
252شاشة
5كرتونة
320قطعة
45خرطوشة
98 قطعة
10لفات
25كجم
320كجم
5كراتين
47طرد
50قطعة
117كجم
1200 قطعة ملابس
5كجم
75جهاز
40قطعة
5كراتين
10كجم
250ق
200ق
200 توب
20لفة
30لفة
2دستة
95قطعة
70قطعة
57523طن طلمبات مياه
43732كجم
755كرتونة
10.645طن
1537طرد
11751كجم
مكبس
77426.80متر
2600قطعة
339طن
15120كجم
مختلفة
267طرد
1200كجم
189عبوة
499كرتونة
10000كجم
960طرد
15.770كجم
111قطعة
174طرد
22000كجم
473000علبة
6720كجم
145خرطوشة
2500طن
3660كجم
27824كجم
8682كجم
14000كجم
6400كجم
133كرتونة
2738كجم
the characters are in arabic here.
hope it clears my issue.
please suggest me the right query for this to get only numbers
thanks
kumar -
Fixed-length numbers and strings
Hello,
I have to make a critical decision about API usage. I would be grateful if some of you could share their experiences. This will help me make an informed decision and avoid potential trouble further down the line.
I have to use fixed-length integer numbers and fixed-length strings such as for example:
-A string that is exactly 5-letter long (no longer and no shorter than 5 letters). e.g. "abcde"
-A number that is exactly 8-digit long (no longer and no shorter than 8 digits). e.g. "12345678"
Ideally I would get some sort of exception when the "container" for the letters or digits contains less or more than what the spec says.
I am not sure which classes or primitives could meet my needs. As far as the fixed-length string is concerned I initially thought of using a array of chars but an array of chars is not that easy to manipulate and contains "garbage" until you explicitely fill it in with data. I'd rather some sort of class.
Can anyone please advise me?
Thanks in advance,
Julien.Why not use the same thing like in the case of the String
/**Warning: this is an example and not very good design.*/
public class FixedInteger {
private int min, max;
private int value;
public int getValue() { return value;}
public void setValue(int v) {
if (v >= min && v < max) {
throw new Exception();
value = v;
/**ex. min = 10000, max = 100000 for 5 digit numbers*/
public FixedInteger(int min, int max, int value) {
this.min = min; this.max = max;
setValue(value);
}You can do tricks like convert it to immutabla like the String and Integer class in the Java Api
Edited by: szgy on Oct 5, 2007 2:22 PM -
Even after deleting the string "Counting to five: one 2 three 4. five." from the string control and replacing it with another string the original string returns after the VI is saved then reopened. Where is this string data coming from? I've attached a copy of the library function. I've been able in my application to get around the problem by replacing the string control with a string constant. But I'm still curious as to what's going on.
Thanks,
Chuck
Solved!
Go to Solution.
Attachments:
Extract Numbers Test.vi 9 KBChuck,
String control has been set to default with the string you are seeing. To change this, enter the new string, right click the control and select
Data Operations>>Make Current Value Default
Now save your vi. -
Inserting numbers with ','
Hello people
I'm trying to update using execute immediate. but when I do the update, I got ORA-01747 and I know why:
My values are with ',' like 13,2345 then I get the string to update (DBMS OUTPUT):
UPDATE TF_MEDIA_PPM SET DW_LAST_UPD = SYSDATE , MEDIA_PPM_ATRIBUTO = ,2001004, TRES_SIGMA_ATRIBUTO = ,4087381, SEIS_SIGMA_ATRIBUTO = ,6173758 WHERE MEDIA_PPM_SEQ = 7145432
And the ',' is causing the error...
How can I solve this ? someone have a clue ?
ThnksHi,
MrTiberio wrote:
How can I solve this ? someone have a clue ?You could use the builtin conversion function to_number specifying your nls_numeric_characters :Scott@my11g SQL>create table t (id integer, n number);
Table created.
Scott@my11g SQL>insert into t values (1,null);
1 row created.
Scott@my11g SQL>update t set n=to_number(',0123456','fm9999999999D999999999','nls_numeric_characters='', ''') where id=1;
1 row updated.
Scott@my11g SQL>select * from t where id=1;
ID N
1 .0123456 -
Separation of Numbers from string
Hi All,
In my project i have a requirement where i need to remove the numerical values from the given string ...
For ex My input:CLWMEK0299
Expected Output : CLWMEK
Kindly please let me know ASAP... '
Thanks and regards,
Sudarshan
Edited by: Sudarshan on Mar 28, 2012 9:51 PMLook at this SQLPLUS:
SQL> select regexp_replace('123abc', '[0-9]','') from dual;
REG
abc
SQL> select regexp_replace('1a7bc', '[0-9]','') from dual;
REG
abc
SQL> create table T ( Text varchar2(20));
Table created.
SQL> insert into T values ('12abc345');
1 row created.
SQL> insert into T values ('abc12345');
1 row created.
SQL> insert into T values ('123abc');
1 row created.
SQL> commit;
Commit complete.
SQL> select regexp_replace(Text, '[0-9]','') from T;
REGEXP_REPLACE(TEXT,'[0-9]','')
abc
abc
abc
IN OBIEE front end - Suppose in the column formual of column - Prod_desc - You have to use evaluate function - like this -
EVALUATE ('REGEXP_REPLACE(%1,%2,%3)',"PRODUCTS"."PROD_DESC",'[0-9]','')
Maybe you are looking for
-
10.5.2, Screensaver Security, and Disk Utility
After installing the 10.5.2 software update, it is appropriate to use Disk Utility (DU) to repair permissions. I learned this from the fact that I had somehow lost the protection I had previously set up by requiring my password to wake up the compute
-
Hi all, Can anybody tell when wsh_new_deliveries,wsh_delivery_details & wsh_delivery assignments populate? and join condition between them ? Thanks in advance
-
Hello All - We are working on CRM 2007 authorizations. We have a scenario: a user having authorization for creating sales order ( via. CRMD_ORDER t-code). He should not have access to modify values in u201CPricesu201D & u201CConditionsu201D tabs (mea
-
Error -41110 with MS Office Report vi
I'm trying to use the MS Office Report express vi, and when I use an excel template with named ranges on more than one sheet I get the error "Error -41110 occurred at ex_RGT_Append Anything to Report.vi"..."Possible reasons: You specified invalid Wor
-
Can't import/merge libraries
I have been having this problem for a long time and I am just about to give up on trying to solve it! Ultimately - I can't merge two libraries. The process gets underway but only ever seems to get to about 80 or 90% (according to the status bar) and