I want to parse a string and get a double value.
For example, I input "65.2 hello".
I want to get "65.2"
Will I?
while(scanner.hasNextLine()) {
String ReadString = scanner.nextLine();
double value = Double.parseDouble(ReadString);
Exception in thread "main" java.lang.NumberFormatException: For input string: "65.2 hello"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:549)
at com.company.Main.main(Main.java:18)
Because at least part of the String can't be converted to a double, you need to remove that part of the String before you can use parseDouble on it.
Try this.
Scanner scanner = new Scanner("65.2 hello");
while(scanner.hasNextDouble()) {
double value = scanner.nextDouble();
System.out.println(value);
}
output:
65.2
For a simple string like "65.2 hello" where there is one numerical value within the string then a simple:
String myString = "65.2 hello";
double value = Double.parseDouble(myString.replaceAll("[^(-?\\d+(\\.\\d+)?)]", "").trim());
should be suffice. But, if there is more than one numerical value within the string then you would need to change it up a little, for example:
String myString = "I weigh 90.7185kg and I would like to loose another 10kg. "
+ "My name is Tom, I'm 32 years old.";
String parsable = myString.replaceAll("[^(-?\\d+(\\.\\d+)?)]", " ").trim()
.replaceAll("\\s\\p{Punct}|\\p{Punct}\\s", "");
double[] values = {};
if (!parsable.isEmpty()) {
String[] numbers = parsable.split("\\s+");
values = new double[numbers.length];
for (int i = 0; i < numbers.length; i++) {
values[i] = Double.parseDouble(numbers[i]);
}
}
// Display doubles array into Console Window:
for (int i = 0; i < values.length; i++) {
System.out.println("Value #" + (i + 1) + " in String is: -> " + values[i]);
}
About the Regular Expressions (regex's) used in this line:
String parsable = myString.replaceAll("[^(-?\\d+(\\.\\d+)?)]", " ").trim()
.replaceAll("\\s\\p{Punct}|\\p{Punct}\\s", "");
The .replaceAll("[^(-?\\d+(\\.\\d+)?)]", " ").trim() will replace everything within the String except for signed or unsigned Integer or floating point numerical values with a whitespace. It then trims the outcome of leading and or trailing whitespaces, tabs, etc (if any).
The .replaceAll("\\s\\p{Punct}|\\p{Punct}\\s", ""); will replace any remaining special characters like punctuation that contains a least one leading or one trailing whitespace. When the first replaceAll() above has completed there is most likely going to be straggling periods, etc remaining in the string. We don't want those for splitting the string so this replaceAll() will get rid of those stragglers.
All that should now remain in the string will be numerical values separated by one or more whitespaces. This is where the regex \\s+ used in the String#split() method comes in handy:
String[] numbers = parsable.split("\\s+");
This will split the new string based on one or more whitespaces. So, what is "90.7185 10 32" will be split into a String[] Array consisting of three elements, ["90.7185", "10", "32"]. Each element of this array is now converted to a double data type and added to the double type values[] Array.
Related
Someone please help, How exactly can I take a string and break it up evenly.
for example (41-25) how can I pull the 41 or 25 out instead of getting a seperate 4 and 1.
Whenever I enter a double it registers it as each single digit including the period but not as a whole.
static double evaluate(String expr){
//Add code below
Stack<String> operators = new Stack<String>();
Stack<Double> values = new Stack<Double>();
String[] temp = expr.split("");
Double value = 0.0;
for(int i=0; i< temp.length;i++){
if(temp[i].equals("(")) continue;
else if(temp[i].equals("+")) operators.push(temp[i]);
else if(temp[i].equals("-")) operators.push(temp[i]);
else if(temp[i].equals("*")) operators.push(temp[i]);
else if(temp[i].equals("/")) operators.push(temp[i]);
else if(temp[i].equals(")")) {
String ops = operators.pop();
value = values.pop();
value = operate(values.pop(), value, ops);
System.out.println(value);
values.push(value);
}
else{
System.out.println(temp[i]);
Double current = Double.parseDouble(temp[i]);
values.push(current);
}
}
return 0;
}
I would split the string before and after any operator rather than splitting every character:
static double evaluate(String expr){
//Add code below
...
String[] temp = expr.split("((?<=[\+\-\*\/])|(?=[\+\-\*\/]))"); // Changes "41-25" to ["41", "-", "25"]
This uses regex to split the string using a positive look behind (?<=) and a positive lookahead (?=) with a character set inside for the four operators that you need [\+\-\*\/] (the operators are escaped with a backslash.
Any string will split before and after any operator. If you need more operators, they can be added to the character set.
With Java you could even make your character set a String to remove duplicate code by putting:
String operators = "\\+-\\*/";
String[] temp = expr.split("((?<=[" + operators + "])|(?=[" + operators + "]))";
This method enables you to change what operators to split on easily.
The question is we have to split the string and write how many words we have.
Scanner in = new Scanner(System.in);
String st = in.nextLine();
String[] tokens = st.split("[\\W]+");
When I gave the input as a new line and printed the no. of tokens .I have got the answer as one.But i want it as zero.What should i do? Here the delimiters are all the symbols.
Short answer: To get the tokens in str (determined by whitespace separators), you can do the following:
String str = ... //some string
str = str.trim() + " "; //modify the string for the reasons described below
String[] tokens = str.split("\\s+");
Longer answer:
First of all, the argument to split() is the delimiter - in this case one or more whitespace characters, which is "\\s+".
If you look carefully at the Javadoc of String#split(String, int) (which is what String#split(String) calls), you will see why it behaves like this.
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
This is why "".split("\\s+") would return an array with one empty string [""], so you need to append the space to avoid this. " ".split("\\s+") returns an empty array with 0 elements, as you want.
When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array.
This is why " a".split("\\s+") would return ["", "a"], so you need to trim() the string first to remove whitespace from the beginning.
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Since String#split(String) calls String#split(String, int) with the limit argument of zero, you can add whitespace to the end of the string without changing the number of words (because trailing empty strings will be discarded).
UPDATE:
If the delimiter is "\\W+", it's slightly different because you can't use trim() for that:
String str = ...
str = str.replaceAll("^\\W+", "") + " ";
String[] tokens = str.split("\\W+");
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line = null;
while (!(line = in.nextLine()).isEmpty()) {
//logic
}
System.out.print("Empty Line");
}
output
Empty Line
I have one String generated of random characters that will encrypt another String given by the user by adding the first character from the String with the first character of the given String. It's working fine, but if the user were to enter multiple words with spaces in between, I want to choose the next character of the first String rather than code the space itself. Is that possible? This is what I have:
(random is the coded string and sentenceUpper is string given by user)
public static void encrypt(String sentenceUpper){
String newSentence = "";
for(int i = 0; i < sentenceUpper.length(); i++){
char one = random.charAt(i);
char two = sentenceUpper.charAt(i);
if(one < 'A' || one > 'Z'){
two = sentenceUpper.charAt(1 + i);}
char result = (char)((one + two)%26 + 'A');
newSentence += "" + result;
}
EDIT FOR BETTER EXPLANATION:
I have:
String random = "WFAZYZAZOHS";
I would like to code user input:
String upperCase: "YOU GO";
So, I'm going to take Y + L = U, etc...
to get :
"UTUSEN
"
But I see that there's a space in "YOU GO" , So I'd like to change it to:
WFA ZY + YOU GO = UTU SE.
I hope that's better explained.
The simplest way to do this would probably be to use an if statement to run the code in the loop only if the character is not a space. If you don't want to skip the character in the random string, you would need a separate variable to track the current character index in that string.
Example: Put this after defining one and two and put the rest of the loop inside it:
if(two==' '){
...
}
Then, add the space in the output:
else{
newSentence+=" ";
}
I have String which I want to convert into Integer.
example - I have string in below format
Input : ABCD00000123
Output: 123
Thanks in Advance
// First remove all non number characters from String
input= input.replaceAll( "[^\\d]", "" );
// Convert it to int
int num = Integer.parseInt(input);
For example
input = "ABCD00000123";
After
input= input.replaceAll( "[^\\d]", "" );
input will be "00000123"
int num = Integer.parseInt(input);
int will be 123.
This is one of the simple solution if the input is always in the format mentioned in the question. There can be multiple scenarios considering position of numeric characters with respect to non numberic characters like
0123ABC
0123ABC456
ABC0123DE
String s = "ABCD00000123"
int output = Integer.parseInt(s.subString(4));
System.out.println(output);
I can tell yo the logic for it... convert this String into a character array, and then parse it from the first index (0 for array), up to length and check the first non-zero integer number, then from that location to the remaining length of the String copy this to another String and then parse it using Integer.parseInt();
String val = "ABCD00000123";
String arr[] = val.toCharArray();
int cnt;
for(cnt = 0 ; cnt < arr.length; cnt++){
switch(arr[cnt]){
/*Place your logic here to check the first non-zero number*/
}
}
and then follow the remaining logic.
if you have enough programming concepts then only you can do it...
I need to extract several integers from a string that looks like this:
22:43:12:45
I need to extract 22, 43, 12, and 45 as separate integers. I need to use string methods or scanner methods to read up until : and extract the 22. Then read between the first : and second : to give me 43, and so on.
I can extract up to the first : no problem, but I down know what to do thereafter.
Any help would be much appreciated.
String[] parts = str.split(":");
int[] numbers = new int[parts.length];
Iterate over this String array to get an array of integers:
int index = 0;
for(String part : parts)
numbers[index++] = Integer.parseInt(part);
You should look at String.split method . Given a regular expression, this methods splits the string based on that. In your case the regular expression is a ":"
String s ="22:43:12:45";
int i =0;
for (String s1 : s.split(":")) { // For each string in the resulting split array
i = Integer.parseInt(s1);
System.out.println(i);
}
The split returns a string array with your string separated. So in this case , The resulting string array will have "22" on the 0th position, "43" on the first position and so on. To convert these to integers you can use the parseInt method which takes in a string and gives the int equivalent.
You can use only indexOf and substring methods of String:
String text = "22:43:12:45";
int start = 0;
int colon;
while (start < text.length()) {
colon = text.indexOf(':', start);
if (colon < 0) {
colon = text.length();
}
// You can store the returned value somewhere, in a list for example
Integer.parseInt(text.substring(start, colon)));
start = colon + 1;
};
Using Scanner is even simpler:
String text = "22:43:12:45";
Scanner scanner = new Scanner(text);
scanner.useDelimiter(":");
while (scanner.hasNext()) {
// Store the returned value somewhere to use it
scanner.nextInt();
}
However, String.split is the shortest solution.
Make a regex like
(\d\d):(\d\d):(\d\d):(\d\d)