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("\\\");
Related
I want to make a method where I can read the text file to the array lists. My ArrayList contains objects, I use some system out println so I can detect where it went wrong, and turns out it's on the while loop part can anyone help me?
public class DataIO {
public static ArrayList<CitizenData> citizenData = new ArrayList<CitizenData>();
public static ArrayList<AppointmentData> appointment = new ArrayList<AppointmentData>();
public static void read(){
try{
Scanner s = new Scanner(new File("Citizen.txt"));
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
while(s.hasNext()){
String fullName = s.nextLine();
String numberID = s.nextLine();
int age = Integer.parseInt(s.nextLine());
Date date = formatter.parse(s.nextLine());
String address = s.nextLine();
String phoneNum = s.nextLine();
String email = s.nextLine();
s.nextLine();
CitizenData data = new CitizenData(fullName,numberID,age,date,address,phoneNum,email);
citizenData.add(data);
}
Scanner sc = new Scanner(new File("Appointment.txt"));
DateFormat formatter1 = new SimpleDateFormat("dd-MMM-yyyy");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm");
while(s.hasNext()){
CitizenData numberID = DataIO.check(s.nextLine());
VaccinationCentre vacCentre = VaccinationCentre.valueOf(s.nextLine());
LocalDateTime date = LocalDateTime.parse(s.nextLine());
String vaccineType = s.nextLine();
s.nextLine();
AppointmentData data1 = new AppointmentData(numberID, vacCentre, date,vaccineType);
appointment.add(data1);
}
}catch(Exception e){
System.out.println("Error in read");
}
}
public static void write(){
try{
PrintWriter p = new PrintWriter("Citizen.txt");
for(int i=0; i<citizenData.size(); i++){
p.println(citizenData.get(i).getFullName());
p.println(citizenData.get(i).getNumber());
p.println(citizenData.get(i).getAge());
p.println(citizenData.get(i).getDob());
p.println(citizenData.get(i).getAddress());
p.println(citizenData.get(i).getPhoneNum());
p.println(citizenData.get(i).getEmail());
p.println();
}
p.close();
PrintWriter q = new PrintWriter("Appointment.txt");
for(int i=0; i<appointment.size(); i++){
AppointmentData j = appointment.get(i);
q.println(j.getNumberID());
q.println(j.getVaccineCentre());
q.println(j.getDate());
q.println(j.getVaccineType());
q.println();
}
q.close();
} catch(Exception e){
System.out.println("Error in write!");
}
}
public static CitizenData check(String x){
for(CitizenData d : citizenData){
if(d.equals(d.getNumber())){
return d;
}
}
return null;
}
}
But here every time I run the code, it keeps on going to the catch and it says "error in read". Is my code wrong, but in which part of it?
I am trying to count the polysyllables from a text file. I have managed to count the syllables and few others(i.e., no. of words, sentence and etc.) but unable to get the count of polysyllables. Searched on internet and found very few information on polysyllables to work with. Appreciate if anyone could help.
static void syllableCount(String text) {
Pattern p = Pattern.compile("[aeiouy]+[^$e(,.:;!?)]");
Matcher m = p.matcher(text);
int syllables = 0;
while (m.find()){
syllables++;
}
System.out.println("Syllables: " + syllables);
}
public static void main(String[] args) {
//accept file name or directory name through command line args
//String fname =args[0];
//pass the filename or directory name to File object
File f = new File("in3.txt");
try (Scanner scanner = new Scanner(f)) {
while (scanner.hasNext()) {
String text = scanner.nextLine();
int words = text.split(" |\n|\t").length;
int sentences = text.split("\\.|\\?|!").length;
int characters = text.replaceAll(" |\n|\t","").split("").length;
syllableCount(text);
**//polySyllables(text);**
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
I have a hashmap of the following type
HashMap<String,List<Training>> map=new HashMap<String,List<Training>>();
Input:
topicName startDate endDate Trainer Venue
css 01-10-2017 11-11-2017 ccc hyd
html 01-10-2017 12-11-2017 www viz
python 10-10-2017 12-11-2017 www viz
Enter Date: 01-10-2017
The attributes/values to be displayed are like this :
Output:
topicName startDate endDate Trainer Venue
css 01-10-2017 11-11-2017 ccc hyd
html 01-10-2017 12-11-2017 www viz
I need to retrieve the details of list from getList().What code do i need to write in this method such that when user enters the date i can display output in the desired way as shown above.
public List<Training> getList(String fromDate) {
}
public static void main(String args[]) throws ParseException{
Map<String,List<Training>> map = new HashMap<String,List<Training>>();
Scanner sc = new Scanner(System.in);
System.out.println("Give me a size ");
int n = sc.nextInt();
for (int i = 0; i < n; i++){
String topicName = sc.next();
//DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//Date fromDate = dateFormat.parse(sc.next());
//Date toDate = dateFormat.parse(sc.next());
String fromDate = sc.next();
String toDate = sc.next();
System.out.println("fromDate********"+fromDate);
String trainer = sc.next();
String venue = sc.next();
List<Training> l1=new ArrayList<Training>();
l1.add(new Training(topicName,fromDate,toDate,trainer,venue));
//System.out.println("list********"+l1);
if(!map.containsKey(fromDate)){
map.put(fromDate,l1);
}else{
map.get(fromDate).add(new Training(topicName,fromDate,toDate,trainer,venue));
}
}
System.out.println("map********"+map);
}
#Override
public String toString() {
return gettopicName() + getfromDate() + gettoDate() + gettrainer() + getvenue() ;
}
Since, fromDate is the key for your Map. Then, you could simply get method which will give you List<Training>.
return map.get(fromDate);
If there are no value for specified key, then it will return null.
Try below code instead of creating Map based on from Date keep a list of training. If user enter date iterate over the training to filter it.
public List<Training> getList(List<Training> trainingList, Date date) {
List<Training> list = new ArrayList<Training>();
for( Training training : trainingList ) {
if( training.getFromDate().getTime() <= date.getTime() &&
date.getTime() <= training.getToDate().getTime() ) {
list.add(training);
}
}
return list;
}
public static void main(String args[]) throws ParseException{
Scanner sc = new Scanner(System.in);
List<Training> l1=new ArrayList<Training>();
System.out.println("Give me a size ");
int n = sc.nextInt();
for (int i = 0; i < n; i++){
String topicName = sc.next();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date fromDate = dateFormat.parse(sc.next());
Date toDate = dateFormat.parse(sc.next());
System.out.println("fromDate********"+fromDate);
String trainer = sc.next();
String venue = sc.next();
l1.add(new Training(topicName,fromDate,toDate,trainer,venue));
}
System.out.println("map********"+l1);
}
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);
}
}
}