JAVA - Double split string and convert to integer - java

Hello i tried many ways to complete this but i failed.
Could you help me ?
I need double split one is "\n" and second is "|".
In textArea is string
350|450\n
444|452\n
and so one.
There are mouse coordinates.
X|Y
in int array i need
array[0]= x coord;
array[1]= y coord;
array[2]= x coord;
array[2]= y coord;
So i have string in textarea.I split that by "\n"
String s[]= txtArea.getText().split("\\n");
This is one split and in textarea i have something like 150|255
this is my mouse coordinates x|y.
So i need next split "|".
String s2[] = s[i].split("|");
After that
int [] array = new [s.length*2];
And some method for
while(!(s[j].equals("|")))
array[i] = Integer.parseInt(s[j]);
I tried something like that-
for(String line : txtArea.getText().split("\\n")){
arrayXY = line.split("\\|");
array = new int[arrayXY.length];
}
Thank you a lot for answers :)
Have a nice day.

This can be solved easily using regex:
String[] split = input.split("\\||\n");
split will then contain the single numbers from the input.

Use Scanner. It is always preferred over String.split().
Your code would then reduce to:
Scanner scanner = new Scanner(txtArea.getText());
scanner.useDelimiter("\\||\\n"); // i.e. | and the new line
for (int i = 0; i < array.length; i++) { // or use the structure you need
array[i] = scanner.nextInt();
}
Also, don't forget to import java.util.Scanner;

Related

Attempting to print Strings on seperate lines

While writing a project for a non CS class I ran into a problem. The project i had in mind is a type of quiz, wherein the user is asked a question and is given multiple choices for answers. Now, I intended to type these questions into a .txt file and use a file scanner to read them in, and create an array of questions like so:
public static String[] questionToString(Scanner sf) {
String temp = "";
String[] questions = new String[Q];
int i = 0;
while(sf.hasNext()){
for(int y = 0; y < 5; y++) {
temp += sf.nextLine();
}
questions[i] = temp;
i++;
temp = "";
return questions;
}
However, this code when tested would return something along the lines of:
Question 1 abcd
as opposed to:
Question 1
a
b
c
d
I want each character to be placed on it's own line, like in the second example. How can I do this while printing the strings? (System.out.println())
Eventually, I plan to put them on a DrawingPanel with the questions lined up below.
Thanks!
Use "\n" to add an extra line in addition to the line println() already appends:
System.out.println(your_var + "\n")
That is because you are adding questions lines to a string. So make a small change to the following line:
temp += sf.nextLine() + "\n";
Of course, the newline char depends on which environment you are running (\n or \r\n).
Best way to append many strings into one with a new line character after each one is to use StringBuilder. I have rewritten your code using StringBuilder
public static String[] questionToString(Scanner sf) {
StringBuilder temp = new StringBuilder();
String[] questions = new String[Q];
int i = 0;
while(sf.hasNext()){
for(int y = 0; y < 5; y++) {
temp.append(sf.nextLine());
temp.append(System.lineSeparator());
}
questions[i] = temp.toString();
i++;
temp = new StringBuilder();
return questions;
}
NOTE: Please don't append /n with your string as the new line character differs for different operating system. I will advise you to use System.lineSeparator(), this will append the new line character depending on the operating system you are running you code on.

Using Scanner and Arrays's to add BigInts

This is a project from school, but i'm only asking for help in the logic on one small part of it. I got most of it figured out.
I'm being given a file with lines of string integers, for example:
1234 123
12 153 23
1234
I am to read each line, compute the sum, and then go to the next one to produce this:
1357
188
1234
I'm stuck on the scanner part.
public static void doTheThing(Scanner input) {
int[] result = new int[MAX_DIGITS];
while(input.hasNextLine()) {
String line = input.nextLine();
Scanner linesc = new Scanner(line);
while(linesc.hasNext()) {
String currentLine = linesc.next();
int[] currentArray = convertArray(stringToArray(currentLine));
result = addInt(result, currentArray);
}
result = new int[MAX_DIGITS];
}
}
In a nutshell, I want to grab each big integer, put it an array of numbers, add them, and then i'll do the rest later.
What this is doing it's basically reading all the lines and adding everything and putting it into a single array.
What i'm stuck on is how do I read each line, add, reset the value to 0, and then read the next line? I've been at this for hours and i'm mind stumped.
Edit 01: I realize now that I should be using another scanner to read each line, but now i'm getting an error that looks like an infinite loop?
Edit 02: Ok, so after more hints and advice, I'm past that error, but now it's doing exactly what the original problem is.
Final Edit: Heh....fixed it. I was forgetting to reset the value to "0" before printing each value. So it makes sense that it was adding all of the values.
Yay....coding is fun....
hasNext method of the Scanner class can be used to check if there is any data available in stream or not. Accordingly, next method used to retrieve next continuous sequence of characters without white space characters. Here use of the hasNext method as condition of if doesn't make any sense as what you want is to check if the there are any numerical data left in the current line. You can use next(String pattern).
In addition, you can try this solution even though it is not optimal solution...
// In a loop
String line = input.nextLine(); //return entire line & descard newline character.
String naw[] = line.split(" "); //split line into sub strings.
/*naw contains numbers of the current line in form of string array.
Now you can perfom your logic after converting string to int.*/
I would also like to mention that it can easily & efficiently be done using java-8 streams.
An easier approach would be to abandon the Scanner altogether, let java.nio.io.Files to the reading for you and then just handle each line:
Files.lines(Paths.get("/path/to/my/file.txt"))
.map(s -> Arrays.stream(s.split("\\s+")).mapToInt(Integer::parseInt).sum())
.forEach(System.out::println);
If i were you i would be using the BufferedReader insted of the Scanner like this:
BufferedReader br = new BufferedReader(new FileReader("path"));
String line = "";
while((line = br.readLine()) != null)
{
int sum = 0;
String[] arr = line.split(" ");
for(String num : arr)
{
sum += Integer.parseInt(num);
}
System.out.println(sum);
}
Considering the level you're on, I think you should consider this solution. By using only the scanner, you can split the lines into an array of tokens, then iterate and sum the tokens by parsing them and validating that they're not empty.
import java.util.*;
class SumLines {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
while(S.hasNext()) {
String[] tokens = S.nextLine().split(" ");
int sum = 0;
for(int i = 0; i < tokens.length; i++) {
if(!tokens[i].equals("")) sum += Integer.parseInt(tokens[i]);
}
System.out.println(sum);
}
}
}

Separating an unknown amount of hyphens in java?

Good day, guys,
I'm working on a program which requires me to input a name (E.g Patrick-Connor-O'Neill). The name can be composed of as many names as possible, so not necessarily restricted to solely 3 as seen in the example above.But the point of the program is to return the initials back so in this case PCO. I'm writing to ask for a little clarification. I need to separate the names out from the hyphens first, right? Then I need to take the first character of the names and print that out?
Anyway, my question is basically how do I separate the string if I don't know how much is inputted? I get that if it's only like two terms I would do:
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
I did attempt to do the code, and all I have so far is:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
}
}
}
I'm taking a crash course in programming, so easy concepts are hard for me.Thanks for reading!
You don't need to split it a second time. By doing String[] x = input.split("-"); you have an Array of Strings. Now you can iterate over them which you already do with the enhanced for loop. It should look like this
String[] x = input.split("-");
String initials = "";
for (String name : x) {
initials += name.charAt(0);
}
System.out.println(initials);
Here are some Java Docs for the used methods
String#split
String#charAt
Assignment operator +=
You can do it without splitting the string by using String.indexOf to find the next -; then just append the subsequent character to the initials:
String initials = "" + input.charAt(0);
int next = -1;
while (true) {
next = input.indexOf('-', next + 1);
if (next < 0) break;
initials += input.charAt(next + 1);
}
(There are lots of edge cases not handled here; omitted to get across the main point of the approach).
In your for-each loop append first character of all the elements of String array into an output String to get the initials:
String output = "";
for(String i : x) {
output = output + y.charAt(0);
}
This will help.
public static void main(String[] args) {
String output = "";
String input = "Patrick-Connor-O'Neil-Saint-Patricks-Day";
String[] brokenInput = input.split("-");
for (String temp : brokenInput) {
if (!temp.equals(""))
output = output + temp.charAt(0);
}
System.out.println(output);
}
You could totally try something like this (a little refactor of your code):
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = "";
System.out.println("What's your name?");
input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
System.out.println(y);
}
}
}
I think it's pretty easy and straightforward from here if you want to simply isolate the initials. If you are new to Java make sure you use a lot of System.out since it helps you a lot with debugging.
Good coding.
EDIT: You can use #Mohit Tyagi 's answer with mine to achieve the full thing if you are cheating :P
This might help
String test = "abs-bcd-cde-fgh-lik";
String[] splitArray = test.split("-");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < splitArray.length; i++) {
stringBuffer.append(splitArray[i].charAt(0));
}
System.out.println(stringBuffer);
}
Using StringBuffer will save your memory as, if you use String a new object will get created every time you modify it.

Parsing a string in Java and having the out put seperated by a comma

so far i have this
import java.util.ArrayList;
public class Sequence
{
private double[] sequence;
public Sequence(String s)
{
String s = "903, 809, 719";
System.out.println
(java.util.Arrays.toString(s.split("\\.")));
}
Will this print the numbers in the string seperated by a comma?
Im then trying to to parse each individual String to get a double, storing these doubles in sequence. How do i do it?
You should try a different split.
Try like this :
s.split(", ");
Hope this can help you.
String str_arr[] = s.split(", ");
for (String string : str_arr) {
double d = Double.valueOf(s);
//perform the necessary action here
}
To answer your question, you're splitting your string with "\.", so no, it wont print the numbers separated by a comma.
To split the string by ", " simply change your code to be
s.split(", ");
In this particular scenario, I would personally split s into an array of strings and then add each element of that array of strings into an ArrayList of doubles so you can use them as you please later, like so
String[] doubleStrings = s.split(", ");
ArrayList<Double> doubleList = new ArrayList<Double>();
for(int i = 0; i < doubleStrings.length; i++){
doubleList.add(Double.parseDouble(doubleStrings[i]));
}
By using an ArrayList, you can store each element of the split string in sequence, and thereby easily allowing you to print or process each Double however you please.
String[] ns = s.split(",");
ArrayList<Double> doubles = new ArrayList<>();
for(String q : ns)
{
doubles.add(new Double(Double.parseDouble(q)));
}
You should have the double values in the doubles ArrayList. (make sure you try and catch a number format exception for the Double parsing)
No, this will split the string at ANY position. . is the regexp for 'any character', please try
s.split(", ")

Take different values from a String and convert them to Double Values

In my code, I'm asking the user to input three different values divided by a blank space.
Then, those three different values I would like to assign them to three different Double variables.
I have tried by assigning the first character of such string to my double variables but I haven't been able to succeed.
Any suggestions?
Thank you!
Here is what I'm trying to do:
int decision = message();
String newDimensions;
double newHeight, newWidth, newLength;
if(decision == 1){
newDimensions = JOptionPane.showInputDialog("Please enter the desired amount to be added" +
"\nto each dimension." +
"\nNOTE: First value is for Height, second for Width, third for Length" +
"\nAlso, input information has to have a blank space between each value." +
"\nEXAMPLE: 4 8 9");
newHeight = Double.parseDouble(newDimensions.charAt(0));
Take input from user.
split that line using delimeter space i.e " ".
inside for loop change each index element to double.By using Double.parseDouble(splitted[i]);
Get the input, split it by a whitespace and parse each Double. This code does not sanitize the input.
String input = "12.4 19.8776 23.3445";
String[] split = input.split(" ");
for(String s : split)
{
System.out.println(Double.parseDouble(s));
}
You could first split the input using String.split and then parse each variable using Double.parseDouble Double.parseDouble to read them into a Double variable.
String[] params = newDimensions.split(" ");
newHeight = Double.parseDouble(params[0]);
newWidth = Double.parseDouble(params[1]);
Double#parseDouble(str) expects a string,and you are trying to pass a character.
try this:
newHeight = Double.parseDouble(newDimensions.subString(1));
Try something like this:
newDimensions = JOptionPane.showInputDialog(...
newDimensions = newDimensions.trim();
String arr[] = newDimensions.split(" ");
double darr[] = new double[arr.length];
for(int i=0;i<arr.length;i++) darr[i] = Double.parseDouble(arr[i].trim());
There are still some defensive issues that can be taken. Doing a trim on your parse double is kind of critical.

Categories

Resources