package Testing;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class testing {
// map to store the number of errors per user
private static Map<String, Integer> errorsPerUser = new HashMap<>();
// variable to store the number of jobs started
private static int jobsStarted = 0;
// variable to store the number of jobs completed
private static int jobsCompleted = 0;
public static void main(String[] args) {
// specify the path to the log file
String filePath = "C:/Users/Wafiq/Documents/WIX1002/GroupAssignment/extracted_log.txt";
try (Scanner scanner = new Scanner(new File(filePath))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
int timestampEndIndex = line.indexOf("]");
String lineWithoutTimestamp = line.substring(timestampEndIndex+2);
// check if line contains error message
if (lineWithoutTimestamp.contains("error: This association")) {
// extract the user from the line
String user = extractUser(lineWithoutTimestamp);
// increment the error count for the user
incrementErrorCount(user);
}
// check if line indicates job start
if (lineWithoutTimestamp.contains("sched: Allocate")) {
jobsStarted++;
}
// check if line indicates job completion
if (lineWithoutTimestamp.contains("_job_complete: JobId")) {
jobsCompleted++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// print the results
System.out.println("Number of jobs started: " + jobsStarted);
System.out.println("Number of jobs completed: " + jobsCompleted);
System.out.println("Number of errors per user:");
for (Map.Entry<String, Integer> entry : errorsPerUser.entrySet()) {
System.out.println(": " + entry.getValue());
}
}
// method to extract the user from the line
private static String extractUser(String line) {
// assuming the user is the string before "error" in the line
return line.substring(0, line.indexOf("error")).trim();
}
// method to increment the error count for the user
private static void incrementErrorCount(String user) {
if (errorsPerUser.containsKey(user)) {
errorsPerUser.put(user, errorsPerUser.get(user) + 1);
} else {
errorsPerUser.put(user, 1);
}
}
}
Output:
File data:
I'm trying to extract the number of jobs causing error and the corresponding user. I have done the number of jobs causing error but I don't know how to extract the number of corresponding user.
(p/s: Pls don't slander me, I'm a first year student in Comp Science. I have tried my best)
The user is not at the same index each line so I dont know how to extract it from the line.
While the user is not at the same index across lines, it always comes after user=' and ends on the next '. Search for these substrings in your line and you are done.
int startIndex = line.indexOf("user='");
if (startIndex>=0) {
int endIndex = line.indexOf("'", startIndex);
String user = line.substring(startIndex, endIndex);
System.out.println("user="+user);
} else {
System.out.println("no user in line");
}
Edit: I saw there is another pattern also in use. I think you can change the above algorithm to also allow for the second one.
There are two methods of same class .I want to compare two variables value by using assertion .
here are the two methods
//Method 1
public void Edit_window() throws InterruptedException {
collection_title.clear();
// driver.wait(2000);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
collection_title.sendKeys(dateFormat.format(date));
}
//Method 2
public void name_collection()
{
String updated_title=col_title.getText() ;
System.out.println("the title eof the collectio is " + updated_title) ;
System.out.println("the value is" + date) ;
}
So if you can see there is one variable "date " and it contains the current date. I want to that variable value and compare with the variable value "updated_title" which is defined in the method 2 . Any input please !
You can basically change the return type of the methods to String type and then add assertion. Sample below:
public String Edit_window() throws InterruptedException {
collection_title.clear();
// driver.wait(2000);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
collection_title.sendKeys(dateFormat.format(date));
return dateFormat.format(date);
}
public String name_collection()
{
String updated_title=col_title.getText() ;
System.out.println("the title eof the collectio is " + updated_title) ;
System.out.println("the value is" + date) ;
return date;
}
//And then for assertion you can basically: Assert.asserEquals(classObject.Edit_window(), classObject.name_collection);
Hope the solution provided by the Mrunal is works for you. I will suggest you to create a public class and store the Reusable values such as id, email, autogenerated numbers etc. So that you should be able to access anywhere from your framework.
we can't say that always we will only do the comparison in the same class. So please try to create the class as below and use it to store the values.
public class Repovalues {
private string id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
So I am trying to create a class that represents a fictional Licence Number for a given person. The Licence Number is constructed from the following:
The initials of the person's forename and surname
The year the licence was issued
A random arbitrary serial number
So for example, Maggie Smith whose licence was issued in 1990, might have a Licence Number of MS-1990-11, with 11 being the serial number. However, Mark Sanders might have had his licence issued the same year meaning the beginning of his licence may be MS-1990 also.
So this is where the problem occurs. I need to make sure that the serial number for this person is not the same as Maggie's. So I'd have to check through any records that have the same initials and issue year, then generate a new unique serial number. Here's my code so far:
public class LicenceNumber {
private final Name driverName;
private final Date issueDate;
private static final Map<String, LicenceNumber> LICENCENOS = new HashMap<String, LicenceNumber>();
public LicenceNumber(Name driverName, Date issueDate){
this.driverName = driverName;
this.issueDate = issueDate;
}
public static LicenceNumber getInstance(Name driverName, Date issueDate){
Calendar tempCal = Calendar.getInstance();
tempCal.setTime(issueDate);
String issueYear = String.valueOf(tempCal.get(Calendar.YEAR));
int serialNo = 1;
String k = driverName.getForename().substring(0, 1) + driverName.getSurname().substring(0, 1) + "-" + issueYear + "-" + serialNo;
if(!LICENCENOS.containsKey(k)){
LICENCENOS.put(k, new LicenceNumber(driverName,issueDate));
}
return LICENCENOS.get(k);
}
public boolean isUnique(){
return true;
}
public Name getDriverName() {
return driverName;
}
public Date getIssueDate() {
return issueDate;
}
}
And a snippet of how it may be instantiated:
public final class DrivingLicence {
private final Name driverName;
private final Date driverDOB;
private final Date issueDate;
private final LicenceNumber licenceNo;
private final boolean isFull;
public DrivingLicence(Name driverName, Date driverDOB, Date issueDate, boolean isFull){
//TO-DO validate inputs
this.driverName = driverName;
this.driverDOB = driverDOB;
this.issueDate = issueDate;
this.licenceNo = LicenceNumber.getInstance(driverName, issueDate);
//this.licenceNo = new LicenceNumber(driverName, issueDate);//instantiate a licence number using the driverName and dateOfIssue
this.isFull = isFull;
}
}
I've based it on some lecture notes that discuss how you can use factories for uniqueness. I'm also unsure if I should create a LicenceNumber using getInstance or by creating a new Object. Does anyone know a way I could check if a serial number for a given string, e.g. XX-XXXX already exists?
Here is an approach that will create incremental numbers for the duration of the program. Since there is no backing database, each run of the program will reset.
It works by using an AtomicInteger to ensure uniqueness. I have used a ConcurrentMap to take advantage of thread safety as well as the .putIfAbsent method. However, it can be easily converted to use a standard Map. I also just used a String, but a better approach would be to use a real domain object. It is sufficient for handling the OP's question and for illustrative purposes.
// a Map for holding the sequencing
private ConcurrentMap<String, AtomicInteger> _sequence =
new ConcurrentHashMap<>();
/**
* Returns a unique, incrementing sequence, formatted to
* 0 prefixed, 3 places, based upon the User's initials
* and the registration year
*/
public String getSequence(String initials, String year)
{
String key = makePrefix(initials, year);
AtomicInteger chk = new AtomicInteger(0);
AtomicInteger ai = _sequence.putIfAbsent(key, chk);
if (ai == null) {
ai = chk;
}
int val = ai.incrementAndGet();
String fmt = String.format("%03d", val);
return fmt;
}
/**
* A helper method to make the prefix, which is the
* concatintion of the initials, a "-", and a year.
*/
private String makePrefix (String initials, String year)
{
return initials + "-" + year;
}
Test Example:
public static void main(String[] args)
{
LicensePlate_37169055 lp = new LicensePlate_37169055();
System.out.println("ko, 1999: " + lp.getSequence("ko", "1999"));
System.out.println("ac, 1999: " + lp.getSequence("ac", "1999"));
System.out.println("ko, 1999: " + lp.getSequence("ko", "1999"));
System.out.println("ac, 1999: " + lp.getSequence("ac", "1999"));
System.out.println("ms, 1999: " + lp.getSequence("ms", "1999"));
System.out.println("ko, 2001: " + lp.getSequence("ko", "2001"));
}
Example Output:
ko, 1999: 001
ac, 1999: 001
ko, 1999: 002
ac, 1999: 002
ms, 1999: 001
ko, 2001: 001
To integrate into the OP's code, the following modifications are suggestive:
public static LicenceNumber getInstance(Name driverName, Date issueDate){
Calendar tempCal = Calendar.getInstance();
tempCal.setTime(issueDate);
String issueYear = String.valueOf(tempCal.get(Calendar.YEAR));
// ** get the initials; I would actually move this functionality to be
// a method on the Name class
String initials = driverName.getForename().substring(0, 1) + driverName.getSurname().substring(0, 1);
// get the unique serial number
String serial = getSequence(initials, issueYear);
// make the full licenseplate String
String k = makePrefix(initials, issueYear) + "-" + serial;
if(!LICENCENOS.containsKey(k)){
LICENCENOS.put(k, new LicenceNumber(driverName,issueDate));
}
return LICENCENOS.get(k);
}
I've got a class named "User" which has a method that makes the User type his name. This name is saved in an array that is empty at first.
Question is, how can I use this "stored" name in another class (I want to show the name in this other class)
Here's what I've got (Sorry for the spanish lol)
public class Usuario {
private Scanner entrada = new Scanner(System.in);
private String Usuario[] = new String[20];
private int Posicion = 0;
private int punteo;
public void Datos() {
System.out.println("Ingresa tu nombre");
if(Usuario[Posicion] == null) {
this.Usuario[0] = entrada.nextLine();
Posicion++;
}
}
public String Usuario() {
return Usuario[Posicion-1];
}
And I want to use the name (Usuario[Posicion-1]) for example in a class like this:
public class Score extends Usuario {
Usuario usr = new Usuario();
String[] Name = new String[20];
public void Score () {
Name[0]=usr.Usuario();
System.out.println("------------Scores ------------------");
System.out.println(" Name "+ " Score");
for(int i=0;i<11;i++) {
System.out.println(i+".- " + " "+Name[0] +" 200 ");
}
}
}
But Everytime I try to retrieve this data in this class I get a "null" value or an "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1" error, which makes me believe that I can't use the information from the array in another class :(
I'd appreciate any help. (also Sorry for the not-so-good english).
Each new version of a class or an object is not going to have the same values.
you will have to get the name from the object User.name then set it in your other object secondObject.name = User.name
So I have a string variable which is meant to hold names of cars separated by commas.
String cars = "";
What I want to do is append cars to this string. The way a new car would be added:
String newCar1 = "Mini";
String newCar2 = "LandRover";
appendToCars(newCar1);
appendToCars(newCar2);
Then currently I have this, which I primarily need help with.
public void appendToCars(String newCar)
{
cars = cars + "," + newCar;
}
So output should be:
Mini,LandRover
but it's:
[,]Mini
Been racking my brain about this for hours figuring out how to do it, but I just can't get the result I actually want.
Im also using a JUnit test for this which reads :
#Test
public void testAppendToCars() {
System.out.println("appendToCars");
String newCar1 = "Mini";
String newCar2 = "LandRover";
String expResult = newCar1 + "," + newCar2;
testDel.appendToCars(newCar1);
testDel.appendToCars(newCar2);
String result = testDel.getCars();
assertEquals("Delivery notes incorrectly stored", expResult, result);
I think you just have a variable scope issue. This example uses your code but takes the scope into consideration:
public class temp {
static String cars = "";
public static void appendToCars(String something)
{
if (cars.equals("")){
cars = something;
}
else {
cars= cars + "," + something;
}
}
public static void main(String[] args){
String newcar1 = "Mini";
String newcar2 = "LandRover";
appendToCars(newcar1);
appendToCars(newcar2);
System.out.println(cars);
}
}
This class will return the following:
Mini,LandRover