How to take input in expected form in java? - java

I want to take a string input in
%d+%d
format in java.How do i do it?
I know that I can do this with string.split() method. But I feel that it is going to be way more complex if I had to deal with more strings in input. Like
%d+%d-%d
I am looking for solutions that are close to a scanf solution for c.
I tried this for %d+%d
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
String first,second;
String[] arr = str.split("\\+");
first = arr[0];
second = arr[1];
scanner.close();
And this for %d+%d-%d+%d..........=%d-%d+%d.....+%d...
private final String[] splitLoL(String txt) {
LinkedList<String> strList1 = new LinkedList<String>();
LinkedList<String> strList2 = new LinkedList<String>();
LinkedList<String> strList3 = new LinkedList<String>();;
strList1.addAll(Arrays.asList(txt.split("\\+")));
for(String str : strList1) {
String[] proxy = str.split("-");
strList2.addAll(Arrays.asList(proxy));
}
for(String str : strList2) {
String[] proxy = str.split("=");
strList3.addAll(Arrays.asList(proxy));
}
String[] strArr = new String[strList3.size()];
for(int i = 0; i < strArr.length; i++) {
strArr[i] = new String(strList3.get(i));
}
return strArr;
}

Try this:
String str = scanner.nextLine();
List<String> str2 = new ArrayList();
Matcher m = Pattern.compile("\\d+").matcher(str);
while(m.find()) {
str2.add(m.group());
}

Or you can do the following using JDK 9+:
import java.util.Scanner;
public class ScannerTrial {
public static void main(String[] args) {
Scanner scanner = new Scanner(" 4 z zz ggg 22 e");
scanner.findAll("\\d+").forEach((e) -> System.out.println(e.group()));
}
}
This would print
4 22

Related

filling an array with a date from user input

So I am trying to fill an array with the date in a specific format (0000/00/00) then tokenize it on the "/" characters, then print it back in the format MM-DD-YYYY. I am having some trouble with tokenizing it. I'm new to this, what did I miss?
public static void main(String[] args) {
String[] date = new String[1];
date[0] = "0000/00/00";
Scanner s = new Scanner(System.in);
do {
System.out.println("Enter your date, format must be YYYY/MM/DD - include slashes");
date[0] = s.nextLine();
for (int i = 0; i < date.length; i++)
String[] tokens = date[i].split("/");
} while (true);
}
Try this :
String str[] = date[i].split("\\\");

How can i split String in java with custom pattern

I am trying to get the location data from this string using String.split("[,\\:]");
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
String[] str = location.split("[,\\:]");
How can i get the data like this.
str[0] = 27.980194
str[1] = 46.090199
str[2] = 0.48
str[3] = 1
str[4] = 6
Thank you for any help!
If you just want to keep the numbers (including dot separator), you can use:
String[] str = location.split("[^\\d\\.]+");
You will need to ignore the first element in the array which is an empty string.
That will only work if the data names don't contain numbers or dots.
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
Matcher m = Pattern.compile( "\\d+\\.*\\d*" ).matcher(location);
List<String> allMatches = new ArrayList<>();
while (m.find( )) {
allMatches.add(m.group());
}
System.out.println(allMatches);
Quick and Dirty:
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
List<String> strList = (List) Arrays.asList( location.split("[,\\:]"));
String[] str = new String[5];
int count=0;
for(String s : strList){
try {
Double d =Double.parseDouble(s);
str[count] = d.toString();
System.out.println("In String Array:"+str[count]);
count++;
} catch (NumberFormatException e) {
System.out.println("s:"+s);
}
}

NumberFormatException: For input string: "2"

I have a list of strings. First element is:
2 helloworld 10173.991234
I've written the code below:
ArrayList<Integer> idList = new ArrayList<Integer>();
for (String s:list){
String subs = s.substring(0,8);
subs = subs.trim();
idList.add(Integer.valueOf(subs));
}
This code shoud parse first id field and add it to arraylist.
But it fails on line idList.add(Integer.valueOf(subs));
Whats the problem? Any help?
Upd:
public class Solution {
public static void main(String[] args) throws Exception {
if (args[0].equals("-c")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileString = reader.readLine();
reader.close();
Scanner scanner = new Scanner(new File(fileString));
ArrayList<String> list = new ArrayList<String>();
while (scanner.hasNextLine()) {
list.add(scanner.nextLine());
}
String ne = list.get(list.size()-1);
scanner.close();
int maxId;
if (ne.length()>1) {
ArrayList<Integer> idList = new ArrayList<Integer>();
for (String s:list){
String subs = s.substring(0,8);
subs = subs.trim();
idList.add(Integer.parseInt(subs));
}
maxId = idList.get(0);
for (int i:idList){
if (maxId<i){
maxId=i;
}
}
maxId++;
}
else {
maxId = 0;
}
String maxIdString = ""+maxId;
while (maxIdString.length()<8){
maxIdString+=" ";
}
if (maxIdString.length()>8){
maxIdString = maxIdString.substring(0,8);
}
String productName = "";
for (int i = 1; i < args.length-2; i++) {
productName+=args[i]+" ";
}
productName = productName.trim();
while (productName.length()<30){
productName+=" ";
}
if (productName.length()>30)
productName=productName.substring(0,30);
String price = args[args.length-2];
while (price.length()<8){
price+=" ";
}
if (price.length()>8)
price=price.substring(0,8);
String quantity = args[args.length-1];
while (quantity.length()<4){
quantity+=" ";
}
if (quantity.length()>4)
quantity=quantity.substring(0,4);
String outString = maxIdString+productName+price+quantity;
FileOutputStream outputStream = new FileOutputStream(fileString,true);
if (ne.length()>1)
outputStream.write("\r\n".getBytes());
outputStream.write(outString.getBytes());
outputStream.close();
}
}
}
It's the content of the file
2 helloworld 10173.991234
124 helloworld 10173.991234
125 helloworld 10173.991234
Program arguments, for example:
-c helloworld 10173.99 1234
I found what the problem was :) It was in UTF-8 coding. I understood it after starting to use Notepad++ application.

java split string into string array produce first value wrong

Input string:
-;Lokacija;-;Pozicija;Grad;-;-;
Code:
public static ArrayList<String> sortList = new ArrayList<String>();
//Load
String Row = new String("-;Lokacija;-;Pozicija;Grad;-;-;");
String[] RowAsList;
RowAsList = Row.split(";");
sortList.add( RowAsList[0] );
// Check
StringBuffer minus = new StringBuffer( "-");
String itm = sortList.get(0);
if( !itm.contentEquals( minus ) )
// not minus
else
.....
Problem: this code says there is no minus on first item (0), subsequent minuses are recognized correctly.
Anyone has any ideas as to why ?
Thanks,
Kajko
Remove the static modifier before the sortList member:
public List<String> sortList = new ArrayList<String>();
Thats what you want
public class Test
{
public static ArrayList<String> sortList = new ArrayList<String>();
public static void main(String a[])
{
//Load
String Row = new String("-;Lokacija;-;Pozicija;Grad;-;-;");
String[] RowAsList;
RowAsList = Row.split(";");
for(int i=0;i<RowAsList.length-1;i++) {
sortList.add(RowAsList[i]);
}
System.out.println(sortList);
// Check
StringBuffer minus = new StringBuffer("-");
String itm = sortList.get(0);
if( itm.contentEquals( minus ) )
System.out.println(sortList.get(0));
// not minus
else
System.out.println("not found...");
}
}
Try :
String Row = new String("-;Lokacija;-;Pozicija;Grad;-;-;");
ArrayList<String> sortList = new ArrayList<String>();
String[] RowAsList= Row .split(";");
sortList.add( RowAsList[0]);
StringBuffer minus = new StringBuffer( "-");
String itm = sortList.get(0);
if( itm.equals( minus.toString())){
System.out.println("Get Here" + itm);
}
else{
System.out.println("Not Here"+ itm);
}

Adding text read from a file to an array list in java

I am having trouble putting text read from a file into an array list.
My text looks like this:
438;MIA;JFK;10:55;1092;447
638;JFK;MIA;19:45;1092;447
689;ATL;DFW;12:50;732;448 etc...
My code looks like this:
package filesexample;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
/**
*
* #author
*/
public class FilesExample {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
File file = new File ("/Schedule.txt");
try
{
Scanner scanner= new Scanner(file);;
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
Scanner lineScanner= new Scanner(line);
lineScanner.useDelimiter(";");
while(lineScanner.hasNext()){
String part = lineScanner.next();
System.out.print(part + " ");
}
System.out.println();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
Some help on getting started would be much appreciated thank you!
You don't need to do the following
Scanner lineScanner= new Scanner(line);
lineScanner.useDelimiter(";");
Just do
String[] parts = line.split(";");
They all need to have there own array for each category, so flight
number will need its own array, origin its own array
I would say, don't. You don't need to have separate array for each of them.
I would rather create a class with attributes: -flight number, origin, destination, time, miles and price.
Now for every line, I would just split it on ;, and have a constructor in the class that takes an array as parameter. And rather than having separate ArrayList for each of those parameters, I would have an ArrayList of that class instance.
class Flight {
private int flightNumber;
private String origin;
private String destination;
... so on for `time, miles and price`
public Flight(String[] attr) {
this.flightNumber = Integer.parseInt(attr[0]);
this.origin = attr[1];
this.destination = attr[2];
... so on.
}
}
And then where you are using: -
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(";");
I would use String#split() to get individual attributes, and then create an ArrayList<Flight>, and add Flight instance to it: -
List<Flight> flights = new ArrayList<Flight>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] attributes = line.split(";");
flights.add(new Flight(attributes));
}
NOTE : -
You can improve upon how you instantiate your Flight class, and how you set different attributes. Since your attributes are of different types, and they are in String form, so you would need to use appropriate conversion from String to Integer or String to double which I have not considered here.
use String.split(delimiter) to split your String.
List<String> list = new ArrayList<String>();
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
String[] strArr = line.split(";");
for(String s: strArr){
list.add(s); //adding a string into the list
System.out.println(s + " ");
}
}
System.out.println();
EDIT: From your comments
of the text I posted, the first number is flight number, origin, destination, time, miles and price. They all need to have
there own array for each category, so flight number will need its own
array, origin its own array etc.
you don't need an array for each property. create a class and name it Filght. and make your properties as instance variables.
class Flight {
private long filghtNo;
private String origin;
private dest;
private Date time;
private long miles;
private double price;
//setters and getters
}
List<Flight> list = new ArrayList<Flight>();
Flight flight = new Flight();
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
Scanner scan = new Scanner(line);
if(scan.hasNextLong()){
flight.setFilgthNo(scan.nextlong());
}
else if // do the same for other properties
}
list.add(flight);
This way is more Object Oriented.
I re-iterate the need for a more OO approach but here is what you need for what you asked for.
public final class FlightInfoParser {
private static final String[] EMPTY_STRING_ARRAY = new String[]{};
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
List<String> flightNumbersList = new ArrayList<String>();
List<String> originsList = new ArrayList<String>();
List<String> destinationsList = new ArrayList<String>();
List<String> departureTimesList = new ArrayList<String>();
List<Integer> milesList = new ArrayList<Integer>();
List<Double> pricesList = new ArrayList<Double>();
String line;
while ((line = r.readLine()) != null) {
String[] fields = line.split(";");
flightNumbersList.add(fields[0]);
originsList.add(fields[1]);
destinationsList.add(fields[2]);
departureTimesList.add(fields[3]);
milesList.add(Integer.parseInt(fields[4]));
pricesList.add(Double.parseDouble(fields[5]));
}
String[] flightNumbersArray = flightNumbersList.toArray(EMPTY_STRING_ARRAY);
String[] originsArray = originsList.toArray(EMPTY_STRING_ARRAY);
String[] destinationsArray = destinationsList.toArray(EMPTY_STRING_ARRAY);
String[] departureTimesArray = departureTimesList.toArray(EMPTY_STRING_ARRAY);
int[] milesArray = new int[milesList.size()];
for (int i = 0, len = milesArray.length; i < len; ++i) {
milesArray[i] = milesList.get(i);
}
double[] pricesArray = new double[pricesList.size()];
for (int i = 0, len = pricesArray.length; i < len; ++i) {
pricesArray[i] = pricesList.get(i);
}
}
}

Categories