I am writing a program in Java that makes use of the command line.
The program that I'm making is used by another program, the problem is that my 4th parameter has to be an int, for example 60(this is an int, it's used for calculations) for my program to work, and the program that uses it then has fixedwidth:60(this is a string) as the 4th parameter.
My question now is how is it possible to still use the 60 in calculations while not giving errors due to the program using it having a string as a 4th parameter and not an int. I have triend Integer.parseInt and Integer.ToString, but I still get the same error
Thanks in advance.
Split the string on : and then parse the second part, like so -
String str = "fixedwidth:60";
String[] arr = str.split(":");
int val = Integer.parseInt(arr[1]);
// OR -
// int val = Integer.valueOf(arr[1]);
System.out.println(val);
Output is
60
Integer.parseInt(String) and Integer.valueOf(String) both expect the input String to be just the number you want to parse. That's why you probably get a NumberFormatException when trying to parse "fixedwidth:60".
If you really need to input the whole string "fixedwidth:60", you must first extract the number from that string. You can do that with Elliott Frisch's code using String.split(":"):
String str = "fixedwidth:60";
String[] arr = str.split(":"); // arr = { "fixedwidth", "60"}
int val = Integer.parseInt(arr[1]); // arr[1] = "60", which can be parsed
Related
I'm trying to use a scanner to parse out some text but i keep getting an InputMismatchException. I'm using the scanner.next(Pattern pattern) method and i want to return the next n amount of characters (including whitespace).
For example when trying to parse out
"21 SPAN 1101"
I want to store the first 4 characters ("21 ") in a variable, then the next 6 characters (" ") in another variable, then the next 5 ("SPAN "), and finally the last 4 ("1101")
What I have so far is:
String input = "21 SPAN 1101";
Scanner parser = new Scanner(input);
avl = parser.next(".{4}");
cnt = parser.next(".{6}");
abbr = parser.next(".{5}");
num = parser.next(".{4}");
But this keeps throwing an InputMismatchException even though according to the java 8 documentation for the scanner.next(Pattern pattern) it doesn't throw that type of exception. Even if I explicitly declare the pattern and then pass that pattern into the method i get the same exception being thrown.
Am I approaching this problem with the wrong class/method altogether? As far as i can tell my syntax is correct but i still cant figure out why im getting this exception.
At documentation of next(String pattern) we can find that it (emphasis mine)
Returns the next token if it matches the pattern constructed from the specified string.
But Scanner is using as default delimiter one or more whitespaces so it doesn't consider spaces as part of token. So first token it returns is "21", not "21 " so condition "...if it matches the pattern constructed from the specified string" is not fulfilled for .{4} because of its length.
Simplest solution would be reading entire line with nextLine() and splitting it into separate parts via regex like (.{4})(.{6})(.{5})(.{4}) or series of substring methods.
You might want to consider creating a convenience method to cut your input String into variable number of pieces of variable length, as approach with Scanner.next() seems to fail due to not considering spaces as part of tokens (spaces are used as delimiter by default). That way you can store result pieces of input String in an array and assign specific elements of an array to other variables (I made some additional explanations in comments to proper lines):
public static void main(String[] args) throws IOException {
String input = "21 SPAN 1101";
String[] result = cutIntoPieces(input, 4, 6, 5, 4);
// You can assign elements of result to variables the following way:
String avl = result[0]; // "21 "
String cnt = result[1]; // " "
String abbr = result[2]; // "SPAN "
String num = result[3]; // "1101"
// Here is an example how you can print whole array to console:
System.out.println(Arrays.toString(result));
}
public static String[] cutIntoPieces(String input, int... howLongPiece) {
String[] pieces = new String[howLongPiece.length]; // Here you store pieces of input String
int startingIndex = 0;
for (int i = 0; i < howLongPiece.length; i++) { // for each "length" passed as an argument...
pieces[i] = input.substring(startingIndex, startingIndex + howLongPiece[i]); // store at the i-th index of pieces array a substring starting at startingIndex and ending "howLongPiece indexes later"
startingIndex += howLongPiece[i]; // update value of startingIndex for next iterations
}
return pieces; // return array containing all pieces
}
Output that you get:
[21 , , SPAN , 1101]
I have a very simple question about JAVA string filter
I to want input this command to console.
add 100#10
which means execute add method input arguments 100 and 10 respectively.
I used
String[] s = str.split("#");
String a = s[0];// here can get 100
String b=s1];// get can get 10
I have two questions
first is how to do delete the at (#) character before put it to string.split()
second can anyone can provide some better solution to handle this kind of input ?
such as
add 1000#10 //only add,1000,10 need to take
times 1000#10 //only add,1000,10 need to take
You can split on multiple tokens because it's a regex parameter:
String a[] = "aadd 100#200".split("[ #]");
returns ["aadd", "100", "200"]
Then you can do
String command = a[0];
String operand1 = a[1];
String operand2 = a[2];
not as sexy as ergonaut's solution, but you also can use two splits:
String[] arr1 = "add 100#10".split(" ");
String[] arr2 = arr1[1].split("#");
String[] result = [arr1[0], arr2[0], arr2[1]];
should be
["add","100","10"]; // this is result
greetings
As an example I have abcdbab and I want to replace all ab with A.
The output is AcdbA.
I try this one but it gives an error.
char N = 65;
String S = "abcdbab";
S = S.replaceAll("ab", N);
System.out.print(S);
Is there any method to do this?
Use String.replace(CharSequence,CharSequence) (remember String is immutable, so either use the result or assign it back) like
String str = "abcdbab";
System.out.println(str);
str = str.replace("ab", "A");
System.out.println(str);
Output is
abcdbab
AcdbA
Just change the following line:
char N = 65;
to
String N = "A";
and it'll work fine.
There is no such method String#replace(CharSequence, char), you will need to find the one that is closes to your needs and adjust to it, for example, there is a String#replaceAll(CharSequence, CharSequence) method and char can be represented as a CharSequence (or a String), for example...
S = S.replaceAll("ab", Character.toString(N));
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
You can also change
S = S.replaceAll("ab", N);
to
S = S.replaceAll("ab", "" + N);
referencing here, http://www.tutorialspoint.com/java/java_string_replaceall.htm replaceAll takes a String, String not String, Char
I have some expression in a Java string and a would get the letter, which was on the left side and on the right side of a specific sign.
Here are two examples:
X-Y
X-V-Y
Now, I need to extract in the first example the letter X and Y in a separate string. And in the second example, I need to extract the letters X, V and Y in a separate string.
How can i implemented this requirement in Java?
Try with:
String input = "X-V-Y";
String[] output = input.split("-"); // array with: "X", "V", "Y"
use String.split method with "-" token
String input = "X-Y-V"
String[] output = input.split("-");
now in the output array there will be 3 elements X,Y,V
String[] results = string.split("-");
do like this
String input ="X-V-Y";
String[] arr=input.split("-");
output
arr[0]-->X
arr[1]-->V
arr[2]-->Y
I'm getting in on this too!
String[] terms = str.split("\\W"); // split on non-word chars
You can use this method :
public String[] splitWordWithHyphen(String input) {
return input.split("-");
}
you can extract and handle a string by using the following code:
String input = "x-v-y";
String[] extractedInput = intput.split("-");
for (int i = 0; i < extractedInput.length - 1; i++) {
System.out.print(exctractedInput[i]);
}
Output: xvy
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)