Extract data from txt file in java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 days ago.
Improve this question
i have a text file which contain data for a given month in days,like below. The data sequence can be different and other tags can also be there such as Unnecessary info. i need to extract some tags such as Date, "Min Temperatue", "Min Temperatue time", "Max Temperature", "Max Temperatue time", "Average Temperature". what approach to use ??your text`
> `Device: HAIER
Version: 23.2
Sensor: 1
Ext Sensor: 1
1:
Date: 2023-02-14
Unnecessary info : ignore
Min Temperature: +5.7, Min Temperature time: 00:15
Max Temperature: +6.1, Max Temperature time: 10:14
Average Temperature: +5.8
2:
Date: 2023-02-14
Min Temperature: +5.7, Min Temperature time: 00:15
Max Temperature: +6.1, Max Temperature time: 10:14
Unnecessary info : ignore
Average Temperature: +5.8
3:
Date: 2023-02-14
Min Temperatue: +5.7, Min Temperatue time: 00:15
Max Temperature: +6.1, Max Temperatue time: 10:14
Average Temperature: +5.8
4:
Date: 2023-02-14
Min Temperatue: +5.7, Min Temperatue time: 00:15
Max Temperature: +6.1, Max Temperatue time: 10:14
Average Temperature: +5.8`
I have tried using regex, but as i stated earlier the sequence can be different so the regex gets failed at times. i tried to use ANTLR aswell but could not achieve success.``

Here, I am trying to give solution on basis of your requirement and hope, this solution work for you. One thing I am trying to highlighted here is that, there is a miss spell for word Temperatue & Temperature.
And following solution is based on RegEx which I have consider a small mistake on mismatch word. Also, I have consider the sequence can be differ here. Still, I am assuming that required all tags must be present here.
public static void main(String[] args) throws Exception {
String filePath = ".... file name";
String data = readFileAsString(filePath);
List<String> dates = matchAll(data, "Date: (\\d{4}-\\d{2}-\\d{2})", 1);
List<String> minTemp = matchAll(data, "Min Temperatur?e: (\\+\\d+\\.\\d+)", 1);
List<String> minTempTime = matchAll(data, "Min Temperatur?e time: (\\d{2}:\\d{2})", 1);
List<String> maxTemp = matchAll(data, "Max Temperatur?e: (\\+\\d+\\.\\d+)", 1);
List<String> maxTempTime = matchAll(data, "Max Temperatur?e time: (\\d{2}:\\d{2})", 1);
List<String> avgTemp = matchAll(data, "Average Temperatur?e: (\\+\\d+\\.\\d+)", 1);
int totalDateRecords = dates.size();
//Check, If Regex is properly work and collected records for all dates.
if(totalDateRecords == minTemp.size() && totalDateRecords == minTempTime.size()
&& totalDateRecords == maxTemp.size() && totalDateRecords == maxTempTime.size()
&& totalDateRecords == avgTemp.size())
{
for(int i = 0; i < totalDateRecords; i++) {
System.out.print("Date :"+dates.get(i));
System.out.print(" MinTemp :"+minTemp.get(i));
System.out.print(" MinTempTime :"+minTempTime.get(i));
System.out.print(" MaxTemp :"+maxTemp.get(i));
System.out.print(" MaxTempTime :"+maxTempTime.get(i));
System.out.println(" AvgTemp :"+avgTemp.get(i));
}
}
}
public static List<String> matchAll(String inputText, String expression, int groupNum) {
Matcher m = Pattern.compile(expression, Pattern.CASE_INSENSITIVE).matcher(inputText);
List<String> list = new ArrayList<String>();
while (m.find()) {
list.add(m.group(groupNum).trim());
}
return list;
}
public static String readFileAsString(String fileName)throws Exception{
return new String(Files.readAllBytes(Paths.get(fileName)));
}
Output for this program as follows:
Date :2023-02-14 MinTemp :+5.7 MinTempTime :00:15 MaxTemp :+6.1 MaxTempTime :10:14 AvgTemp :+5.8
Date :2023-02-14 MinTemp :+5.7 MinTempTime :00:15 MaxTemp :+6.1 MaxTempTime :10:14 AvgTemp :+5.8
Date :2023-02-14 MinTemp :+5.7 MinTempTime :00:15 MaxTemp :+6.1 MaxTempTime :10:14 AvgTemp :+5.8
Date :2023-02-14 MinTemp :+5.7 MinTempTime :00:15 MaxTemp :+6.1 MaxTempTime :10:14 AvgTemp :+5.8

Related

Basic for loop in java and data storage

I am very new to coding and I have a simple question. I want to input day, month and year inside a for loop and after inputting it I want to display all the inputted values on the same time. how to do it.kindly help me.
i have attached the code below.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=0;i<n;i++) {
int day = in.nextInt();
String month = in.next();
int year = in.nextInt();
}}
//need to display the entire content from the for loop
//suppose if the n value is 3
//i will be giving 3 inputs
//10 jan 1998
//11 nov 2000
//12 dec 1995
//i want to print all at the same time
Kindly help me with it.
If I understood your question correctly and you just want to print your inputs, just add the following to the loop:
System.out.println(String.format("%d %s %d", day, month, year));
or otherwise, but not as pretty (at least in my opinion):
System.out.println(day + " " + day + " " + month + " " + year);
EDIT
As indicated, you want to print them all at the same time. To do so, you can just save them all in a list or an array for example like the following:
Before the loop:
String[] dates = new String[n];
In the loop:
dates[i] = String.format("%d %s %d", day, month, year);
And then go ahead and insert another loop to print the content of the array:
for(String date: dates){
System.out.println(dates[i]);
}
From what I have gathered, you are looking to set a number on how many dates you'd like the user to enter, take in that number of dates and then print out the dates after the user input.
Here is some basic code that will do that for you
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int numOfInputs = 3; //How many separate dates you would like to enter
int day[] = new int[numOfInputs]; //declaring an integer array day and setting the array size to the value of numOfInputs
String month[] = new String[numOfInputs]; //declaring a string array month and setting the array size to the value of numOfInputs
int year[] = new int[numOfInputs]; //declaring an integer array year and setting the array size to the value of numOfInputs
//get inputs
for(int i=0;i<numOfInputs;i++) {
System.out.println("Please enter a day");
day[i] = sc.nextInt();
System.out.println("Please enter a month");
month[i] = sc.next();
System.out.println("Please enter a year");
year[i] = sc.nextInt();
}
//print content
for(int i=0;i<numOfInputs;i++) {
System.out.println(day[i] + " " + month[i] + " " + year[i]);
}
//close scanner
sc.close();
}
Let me know if this doesn't answer your question or if you need any clarification.

java.util.IllegalFormatPrecisionException error when rounding to the two-decimal places using printf

I'm a new java coder and am getting an error when using printf to round a value to twodecimal places. Can anyone help me understand why, and how to resolve the error?
Code
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
int age = 0;
int count = 0;
int round = 0;
while ((age < 12) || (age > 18))
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a non-teen age: ");
age = input.nextInt();
if ((age < 12) || (age > 18))
{
count = count + 1;
round = round + age;
}
}
System.out.println("Opps! " + age + " is a teen's age.");
System.out.println("Number of non-teens entered: " + count);
System.out.printf("Average of non-teens ages entered: %.2d", round);
}
}
Error:
Exception in thread "main" java.util.IllegalFormatPrecisionException: 2
at java.util.Formatter$FormatSpecifier.checkInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.<init>(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
Demo.main(Demo.java:31)
I guess the error is in this line
System.out.printf("Average of non-teens ages entered: %.2d", round);
'.2' does not make sense for decimal integers. Remove it:
System.out.printf("Average of non-teens ages entered: %d", round);
Integers can’t have decimal places since they don’t have a fractional part. Try using a float instead:
"Average of non-teens ages entered: %.2f"
Also, your round variable is currently storing a sum, so you need to divide it by count to get the average age:
System.out.printf("Average of non-teens ages entered: %.2f", (float)round / count);
Because your format specifiers don't match input arguments used in the printf method.
Use %f rather than %d as the format specifier character for int/double values.

Mapreduce-java: calcutaing average for array list

I have and assignment for mapreduce and I am very new in mapreduce programming.
I want to calculate for each year and specific city what is average, min and max values.
so here is my sample input
Calgary,AB,2009-01-07,604680,12694,2.5207754,0.065721168,0.025668362,0.972051954,0.037000279,0.022319018,,,0.003641149,,,0.002936745,,,0.016723641
Calgary,AB,2009-12-30,604620,12694,2.051769654,0.060114973,0.034026918,1.503277516,0.054219005,0.023258217,,,0.00354166,,,0.003361414,,,0.122375131
Calgary,AB,2010-01-06,604680,12266,4.015745522,0.097792741,0.032738892,0.368454554,0.019228992,0.032882053,,,0.004778065,,,0.003190444,,,0.064203865
Calgary,AB,2010-01-13,604680,12551,3.006492921,0.09051656,0.041508534,0.215395047,0.012081755,0.023706119,,,0.004231772,,,0.003083003,,,0.155212503
I know how to find city and year
I am using this code:
String line = value.toString();
String[] tokens = line.split(",");
String[] date = tokens[2].split("-");
String year = date[0];
String location = tokens[0];
Now I want to find these two numbers in each line (e.g.2.5207754,0.065721168 , not exactly the same but all the number after third and fourth comma) and find an average, a min and max.
and in the output should looks like this:
Calgary 2009 average: "" , min; "" , max: ""
Calgary 2010 average: "" , min; "" , max: ""
I was trying to use this code to find the values in each line but because the data set is in not the same in the each line I got error (in the part there is no data or bigger that this length)
float number = 0;
float number2 = 0 ;
char a;
char c;
a = line.charAt(34);
c = line.charAt(44);
if (a == ',')
{
number = Float.parseFloat(line.substring(35, 44));
}
else
{
number = Float.parseFloat(line.substring(35, 46));
}
if (c == ',')
{
number2 = Float.parseFloat(line.substring(45, 56));
} else
{
number = Float.parseFloat(line.substring(47, 58));
}
Text numbers = new Text(number + " " + number2 + " ");
Then I was trying to use this code and the same as above it doesn't work:
String number = tokens[4];
String number2 = tokens[5];
so can you help me to do this project?
Looking at your input, it seems your records are separated by space. You can first split using " " and then get the individual values and use them for calculation
String[] arr = line.split(" ");
for(String val : arr){
String[] dataArr = val.split(",");
String city = dataArr[0];
String date = dataArr[2];
String v1 = dataArr[5];
String v2 = dataArr[6];
System.out.println("city: "+city +" date: "+ date +" v1: "+ v1+"v2: "+ v2);
}
city: Calgary date: 2009-01-07 v1: 2.5207754v2: 0.065721168
city: Calgary date: 2009-12-30 v1: 2.051769654v2: 0.060114973
city: Calgary date: 2010-01-06 v1: 4.015745522v2: 0.097792741
city: Calgary date: 2010-01-13 v1: 3.006492921v2: 0.09051656
city: Calgary date: 2009-01-07 v1: 2.5207754v2: 0.065721168

Cost Calculator

My code needs to calculate the cost of ISP service via 3 different questions.
choice of package (1,2,3)
Which month it is: (1-12)
How many hours used:(x)
I broke the months into 3 separate arrays. One for Feb. with 28 days, one for months with 30 days and one with months that have 31 days. I need to check the number of hours entered and make sure that it does not exceed the amount of hours that are in whichever month they have chosen. I have started to with this:
import java.util.Scanner; //Needed for the scanner class
public class ISP_Cost_Calc
{
public static void main(String[] args)
{
String input; //To hold users input.
char selectPackage; //To hold Internet Package
double hourUsage, totalCharges, addCharges; //Variables
Scanner keyboard = new Scanner(System.in); //Create a Scanner object to collect keyboard input.
int[] twentyeightArray; //List of months with 28 days (that's what the te is for)
twentyeightArray = new int[1]; //Make room for one integer in list
twentyeightArray[0] = 2; //Set the one integer in this list to month number 2
int[] thirtyArray; //List of months with 30 days.
thirtyArray = new int[4];
thirtyArray[0] = 4;
thirtyArray[1] = 6;
thirtyArray[2] = 9;
thirtyArray[3] = 11;
int[] thiryoneArray; //List of months with 31 days.
thiryoneArray = new int[7];
thiryoneArray[0] = 1;
thiryoneArray[1] = 3;
thiryoneArray[2] = 5;
thiryoneArray[3] = 7;
thiryoneArray[4] = 8;
thiryoneArray[5] = 10;
thiryoneArray[6] = 12;
//Prompt the user to select a Internet Package.
System.out.print("Enter your plan (1, 2, 3):");
input = keyboard.nextLine();
selectPackage = input.charAt(0);
//Prompt the user for the month.
System.out.print("Enter your month number (1-12):");
input = keyboard.nextLine();
char monthNum = input.charAt(0);
//Prompt the user for how many hours used.
System.out.print("Enter your hours:");
input = keyboard.nextLine();
hourUsage = Double.parseDouble(input);
//Display pricing for selected package...
switch (selectPackage)
{
case '1':
if (hourUsage > 10)
{
addCharges = hourUsage - 10;
totalCharges = (addCharges * 2.0) + 9.95;
System.out.println("You have used " + hourUsage + " hours and your total is $" + totalCharges + " per month. ");
}
else
{
System.out.println("Your total is $9.95 per month.");
}
break;
case '2':
if (hourUsage > 20 )
{
addCharges = hourUsage - 20;
totalCharges = (addCharges * 1.0) + 13.95;
System.out.println("You have used " + hourUsage + " and your total is $" + totalCharges + " per month.");
}
else
{
System.out.println("Your total is $13.95 per month.");
}
break;
case '3':
System.out.println("Your total is $19.95 per month.");
break;
default:
System.out.println("Invalid Choice.");
}
}
}
So I just need advice with how to incorporate this into my if statements.
Thank you
Instead of using separate arrays to implement your month. You can do this:
int[] month = {31,28,31,30,31,30,31,31,30,31,30,31};
int[] monthLeapYear = {31,29,31,30,31,30,31,31,30,31,30,31};
You can check whether a given year is a leap year first, then choose the right array to use for the month. This way you only need 2 arrays - ever.
and you may have something like this to help you. I also advise you to create some methods in your implementation to modularize your program.
public static Boolean isLeapYear(int year)
{
if(year % 4 == 0 && year % 100 != 0)
return true;
return false;
}
The array is by index 0 - 11. That be can be over come by doing this:
//Let say your current month is 1-12
month[currentMonth-1]
Alternatively add 1 element to your array (so that the elements tally now):
int[] month = {0,31,28,31,30,31,30,31,31,30,31,30,31};
It may be easier if instead of using seperatre arrays for different numbers of days, you use an enum of Months which contains the number of days and the number of hours.
public enum Month {
JANUARY(31),FEBRUARY(28),MARCH(31),APRIL(30),MAY(31),JUNE(30),JULY(31),AUGUST(30),SEPTEMBER(30),OCTOBER(31),
NOVEMBER(30),DECEMBER(31);
private int hours;
private Month(int days){
hours = days*24;
}
public int getHours(){
return hours;
}
}
Using something like that would cut down on the unnecessary array use and combine everything into a single class. This would make it a lot easier to get the number of days and hours in each month.
Instead of creating multiple arrays, just use one array like:
month[0] = 31;
month[1] = 28;//what if leap year?
month[2] = 31;
//and so on
Then you could do something like:
int monthNumber = monthNum - 48;
if (hours > month[monthNumber - 1] * 24) {
//do something
} else {
//else do another thing
}
This is insane.
What is going to happen in 2016 when February will have 29 days instead of 28 days?
Stop using integers to represent hours. Use proper data types like DateTime and TimeSpan.
Get the DateTime at 00:00 of the 1st day of the selected month,
then get the DateTime at 00:00 of the 1st day of the next month,
then calculate the difference of these two to obtain a TimeSpan holding the duration of the selected month.
Then convert your hours to a TimeSpan and compare this against the duration of the selected month.
This will tell you whether the entered number of hours fits within the selected month.
To check conditions based on your months.You can use contains method of arraylist by converting array into arraylist as
Arrays.asList(your1stArray).contains(yourChar)
in your char just add the input no of the month
for eg:
switch (monthNum )
{
case '1':
if (Arrays.asList(your1stArray).contains(yourChar)){
//code goes here
}
case '1':
if (Arrays.asList(your2ndArray).contains(yourChar)){
//code goes here
}
)
)

How do I repeat an entire program until manually terminated? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
My code works fine except for the part where I am supposed to ask the user if they would like to quit the program. It's a simple y/n that should trigger the entire program to repeat if 'n' is entered and terminates when 'y' is entered. I know i need to use a while loop but i just can't figure out exactly how I need to write it in code so that it works like expected.
import java.util.*;
public class MilitaryTime
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int hour1, minute1, hour2, minute2;
System.out.print("Please enter the first time: ");
int time1 = in.nextInt();
System.out.println();
hour1 = time1 / 100;
minute1 = time1 % 100;
System.out.print("Please enter the second time: ");
int time2 = in.nextInt();
System.out.println();
hour2 = time2 / 100;
minute2 = time2 % 100;
System.out.println("Time elapsed: " + (Math.abs(hour1 - hour2) + " Hours, " + (Math.abs(minute1 - minute2) + " Minutes \n")));
System.out.print("Do you want to quit? (y/n): ");
String answer = in.next();
while (answer != "n")
{
}
}
}
You should probably split your code in (at least) two different methods, but I'll just try to point out a way to achieve what you want with minimal changes:
public static void main (String [] args)
{
String answer = null; // you have no answer yet...
do { // ... but you want to execute your stuff at least once
Scanner in = new Scanner(System.in);
int hour1, minute1, hour2, minute2;
System.out.print("Please enter the first time: ");
int time1 = in.nextInt();
System.out.println();
hour1 = time1 / 100;
minute1 = time1 % 100;
System.out.print("Please enter the second time: ");
int time2 = in.nextInt();
System.out.println();
hour2 = time2 / 100;
minute2 = time2 % 100;
System.out.println("Time elapsed: " + (Math.abs(hour1 - hour2) + " Hours, " + (Math.abs(minute1 - minute2) + " Minutes \n")));
System.out.print("Do you want to quit? (y/n): ");
answer = in.next();
} while (!answer.equalsIgnoreCase("n"));
}
Until then rerun the main method.
while (answer.equals("n")) // comment by drewmoore; its helpfull for strings..
{
// you said, program should repeat if n is pressed.
// so, if answer is equal to n then execute the main function.
main();
}
This would execute until the user presses some other button.
Secondly, you don't need to use while loop. This can be done using if too.

Categories