Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to convert a string to an int but i take an error. Here is my code:
int foo = Integer.parseInt(ABoard[first]);
if (computerBoard[foo] != -1) {
second = computerBoard[foo];
} else {
second = board.getRandomPosition();
while (first==second) {
second = board.getRandomPosition();
}
}
I want to take a number (int) from a string array and then to take the value of this number from an int array if the value of this number isn't -1.
You need to trim off all of the whitespaces before you parse,
int foo = Integer.parseInt(ABoard[first].trim());
Or replace all non numeric digits
int foo = Integer.parseInt(ABoard[first].replaceAll("[^0-9\\-]", ""); //including 0-9 and -
In order to parse String to int you need to remove all non-numeric characters from it (assuming we are not interested in negative integers).
Here is the code to do that:
int foo = Integer.parseInt(ABoard[first].replaceAll("[^0-9]", ""));
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Given that I have a string of number, like "12354789556", I need to check that string whether has digits from 0 to 9 at least once.
Can anyone tell me whether i can express this in regex please?
If your strings contains only digits for example "123548955664789556" then try:
System.out.println(myString.chars().distinct().count() == 10);
if your string can also contain letters for example sth like "bbb1235489556fhjerfs64789556"
System.out.println(myString.replaceAll("[^\\d]", "").chars().distinct().count() == 10);
With lookaheads :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)
If you want to restrict the string to digits only in addition to making sure it contains every digit :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)\d+$
Note that a version without lookaheads would be technically possible, but would realistically have to be crafted by code as it would have to enumerate all possible orders between digits (10! = 3628800 enumerations).
You can also do it in Java like this:
boolean containsAll = true;
for (int i = 0; i < 10; i++) {
if (!str.contains("" + i)) {
containsAll = false;
}
}
return containsAll;
A non-regex way would be to loop through the String and return false if the indexOf returns -1:
static boolean checkAll(String s, char[] allNums) {
for (int i = 0; i < allNums.length; i++) {
if (s.indexOf(allNums[i]) == -1) {
return false;
}
}
return true;
}
Example
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have one read method from excel file and return me String value.
ReqQty = 2 in my excel value but it is in string and from UI side application is not allowing to enter string value in "ReqQty" it is allowing only Integer value . so here i am not able to provide value in 'ReqQty' field by 'SendKeys' method .
The code is:
String Str = ExcelUtils.getcell(1,2) ;
Integer x = Integer.Valueof(x);
driver.findelement(By.xpath("xpath").sendkeys(Integer.valueof(x)); –
Here is something to get you going:
#Test
public void testParsing() {
String input = "ReqQty = 2";
Pattern pattern = Pattern.compile("ReqQty.*=.*([\\d]+)");
Matcher matcher = pattern.matcher(input);
if (!matcher.find()) {
throw new IllegalArgumentException("failed to parse digits from: " + input);
}
System.out.println(Integer.parseInt(matcher.group(1)));
}
The key elements:
a regular expression pattern used to "match" for a number of digits within a string
Integer.parseInt() to turn that substring of digits into a number
Beyond that: it looks like you are overburdening yourself. The error message you got is quite clear "ReqQty = 2" is not a string that only contains a number. Thus you have to extract that number part from this string. This is really basic stuff. If that is already beyond your skills, then fetching data from excel to pass that into selenium is probably beyond your current skills!
Thus: the real answer is - step back and study the java basics!
you can convert a string into an integer using Integer.parseInt(String x)
String x = "17";
int xAsInt = Integer.parseInt(x);
System.out.println(xAsInt);
To convert a string value into an integer you can try this
'int x = Integer.parseInt("1234");'
or if you are using StringBuilder or StringBuffer you can try this
'Integer.parseInt(myBuilderOrBuffer.toString());'
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a long string of digits in Java. I want to find of the string contains any one of the digits 0,1,4,6,8,9 or not. I do not want to check if my string contains just any random digits or not.
I don't care how many times the digit is present. If any one of the above digits is present in the string even once, I want to stop right there and return true.
what regex can be used to match this string?
Is there any faster way to do it instead of using regex?
I am using Java 8.
EDIT: I already found lots solutions online for checking if a string contains digits or not. Those solutions don't work here because I want to optimally find out if my string (of length~10^15 characters) contains specific digits or not.
You can use the pattern .*[014689].* along with String.matches():
String input = "1 Hello World";
if (input.matches(".*[014689].*")) {
System.out.println("Match!");
}
Assuming your String is so very big that you have to read it from an InputStream, I'd advise something of the likes :
public static final Pattern TO_MATCH = Pattern.compile("[014689]");
public static boolean hasDigits(InputStream is, int bufferSize){
BufferedReader l_read = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()),bufferSize);
return l_read.lines().filter(s -> TO_MATCH.matcher(s).find()).findAny().isPresent();
}
Where you can tweak buffersize for performance.
if (preg_match('/[^|]/', $string)) {
// string contains characters other than |
}
or:
if (strlen(str_replace('|', '', $string)) > 0) {
// string contains characters other than |
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have started learning Java and have some across some difficulties. I'm trying to subtract two strings.
for example, with these strings;"032"&&"100". I want to be able to subtract each number individually so that the answer would be "032".
I have tried using substring, and parsing the two values to ints, but don't know what to do next. I have also tries using a for loop, to go through each arrays of the strings.
I do not expect for anyone to do this for me, but I would love to get some insight,or to tell me that i'm headed in the right direction
thanks
public static String appliquerCoup( String combinaison, String coup ) {
String nouveauCoup="";
if(combinaison!=null&&coup!=null){
for(int i=0;i>combinaison.length();i++){
int a = Integer.parseInt(combinaison.substring(i, i + 1));
int b = Integer.parseInt(coup.substring(i, i + 1));
nouveauCoup=String.valueOf(a-b);
if(a-b<0){
nouveauCoup=0;
}
}
} // main
return nouveauCoup;
}
If I understand you question correctly. you want to subtract each digit individually.
So (0-1), (3-0), (2-0). The following program does this (yields -132):
public static void main(String[] args) {
String A = "032";
String B = "100";
String str = "";
for(int i = 0; i < A.length(); i++)
{
int a = Integer.parseInt(A.substring(i, i + 1));
int b = Integer.parseInt(B.substring(i, i + 1));
int c = a - b;
str += String.valueOf(c < 0 ? 0 : c);
}
System.out.println(str);
}
Essentially, extract the i-th character of each string, convert them to integers, then do the subtraction. Convert the result back to a string and append it to the result string.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got this string:
"type":"image","originX":"center","originY":"center","left":135,"top":259,"width":270,"height":519,"fill":"rgb(0,0,0)","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"src":"file:///C:/Users/Alvin%20Combrink/Dropbox/Entrepren%C3%B6rskap/Design/Hemsidan/Backgrunder/Labyrint.jpg","filters":[]},
each part is seperated by a comma, i want to be able to extract a few of the numbers into doubles. The ones i want are left, top, scaleX, scaleY and angle. How shall i approch this?
thanks
If you don't want to rely on using JSON parsers (you should, though, if you are using JSON a lot), you could use the split-method on the entire string and split according to , (comma), find the chunks of data that you want, split those according to : and read the data directly from the 2nd slot in the resulting array.
You may need to substring the last " to be able to parse the numbers directly, though.
But like I said, you really do want to use a JSON parser of some kind if you are using JSON more than a few times in your program.
Code example:
String abc = "ABC:123,DEF:456,GHI:789";
String[] chucks = abc.split(",");
String[] oneToThree = chunks[0].split(":");
String nums = oneToThree[1];
System.out.println(nums);
//This will print 123
I know that someone already replied, but I've been doing this, hope that help too:
public class HelloWorld{
public static void main(String []args){
String text ="\"type\":\"image\",\"originX\":\"center\",\"originY\":\"center\",\"left\":135,\"top\":259,\"width\":270,\"height\":519,\"fill\":\"rgb(0,0,0)\",\"overlayFill\":null,\"stroke\":null,\"strokeWidth\":1,\"strokeDashArray\":null,\"strokeLineCap\":\"butt\",\"strokeLineJoin\":\"miter\",\"strokeMiterLimit\":10,\"scaleX\":1,\"scaleY\":1,\"angle\":0,\"flipX\":false,\"flipY\":false,\"opacity\":1,\"shadow\":null,\"visible\":true,\"clipTo\":null,\"src\":\"file:///C:/Users/Alvin%20Combrink/Dropbox/Entrepren%C3%B6rskap/Design/Hemsidan/Backgrunder/Labyrint.jpg\"";
//Just left and scaleX for example
String left = readValue(text, "left");
String scaleX = readValue(text, "scaleX");
System.out.println("left:" + left);
System.out.println("scaleX:" + scaleX);
}
public static String readValue(String text, String key)
{
//search for the init of the value
int start = text.indexOf("\"" + key + "\"");
//search for the end of the value
int end = text.indexOf(",", start + key.length() + 3);
//return the value. these + 3 , is for quotes and ":"
return text.substring(start + key.length() + 3,end);
}
}