Split a string using white space java [duplicate] - java

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
I have a String like the following 2 4 12 12 yellow Hi how are you
I want to split the string like this {2,2,12,12,yellow, Hi how are you} in order to pass the items in the list as parameters in a constructor.
Any help?

The trivial answer is to split the string:
String[] fragments = theString.split(" ", 6);
Given that the fragments have specific meanings (and presumably you want some of them as non-string types), it might be more readable to use a Scanner:
Scanner sc = new Scanner(theString);
int x = sc.nextInt();
int y = sc.nextInt();
int width = sc.nextInt();
int height = sc.nextInt();
String color = sc.next();
String message = sc.nextLine();
This approach is also easier if you are reading these strings, say, from a file or standard input: just create the Scanner over the FileReader/InputStream instead.

Related

How to check if a string matches a format in java? [duplicate]

This question already has an answer here:
How to check if a string matches a specific format?
(1 answer)
Closed 3 years ago.
public static String[] positionQuery(int dim, Scanner test_in) {
Scanner stdin = new Scanner(System.in);
System.out.println("Provide origin and destination coordinates.");
System.out.println("Enter two positions between A1-H8:");
String s = stdin.nextLine();
String coordinates [] = s.split(" ");
String origin = coordinates[0];
String dest = coordinates[1];
Here is my code, I am getting two strings from the scanner and I want to check if the positions have the correct format of capital letter and integer. I looked at the .matches() method but didn't quite get how to do it with this pattern: A1-H8
The strings are like E6, B4, F1, A8... the pattern is capital letter-integer.
Cheers!
import java.util.Scanner;
public class PatternCheck {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
scan.close();
String RegexPattern = "^[A-Z][0-9]$";// Change the pattern as per your
// requirement
String sAr[] = s.split("-");
for (int i = 0; i < sAr.length; i++) {
System.out.println(sAr[i].matches(RegexPattern));
}
}
}
Assuming you are only working with single-digit numbers and passing in a 2 character String to test (after splitting), if the string is s, this expression should do:
(s.length()==2) && Character.isLetter(s.charAt(0)) && Character.isDigit(s.charAt(1))
REVISION: as Andreas pointed out in a comment, when fed Ψ1, the above evaluates to true (isUpperCase also is no use fixing it, because that Phi is upper case).
I like the below less, but it avoids the indicated issue:
(s.length()==2) && ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(s.charAt(0))>-1) && Character.isDigit(s.charAt(1))
I am going along with the requirement from the original problem and clarified in comments that the letter be upper case.
Revision 2: The fix was unnecessarily ugly. Nicer is:
(s.length()==2) && (s.charAt(0)>='A') && (s.charAt(0)<='Z')&& Character.isDigit(s.charAt(1))
If you do not have requirement of ordering then regex [A-H][1-8]-[A-H][1-8] can help (as a Java string: "[A-H][1-8]-[A-H][1-8]")
Example: A1-H8 , H4-G7 , C8-A1
You can test it out here: https://www.regexplanet.com/advanced/java/index.html

How do I turn an input String's characters to lowercase? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I am trying to create the following program in which I need to turn the input String's characters into lowercase to ease my work.
I tried using toLowerCase(); first but it didn't work. Then I tried using toLowerCase(locale); and yet I have not succeeded.
public static void Mensuration() {
Locale locale = Locale.ENGLISH;
Scanner inputz = new Scanner(System.in);
System.out.println("Which kind of shape's formula would you like to find out.2D or 3D?");
char dimension = inputz.nextLine().charAt(0);
if(dimension == '2') {System.out.println("Okay so which shape?");
String dimensiond = inputz.nextLine().toLowerCase(locale);
if(dimensiond == "rectangle") {System.out.println("Area = length x breadth\nPerimeter = 2(length + breadth)");}
}
}
I expected the program to give the accurate output but the thing that happens is that there is no output actually!!
use equals to compare strings. I think this causing the error
"rectangle".equals(dimensiond)

char digit to integer conversion [duplicate]

This question already has answers here:
Using charAt method, won't add them as an Int, and wont print as string. Will explain better
(4 answers)
Using charAt in System.out.println displays integer?
(5 answers)
Why does this code print the ASCII value instead of the character
(2 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm getting the user to enter a string of numbers, then a for loop should pick out each number from the string and add it to an ArrayList. I'm sure someone can help me out fairly quickly
My problem is as follows. When I print out all the values in the ArrayList, It is printing out much higher numbers e.g. 1234 = 49 50 51 52.
I think what is happening is that it is printing out the ASCII values rather than the numbers themselves. Can anyone spot where and why this is happening?
I have tried changing the int variable barcodeNumberAtI to a char, which yields the same result.
Apologies for lack of comments but this was only supposed to be a quick program
int tempNewDigit;
String barCode, ans;
int barcodeNumberAtI;
ArrayList <Integer> numbers = new ArrayList <Integer>();
public void addNumbers(){
Scanner s = new Scanner(System.in);
do{
System.out.println("Please enter a 12 digit barcode\n");
barCode = s.nextLine();
for(int i = 0; i < barCode.length(); i++){
barcodeNumberAtI = barCode.charAt(i);
System.out.println(barcodeNumberAtI);
numbers.add(barcodeNumberAtI);
}
System.out.print("Would you like to add another? y/n\n");
ans = s.nextLine();
} while (!ans.equals("n"));
}
public void displayNumbers(){
for(int i = 0; i < numbers.size(); i++){
System.out.print(numbers.get(i));
}
}
Happens at this line: barcodeNumberAtI = barCode.charAt(i);
barCode.charAt(i) returns a char which is converted to a int by using its ASCII value.
Use this instead:
barcodeNumberAtI = Character.digit(barCode.charAt(i), 10);
What Character.digit does is converting its first argument from the type char to the corresponding int in the radix specified by the second argument.
Here's a link to the documentation

Giving input separated by spaces

Input:
1 10
How can I provide a space between two inputs so that compiler can take both the inputs differently.
I tried to use
st1=in.nextInt();
in.next();
st2=in.nextInt();
Simply remove the in.next(); call. nextInt() already "ignores" whitespaces. And there is no need to create an array by using split() and to convert the number "manually". Just let the Scanner handle this by using nextInt() like you do already:
Scanner s = new Scanner("1 10 9 5");
while(s.hasNextInt()) {
int number = s.nextInt();
System.out.println(number);
}
The good thing about that is, that you won't get a NumberFormatException like in the other answers if the user does not provide numbers (e.g. a b c).
The following line will give you a String array containing the two numbers as strings:
String[] numbersFromUser = in.nextLine().split(" ");
Assuming that the user properly formats the input.
This would of course also work for a number of arguments greater than 2.
You can then go on to convert numbersFromUser[0] and numbersFromUser[1] into the int values you need:
int st1 = Integer.valueOf(numbersFromUser[0]).intValue();
int st2 = Integer.valueOf(numbersFromUser[1]).intValue();
Use:
data = line.split("\s");
first = data[0];
second = data[1];
third = data[2];
System.out.println(first)
System.out.println(second);
System.out.println(third);
Input:
1 5 6
Output:
1
5
6

I got one string consisted of 2 numbers and white space between them, how can I save the numbers in 2 variables? [duplicate]

This question already has answers here:
Take different values from a String and convert them to Double Values
(5 answers)
Closed 8 years ago.
I'm really new to Java programming, so this is a simple question I guess.
I need to write a program that gets as an input the height and weight of a person as one string in which the height and weight separated by white space, for example: 1.68 70
and it calculates and prints the BMI (calculation by the formula weight/height^2).
I read on the internet that getting input from the user can be done by the Scanner class,
and that's what I used. Now I want to save the height and weight in different variables so I can convert them from string to Double, but I don't know how to do it as the whole input is one string . I'm used to Python and slicing :( .. Please help? Thanks a lot.
Based on your comments in the other answer, it looks like you're using a Scanner already. Try something like this.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter stuff");
double height = scanner.nextDouble();
double weight = scanner.nextDouble();
// do your stuff
}
Here you go.
How to split a String by space
This splits the string into an array on any number of white space. Returns an array of your values. The first value in your string will be in your array at position [0] while the second value at [1].
So to relate that to your example...
String value = "1.68 70";
String[] splitValues = value.split("\\s+");
Double height = Double.parseDouble(splitValues[0]);
Double weight = Double.parseDouble(splitValues[1]);

Categories

Resources