Strinig.indexOf(String str, Int fromIndex)
Hello.
In the API reference manual J2SE 5.0 (and earlyer also),
"public indexOf(String str, int fromIndex)"
is discribed such as,
| Returns the index within this string of the first occurrence of the specified substring,
| starting at the specified index. The integer returned is the smallest value k for which:
| k >= Math.min(fromIndex, str.length()) && this.startsWith(str, k)
I can't understand why str.length() is needed here.
For example,
String string = "my beautiful dream";
String str = "ea";
int fromIndex = 10;
in the case, str.ng.indexOf(str, fromIndex) returns 15, the value is what I what to get.
But,I think the smallest value k for which
| k >= Math.min(fromIndex, str.length()) && this.startsWith(str, k)
is 4, isn't it?
import junit.framework.TestCase;
* @author phinloda
* test String.indexOf
public class IndexOfTest extends TestCase {
public final void testIndexOf() {
String targetString = "my beautiful dream";
String str = "ea";
int fromIndex = 10;
int k1 = myIndexOf(targetString, str, fromIndex);
assertTrue(k1 >= Math.min(fromIndex, str.length()) && targetString.startsWith(str, k1));
int k2 = targetString.indexOf(str, fromIndex);
assertTrue(k2 >= Math.min(fromIndex, str.length()) && targetString.startsWith(str, k2));
assertEquals(k1, k2);
private int myIndexOf(String targetStr, String str, int fromIndex) {
for (int n = 0; n < targetStr.length(); n++) {
if (n >= Math.min(fromIndex, str.length()) && targetStr.startsWith(str, n)) {
return n;
return -1;
public static void main(String[] args) {
junit.textui.TestRunner.run(IndexOfTest.class);
}lastIndexOf(String str, int fromIndex) is more difficult for me.
("this.length()" is right?, but it's nonsense.)
("this.length()" is right?, but it's nonsense.)Yes, it should be this.length() and not str.length().
I don't think it's nonsense because now the empty
string always gives a non-negative index, e.g.
"string".indexOf("", 1000) returns 6...perhaps this
property is useful for some string algorithmsI think it only does this for an empty String, so it would be clearer if the docs said something about returning this.length() if str.length()==0.
Similar Messages
-
String to Int and Int to String
How can I convert a string to Int & and an Int to String ?
Say I've
String abc="234"
and I want the "int" value of "abc", how do I do it ?
Pl. help.String.valueOf(int) takes an int and returns a string.
Integer.parseInt(str) takes a string, returns an int.
For all the others long, double, hex etc. RTFM :) -
Conversion from String to int..NumberFormatException??
Hey all
I am trying to read in a file that has nothing but numbers listed one per line. I am using the bufferedReader class and reading in by line. When I check to see if the one 'string' is the same as another, it says they are the same, when really they are different. I then thought to convert the numbers to integers after reading them in, but it gives me a number format exception. My process is simple:
1) line = in.readLine();
2) int variable = Integer.valueOf(line).intValue();
This gives me the damn exception. The numbers are three digits, e.g. 333, etc. Does anybody know how I can avert this problem or achieve the result I am looking for another way? All I want is to know what numbers are listed in their, without going through by hand checking. Thankshi...try this..
1.Use filereader instead of bufferedreader..OKAY
2. OR USE...
String str = br.readLine();
use... int sanjeev = Integer.parseInt(str);
3 OR...and helloooo one thing more...how u r checking that these 2 strings r same..
get CLEAR IDEA about equals method and "==".. -
Guys/Gals,
Here's an interesting problem to ponder...
I define the following values in my class:
private String descriptorClassName = null;
private String userObjectClassName = null;
private String name = null;
I run the following piece of code as part of the constructor:
descriptorClassName = this.getClass().getName();
userObjectClassName = descriptorClassName.substring(0, descriptorClassName.indexOf("Descriptor"));
name = userObjectClassName.substring(userObjectClassName.lastIndexOf(".")+1);
The first line assigns the value of "com.foo.user.UserDataDescriptor" to descriptorClassName.
The second line assigns the value of "com.foo.user.UserData" to userObjectClassName.
The third line assigns the value of "UserData" to name.
As I step through the code, I see the first two values being set, and yet the third value for name is reported by the debugger as:
"name = null".
I added a call to log4j, which reports that that value of name has been correctly set!
This seems to be a result of the String.substing(int) call, as the call to Sring(substring(int, int) is fine.
Has anyone come accross this one before?
Does anyone have any workarounds other than:
name = userObjectClassName.substring(userObjectClassName.lastIndexOf(".")+1, userObjectClassName.length());
Cheers all.
Regards,
Chris.I've been trying to reproduce this problem and it always works perfectly. The debugger tells me that name = "UserData". I'm using JDev 3.2.2 and my project is using JDK1.2.2_JDeveloper. Here's the exact source code I'm trying.
package com.foo.user;
public class UserDataDescriptor {
private String descriptorClassName = null;
private String userObjectClassName = null;
private String name = null;
public UserDataDescriptor() {
descriptorClassName = this.getClass().getName();
userObjectClassName = descriptorClassName.substring(0, descriptorClassName.indexOf("Descriptor"));
name = userObjectClassName.substring(userObjectClassName.lastIndexOf(".")+1);
System.out.println("end of constructor");
public static void main(String[] args) {
UserDataDescriptor userDataDescriptor = new UserDataDescriptor();
null -
can n e body tell me how can i convert a String to an int
always remember to use the try/catch block with thins that throw exceptions
String gg;
int in;
try{
gg = "30";
in = Integer.parseInt(gg);
catch(NumberFormatException e){
e.printStackTrace();
}Ant -
How to read a C structure with string and int with a java server using sock
I ve made a C agent returning some information and I want to get them with my java server. I ve settled communication with connected socket but I m only able to read strings.
I want to know how can I read strings and int with the same stream because they are sent at the same time:
C pgm sent structure :
char* chaine1;
char* chaine2;
int nb1;
int nb2;
I want to read this with my java stream I know readline methode to get the first two string but after two readline how should I do to get the two int values ?
Any idea would be a good help...
thanks.
Nicolas (France)Does the server sent the ints in little endian or big endian format?
The class java.io.DataInputStream (with the method readInt()) can be used to read ints as binary from the stream - see if you can use it. -
Please help me with my code (has conversion from string to int)
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Test3 extends MIDlet implements CommandListener
{ Form mForm;
Command mCommandQuit;
Command mCommandItem;
TextField input,prime1,prime2,prime3,output;
Display mDisplay;
int i,j=0,k1,k2,p,q,b;
//int [] current=new int [1000];
String mstring,a="";
String [] temp=new String [1000];
public void startApp()
{System.out.println("startApp");
mForm=new Form("RSA Encryption");
mCommandQuit=new Command("QUIT",Command.EXIT,0);
mCommandItem=new Command("ENCRYPT",Command.ITEM,0);
mForm.append("Enter text:\n");
input=new TextField(null,"",100, TextField.ANY);
mForm.append(input);
mForm.append("Enter first prime number(p):\n");
prime1=new TextField(null,"",100, TextField.ANY);
mForm.append(prime1);
mForm.append("Enter second prime number(q):\n");
prime2=new TextField(null,"",100, TextField.ANY);
mForm.append(prime2);
mForm.append("Enter d:\n");
prime3=new TextField(null,"",100, TextField.ANY);
mForm.append(prime3);
mForm.addCommand(mCommandQuit);
mForm.addCommand(mCommandItem);
mDisplay=Display.getDisplay(this);
mDisplay.setCurrent(mForm);
mForm.setCommandListener(this);
public void pauseApp()
{System.out.println("pauseApp");
public void destroyApp(boolean unconditional)
{System.out.println("destroyApp");
public void commandAction(Command c, Displayable d)
{System.out.println("commandAction");
if(c==mCommandQuit)
notifyDestroyed();
else if(c==mCommandItem)
{p = Integer.parseInt(prime1.getString());
q = Integer.parseInt(prime2.getString());
b = Integer.parseInt(prime3.getString());
//breaking up of big string into ints
mstring=input.getString();
temp[0]="";
for(i=1;i<mstring.length();i++)
{if (mstring.charAt(i) == ' ')
{j++;
temp[j]="";
else
{temp[j]=temp[j]+mstring.charAt(i);
mForm.append("\n\nThe array is:\n");
for(i=0;i<temp.length && temp!=null;i++)
{k1=Integer.parseInt(temp[i]); ***********************
k2=k1;
for(j=1;j<b;j++)
{k1=k1*k2;
k1=k1 %(p*q);
k2=k1 %(p*q);
a=a+new Character((char)k2).toString();
output=new TextField(null,a,100, TextField.ANY);
mForm.append(output);
}hi
this code basically takes an input of string like " 179 84 48 48 155 " (with spaces)
then it creates smaller strings in an array like "179","84","48","48","155" without the spaces
then it creates int values 179,84,48,48,155 and finally after some math functions it prints the corresponding letters.
the problem is that it is not printing the letter because of some exceptions-->java.lang.NumberFormatException .it comes in the line where i have put stars
could anybody please help me print the lettersthanks for all ur help guys, but me and my team member solved it on our own. here is the new code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Test3 extends MIDlet implements CommandListener
{ Form mForm;
Command mCommandQuit;
Command mCommandItem;
TextField input,prime1,prime2,prime3,output;
Display mDisplay;
int i,j=0,l,k1,k2,p,q,n,b;
String mstring,a = "";
String [] temp=new String [1000];
public void startApp()
{System.out.println("startApp");
mForm=new Form("RSA Encryption");
mCommandQuit=new Command("QUIT",Command.EXIT,0);
mCommandItem=new Command("DECRYPT",Command.ITEM,0);
mForm.append("Enter text:\n");
input=new TextField(null,"",100, TextField.ANY);
mForm.append(input);
mForm.append("Enter first prime number(p):\n");
prime1=new TextField(null,"",100, TextField.NUMERIC);
mForm.append(prime1);
mForm.append("Enter second prime number(q):\n");
prime2=new TextField(null,"",100, TextField.NUMERIC);
mForm.append(prime2);
mForm.append("Enter d:\n");
prime3=new TextField(null,"",100, TextField.NUMERIC);
mForm.append(prime3);
mForm.addCommand(mCommandQuit);
mForm.addCommand(mCommandItem);
mDisplay=Display.getDisplay(this);
mDisplay.setCurrent(mForm);
mForm.setCommandListener(this);
public void pauseApp()
{System.out.println("pauseApp");
public void destroyApp(boolean unconditional)
{System.out.println("destroyApp");
public void commandAction(Command c, Displayable d)
{System.out.println("commandAction");
if(c==mCommandQuit)
notifyDestroyed();
else if(c==mCommandItem)
{p = Integer.parseInt(prime1.getString());
q = Integer.parseInt(prime2.getString());
b = Integer.parseInt(prime3.getString());
n=p*q;
//breaking up of big string into ints
mstring=input.getString();
temp[0]="";
for(i=1;i<mstring.length();i++)
{if (mstring.charAt(i) == ' ')
{j++;
temp[j]="";
else
{temp[j]=temp[j]+mstring.charAt(i);
l=j;
mForm.append("\n\nThe result is:\n");
for(i=0;i<l;i++)
{k1=Integer.valueOf(temp).intValue();
k2=k1;
for(j=1;j<b;j++)
{k2=k2*k1;
k2=k2 %n;
k1=k2 %n;
a=a+new Character((char)k1).toString();
output=new TextField(null,a,100, TextField.ANY);
mForm.append(output); -
How to convert String to int in JSP?
Hi,
I set a session attribute in Servlet and want use it in JSP, How can I convert it to int or Integer?
the line in my code doesn't work:
int quantity=(int)session.getAttribute("vehiclequantity") ;
Thanks in advance.
Wolf
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<HTML>
<HEAD>
<TITLE>Using the for Statement</TITLE>
</HEAD>
<BODY>
<H1>Using the for Statement</H1>
<%=session.getAttribute("vehiclequantity") %>;
<%
int loopIndex;
int quantity=(int)session.getAttribute("vehiclequantity") ;
out.println(quantity);
for (loopIndex = 1; loopIndex <=2; loopIndex++) {
out.println("This is iteration number "
+ loopIndex + "<BR>");
%>
</BODY>
</HTML>Learning how to read errors and understand them will help you solve your problems quicker by yourself... So lets take a look at the error and classes involved...
The error says:
"Cannor Resolve Symbol: method valueOf(java.lang.Object) in the class java.lang.Integer" and gives you line line where the error occurs: Integer quantity = Integer.valueOf(session.getAttribute("vehiclequantity"));
Now, if we look at the API for the Integer we notice that are are only two valueOf methods: valueOf(java.lang.String s) and valueOf(java.lang.String s, int radix). Not valueOf(java.lang.Object) method.
Now we look at the getAttribute(java.lang.String name) method of HttpSession we see that the method returns a java.lang.Object. Now, you know you put a java.lang.String into that attribute, but the get method returns an Object. This is because you could have put any object in there, an Integer, a String, or some other class instance. But you know it is a String, so you can cast the returned value to a String, so that you will be calling the valueOf(java.lang.String s) method of Integer with the Object returned from the HtttpSession's getAttribute(java.lang.String name) method:
Integer quantity = Integer.valueOf((String)session.getAttribute("vehiclequantity")); -
Kinda urgent please help pass strings to doubles and strings to ints
Need to know how to pass strings to doubles and strings to ints
and to check if a string is null its just if (name == null;) which means black right?
like size as a string and then make the string size a doublecupofjava666 wrote:
Need to know how to pass strings to doubles and strings to ints
and to check if a string is null its just if (name == null;) which means black right?
like size as a string and then make the string size a doubleThink he means blank.
Check the Wrapper classes (Double, Integer) in the api.
parseInt() parseDouble() both take a string and return a primitive.
String s = null;
if(s == null) should do the trick!
Regards.
Edited by: Boeing-737 on May 29, 2008 11:08 AM -
Problem with String to Int conversion
Dear Friends,
Problem with String to Int conversion
I am having a column where most of the values are numeric. Only 4 values are non numeric.
I have replaces those non numeric values to numeric in order to maintain the data type.
CASE Grade.Grade WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade END
This comes the result as down
Grade
_0_
_1_
_10_
_11_
_12_
_13_
_14_
_15_
_16_
_17_
_18_
_19_
_2_
_20_
_21_
_22_
_23_
_24_
_3_
_4_
_5_
_6_
_7_
_8_
_9_
Refresh
Now I want to convert this value to numeric and do some calculation
So I changed the formula as below
cast (CASE Grade.Grade WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade END as INT)
Now I get the following error
View Display Error
_ Odbc driver returned an error (SQLExecDirectW)._
Error Details
Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
_State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 17001] Oracle Error code: 1722, message: ORA-01722: invalid number at OCI call OCIStmtFetch. [nQSError: 17012] Bulk fetch failed. (HY000)_
SQL Issued: SELECT cast ( CASE Grade.Grade WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade END as Int) saw0 FROM "Human Capital - Manpower Costing" WHERE LENGTH(CASE Grade.Grade WHEN 'E1' THEN '20' WHEN 'E2' THEN '21' WHEN 'E3' THEN '22' WHEN 'E4' THEN '23' ELSE Grade.Grade END) > 0 ORDER BY saw_0_
Refresh
Could anybody help me
Regards
Mustafa
Edited by: Musnet on Jun 29, 2010 5:42 AM
Edited by: Musnet on Jun 29, 2010 6:48 AMDear Kart,
This give me another hint, Yes you are right. There was one row which returns neither blank nor any value.
I have done the code like following and it works fine
Thanks again for your support
Regards
Code: cast (CASE (CASE WHEN Length(Grade.Grade)=0 THEN '--' ELSE Grade.Grade END) WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' when '--' then '-1' ELSE Grade.Grade END as Int) -
Checking a value...String OR int
checking a value...String OR int
how to check a given value whether it is a String OR int
if(jTextField1.getText()...) is a String
System.out.println("String");
else //if it an int
System.out.println("int");
How can i check this...
pls,tell.getText of JTextField ALWAYS returns a String.
You can do this to see if it could be interpreted as an int:
String theText = jTextField1.getText();
try
int theInt = Integer.parseInt(theText);
System.out.println("int");
catch (NumberFormatException ex)
System.out.println("String");
}If it isn't in a form that can be parsed as an int, you will get an exception and the catch block will get executed. -
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) -
String str = " Select ? , ...
Hi ,
I have a query for which I need to use PreparedStatement .The query runs likes this :-
String str = " Select ? , ename from emp where deptno ? ";
The values of ? need to be assigned dynamically.
But I cannot create Prepared Statement from this query .
If you have got answer to your questions can you inform me at
Thanks in advanceNo, and you can't use a PreparedStatement where you have ? for the table name either. The database can't prepare it because it doesn't know what fields you will be asking for. So you will have to use a Statement and generate the SQL with string calculations. Sorry.
-
-- what's the difference bet String str="My String"; to this
String str=new String("My String");Its a subtle one. Its also been asked a hundred times before :-)
When a java class is compiled it "interns" all the Strings it can find.
Anywhere that you use that string, gets replaced with a reference to that string.
So the first gets a reference to the interned String.
The second creates a new String, using the interned String as an argument - results in reserving new memory.
Take this code:
String str1 = "My String";
String str2 = "My String";
String str3= new String("My String");In effect the compiler turns it into something like this:
String internedString = "My String"
String str1 = internedString;
String str2 = internedString;
String str3 = new String(internedString);So initially, it only stores "MyString" once, and all your String variables point at that same memory space. As Strings are immutable in java (the contents never change) this is safe to do. str3 creates a NEW String, which reserves new memory, and copies the contents of internedString into it.
So
str1 == str2 (they point to the same bit of memory)
str1 != str3 (str3 created a new String, so is in new memory)
str1.equals(str3) (the contents of the strings are the same)
Hope this helps,
evnafets -
Javascript, string to int
Dear Sir:
I try to convert string to int in flash javascript:
temp="120";
temp2="140";
temp3=int ( temp );
but I got a message "int is not a function", can somebody tell me how to do this?
also, what if I want convert number back to string?
thanks a lot!use:
temp="120";
temp2="140";
temp3=Number ( temp );
// to convert to a string, use:
var temp4:String=String(temp3);
// or
var temp5:String=temp3.toString();
Maybe you are looking for
-
Site2pstoretoken associated URL for Oracle SSO
Hi, My login app works fine except for I need to determine the destination before the app does a submit to /sso/auth. My understanding is that the site2pstoretoken does this. The problem is that it looks like it is stored somewhere in a database or e
-
SSIS Package No longer runs after changing Service to Domain user
Hello, I changed the SQL Agent/SQL Service owner on our SQL 2008r2 Server and one of the jobs started to fail with the following message: " Description: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005. An
-
After upgrading software music will not play
I upgraded the iOS software to the 6.1.3 version and now everytime I try to play music it will shuffle through the playlist and never play anything. Could someone please tell me how to fix this? I restored the ipod back to before the update was done
-
Constant values and encapsulation
Hi All, lookat the code below: class Test{ public static final int flag = 10; Public static void main(String args[]) System.out.println(i); }here the constant value i is used inside the same class. Now generally, we use to make separate java file for
-
How to configure Report Services
Hello I have created an application comprise of few web forms and reports in both web & page formats. Now i want to put these forms on local intranet, so that users can access the application using internet browser. Need step by step guidance in laun