I would like to split a line which might look like this:
6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0
The first value is x the second y.
Now i would like to have as a result two Lists ListX<Integer> and ListY<Double>.
I have tried doing it char by char. Where you can search for ':' and then go back and front to get the number. But there must be a faster way. Especially regarding on the lenght of the string which can get really big. Do You have any idea?
Thanks
You can try using String.split():
String test = "6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0";
String[] splitString1 = test.split(" ");
String[] splitString2 = null;
for(String a : splitString1)
{
splitString2 = a.split(":");
System.out.println(splitString2[0]);
System.out.println(splitString2[1]);
//push splitString2[0] to x
//push splitString2[1] to y
}
Here is the complete code which does what you are thinking to do
import java.util.*;
public class IntegerDoubleExtractor{
public static void main(String []args){
String test = "6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0";
List<Integer> x = new ArrayList<Integer>();
List<Double> y = new ArrayList<Double>();
for(String xy : test.split(" ")) {
String xys[] = xy.split(":");
x.add(Integer.parseInt(xys[0]));
y.add(Double.parseDouble(xys[1]));
}
System.out.println(x);
System.out.println(y);
}
}
You can also use a Scanner and you won't need intermediate Strings or arrays in the process:
Scanner scanner = new Scanner(str);
scanner.useDelimiter(Pattern.compile("[:\\s]"));
while (scanner.hasNext()) {
listX.add(scanner.nextInt());
listY.add(scanner.nextDouble());
}
Related
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.
I am a beginner in programming. I am currently learning how to convert texts from notepad into array line by line. An instance of the text in notepad,
I am a high school student
I love banana and chicken
I have 2 dogs and 3 cats
and so on..
In this case, the array[1] will be string 'I love banana and chicken'.
The lines in the notepad can be updated and I want the array to be dynamic/flexible. I have tried to use scanner to identify each of the lines and tried to transfer them to array. Please refer to my code:
import java.util.*;
import java.io.*;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
throws Exception
{
File file = new File("notepad.txt");
Scanner scanner = new Scanner(file);
String line;
int i = 0;
int j = 0;
while (scanner.hasNextLine()) {
i++;
}
String[] stringArray = new String[i];
while (scanner.hasNextLine()) {
line = scanner.nextLine();
stringArray[j] = line;
j++;
}
System.out.println(stringArray[2]);
scanner.close();
}
}
I am not sure why there is runtime-error and I tried another approach but still did not produce the result that I want.
The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you:
String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new);
You can simply do it by creating an ArrayList and then converting it to the String Array.
Here is a sample code to get you started:
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("notepad.txt"));
List<String> outputList = new ArrayList<>();
String input = null;
while (in.hasNextLine() && null != (input = in.nextLine())) {
outputList.add(input);
}
String[] outputArray = new String[outputList.size()];
outputArray = outputList.toArray(outputArray);
in.close();
}
Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this -
List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));
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(", ")
I want to organize a text file with multiple data
A 33 9.25
V 92 1.123
H 100 2.4
into a parallel Array
So far I got to declaring the arraylist and i know i need to do something with a while loop and hasnext... not sure where to go from there.
public static void main(String[] args) throws IOException
{
Scanner fileIn = new Scanner ( new File("sortdata.txt"));
ArrayList<Character> array1 = new ArrayList<Character>();
ArrayList<Integer> array2 = new ArrayList<Integer>();
ArrayList<Double> array3 = new ArrayList<Double>();
while (fileIn.hasNext())
String i = fileIn.next();
int k = 0;
for(i.index(k);i.length();i.index(k++))
if (i.index(k) =='.')
{
}
}
I know some of my code is wrong but I've been looking at it for a long time, think i'm just missing something minor here.
After reading each line from the file here String i = fileIn.next();, trim() the String(to eliminate leading and trailing white spaces as suggested by #X86) and then follow the below steps.
Split the String on white space using the String#split() method.
The String[] returned by the split method above contains all the 3 data required.
From the string[0] get the character using string.charAt(0) and put it into the Character ArrayList.
Parse string[1] as a Integer using Integer.parseInt(string[1]) and put it into the Integer ArrayList.
Parse string[2] as a Double using Double.parseDouble(string[2]) and put it into the Double ArrayList.
This should work:
while (fileIn.hasNextLine()) {
String c[]= fileIn.nextLine().split(" ");
array1.add(new Character(c[0].charAt(0)));
array2.add(new Integer(c[1].trim()));
array3.add(new Double(c[2].trim()));
}
Java has the notion of format strings, bearing a strong resemblance to format strings in other languages. It is used in JDK methods like String#format() for output conversion.
I was wondering if there's an input conversion method akin to C's scanf in Java?
Take a look at this site, it explains two methods for reading from console in java, using Scanner or the classical InputStreamReader from System.in.
Following code is taken from cited website:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsoleSystem {
public static void main(String[] args) {
System.out.println("Enter something here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
--
import java.util.Scanner;
public class ReadConsoleScanner {
public static void main(String[] args) {
System.out.println("Enter something here : ");
String sWhatever;
Scanner scanIn = new Scanner(System.in);
sWhatever = scanIn.nextLine();
scanIn.close();
System.out.println(sWhatever);
}
}
Regards.
There is not a pure scanf replacement in standard Java, but you could use a java.util.Scanner for the same problems you would use scanf to solve.
Not an equivalent, but you can use a Scanner and a pattern to parse lines with three non-negative numbers separated by spaces, for example:
71 5796 2489
88 1136 5298
42 420 842
Here's the code using findAll:
new Scanner(System.in).findAll("(\\d+) (\\d+) (\\d+)")
.forEach(result -> {
int fst = Integer.parseInt(result.group(1));
int snd = Integer.parseInt(result.group(2));
int third = Integer.parseInt(result.group(3));
int sum = fst + snd + third;
System.out.printf("%d + %d + %d = %d", fst, snd, third, sum);
});
If one really wanted to they could make there own version of scanf() like so:
import java.util.ArrayList;
import java.util.Scanner;
public class Testies {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<String> strings = new ArrayList<String>();
// get input
System.out.println("Give me input:");
scanf(strings, nums);
System.out.println("Ints gathered:");
// print numbers scanned in
for(Integer num : nums){
System.out.print(num + " ");
}
System.out.println("\nStrings gathered:");
// print strings scanned in
for(String str : strings){
System.out.print(str + " ");
}
System.out.println("\nData:");
for(int i=0; i<strings.size(); i++){
System.out.println(nums.get(i) + " " + strings.get(i));
}
}
// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
Scanner getLine = new Scanner(System.in);
Scanner input = new Scanner(getLine.nextLine());
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
Scanner input = (new Scanner(in));
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
}
Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.
Output:
Give me input:
apples 8 9 pears oranges 5
Ints gathered:
8 9 5
Strings gathered:
apples pears oranges
Data:
8 apples
9 pears
5 oranges
Probably not the best example; but, the point is that Scanner implements the Iterator class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>() methods; and then storing the input.
C/C++ has a notion of variable references, which makes creating something like scanf much easier. However, in Java, everything is passed by value. In the case of objects, their references are passed by value.
So, it's essentially impossible to have a concise equivalent to scanf. However, you can use java.util.Scanner, which does things similar to scanf.
So this C/C++:
int a;
float b;
scanf("%d %f", &a, &b);
is (roughly) equivalent to this Java:
int a;
float b;
try (Scanner sc = new Scanner(System.in)) {
a = sc.nextInt();
b = sc.nextFloat();
}
Java always takes arguments as a string type...(String args[]) so you need to convert in your desired type.
Use Integer.parseInt() to convert your string into Interger.
To print any string you can use System.out.println()
Example :
int a;
a = Integer.parseInt(args[0]);
and for Standard Input you can use codes like
StdIn.readInt();
StdIn.readString();
THERE'S an even simpler answer
import java.io.BufferedReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String myBeautifulScanf = new Scanner(System.in).nextLine();
System.out.println( myBeautifulScanf );
}
}