User defined variable displayed as 48 and not 0 - groovy

I created a user defined variable i and put value 0.
In groovy I try to run on a list starting [i], but it returned 48.
when I hard coded put 0, the script is OK
why I is set to 48?
List<String> myList = props.get("myListKey");
int i = vars.get("i");
String id = myList[i];
//String id = myList[0];
System.out.println("id: " + id);
vars.putObject("id", id);
System.out.println("I is: " + i);

The correct way to convert String to number in groovy is using toInteger() function:
int value = vars.get("i").toInteger()
log.info("I2 is: " + value);
Currently you return the ASCII value of character 0 (48). you can check also other options to convert String to int.

Related

C# How to find substring in string?

I have this data:
AC level : FAIL
ADC AC - 0x0440
AC level : FAIL
Average ADC Batt - 0x733e
I want to get the Adc Ac value for example the 0x0440 but when I want to store it in the database ,the output will display 0x737eBatt Level : MidADC but it happened intermittently.
Here is my code:
public static string getBetween(string strSource, string strStart, string strEnd)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
int Start, End;
Start = strSource.IndexOf(strStart, 1) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
return "";
}
// Find ADC value
string ADC = getBetween(serialdata, "-", "AC");
You should probably try to extract the values by their key, rather than relying on characters before and after. In your example the string "AC" already appears twice before the text that you are interested in. Try a function like the following, to get any value:
static bool TryGetValue(string serialData, string key, out string value)
{
var m = Regex.Match(serialData, $".*{Regex.Escape(key)}\\s*[-:](?<value>.*)$", RegexOptions.Multiline);
value = m.Groups["value"].Value.Trim();
return m.Success;
}
you'd call it like this:
if (TryGetValue(serialData, "ADC AC", out var value))
{
Console.WriteLine(value);
}

Code for creating string in a loop to report numbers

I created a code that functions as it is supposed to. I determined the escape function to be -1 for the user to exit the program and used if/else to only add the sum of positive integers.
I know that I have to save the numbers that pass the if statement (only positive numbers) and the only way that I can think of doing this is through a String.
Unfortunately, whenever I attempt to add a string as part of the while loop, it will print the statement over and over again when I only want a single line.
I'm also struggling to set the user input to a single line. I know it has everything to do with the .nextLine() command, but if I pull it outside the brackets (which I've attempted to do) then it reads as an error.
Actually, a source about conversion of Strings to characters or inputs to Strings would be very helpful as well. It's apparent that this is where a good portion of my understanding is lacking.
public static void main(String args[])
{
int userNum = 0;
int sum = 0;
Scanner s = new Scanner(System.in);
String str3;
System.out.print("Enter positive integers (to exit enter -1):\n ");
//Loop for adding sum with exit -1
while(userNum != -1){
//condition to only calculate positive numbers user entered
if(userNum > 0){
//calculation of all positive numbers user entered
sum += userNum;
str3 = String.valueOf(userNum);}
userNum = s.nextInt();
}
System.out.println("The values of the sum are: " + str3);
System.out.println("The Sum: " + sum);
}
}
I'm hoping for the user input to be printed,
Enter positive integers (to exit enter -1): _ _ ___//with the user
input in the same row.
And...
values from string to read out on same line, not multiple lines.
The variable str needs to be initialized as:
String str3 = "";
and in the loop, each entered number must be concatenated to str.
int userNum = 0;
int sum = 0;
Scanner s = new Scanner(System.in);
String str3 = "";
System.out.print("Enter positive integers (to exit enter -1):\n ");
while (userNum != -1) {
userNum = s.nextInt();
if (userNum > 0) {
sum += userNum;
str3 += " " + userNum;
}
}
System.out.println("The values of the sum are: " + str3);
System.out.println("The Sum: " + sum);

Swift OS X String to Int Conversion Error

I'm having trouble converting a String to Int in my Swift OS X Xcode project. I have some data saved in a text file in a comma delimited format. The contents of the text file is below:
1,Cessna 172,3,54.4,124,38.6112
(and a line break at the end)
I read the text file and seperate it, first by \n to get each line by itself, and then by , to get each element by itself. The code to do this is below:
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent("FSPassengers/aircraft.txt")
do {
let content = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
if content != "" {
let astrContent:[String] = content.componentsSeparatedByString("\n")
for aeroplane in astrContent {
let aSeperated:[String] = aeroplane.componentsSeparatedByString(",")
print(aSeperated[0])
print(Int(aSeperated[0]))
//self.aAircraft.append(Aircraft(id: aSeperated[0], type: aSeperated[1], passengerCapacity: Int(aSeperated[2])!, cargoCapacityKg: Double(aSeperated[3])!, cruiseSpeed: Int(aSeperated[4])!, fuelLitresPerHour: Double(aSeperated[5])!))
}
}
}
catch {
print("Error")
}
}
The end result here will be to assign each record (each line of the text file) into the array aAircraft. This array is made up of a custom object called Aircraft. The custom class is below:
class Aircraft: NSObject {
var id:Int = Int()
var type:String = String()
var passengerCapacity:Int = Int()
var cargoCapacityKg:Double = Double()
var cruiseSpeed:Int = Int()
var fuelLitresPerHour:Double = Double()
override init() {}
init(id:Int, type:String, passengerCapacity:Int, cargoCapacityKg:Double, cruiseSpeed:Int, fuelLitresPerHour:Double) {
self.id = id
self.type = type
self.passengerCapacity = passengerCapacity
self.cargoCapacityKg = cargoCapacityKg
self.cruiseSpeed = cruiseSpeed
self.fuelLitresPerHour = fuelLitresPerHour
}
}
In the first code extract above, where I split the text file contents and attempt to assign them into the array, you will see that I have commented out the append line. I have done this to get the application to compile, at the moment it is throwing me errors.
The error revolves around the conversion of the String values to Int and Double values as required. For example, Aircraft.id, or aSeperated[0] needs to be an Int. You can see that I use the line Int(aSeperated[0]) to convert the String to Int in order to assign it into the custom object. However, this line of code is failing.
The two print statements in the first code extract output the following values:
1
Optional(1)
If I add a ! to the end of the second print statement to make them:
print(aSeperated[0])
print(Int(aSeperated[0])!)
I get the following output:
I understand what the error means, that it tried to unwrap an optional value because I force unwrapped it, and it couldn't find an Int value within the string I passed to it, but I don't understand why I am getting the error. The string value is 1, which is very clearly an integer. What am I doing wrong?
Because Casena 172 is not convertible to an Int. You also have other decimal numbers which you will lose precision when casting them to Int. Use NSScanner to create an initializer from a CSV string:
init(csvString: String) {
let scanner = NSScanner(string: csvString)
var type: NSString?
scanner.scanInteger(&self.id)
scanner.scanLocation += 1
scanner.scanUpToString(",", intoString: &type)
self.type = type as! String
scanner.scanLocation += 1
scanner.scanInteger(&self.passengerCapacity)
scanner.scanLocation += 1
scanner.scanDouble(&self.cargoCapacityKg)
scanner.scanLocation += 1
scanner.scanInteger(&self.cruiseSpeed)
scanner.scanLocation += 1
scanner.scanDouble(&self.fuelLitresPerHour)
}
Usage:
let aircraft = Aircraft(csvString: "1,Cessna 172,3,54.4,124,38.6112")
As #mrkxbt mentioned, the issue was related to the blank line after the data in the text file. The string was being split at the \n which was assigning two values into the array. The first value was a string containing the data and the second was an empty string, so obviously the second set of splitting (by ,) was failing. Amended and working code is below:
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent("FSPassengers/aircraft.txt")
do {
let content = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
if content != "" {
let astrContent:[String] = content.componentsSeparatedByString("\n")
for aeroplane in astrContent {
if aeroplane != "" {
let aSeperated:[String] = aeroplane.componentsSeparatedByString(",")
print(aSeperated[0])
print(Int(aSeperated[0])!)
self.aAircraft.append(Aircraft(id: Int(aSeperated[0])!, type: aSeperated[1], passengerCapacity: Int(aSeperated[2])!, cargoCapacityKg: Double(aSeperated[3])!, cruiseSpeed: Int(aSeperated[4])!, fuelLitresPerHour: Double(aSeperated[5])!))
}
}
}
}
catch {
print("Error")
}
}

Binary search of an ArrayList object method to retrieve a string will not identify if strings are identical?

The program in it's entirety sorts an ArrayList of Student objects by integers highest average, last name, and also has the option to perform a search. My program works flawlessly except for my binary search, for which I can absolutely not determine the cause of failure. I have printed all the information as it comes up.
Here is the student class with the method that references the Student's first and last name (String).
public String getFirstName (){
return firstname;
}
public String getLastName(){
return lastname;
}
In addition, here is the code for the binary search. Yes, I know Collections has a method for this exact purpose, but for my class I need to write up the search myself.
private static void searchStudent(ArrayList<Student> a){
Scanner reader = new Scanner(System.in);
System.out.print("Please enter search term: ");
String term = reader.next();
//System.out.println(term + " " + term.length());
System.out.println("---SEARCH RESULTS:---");
for (int i = 0; i < a.size(); i++){
String fName = (a.get(i).getFirstName());
String lName = (a.get(i).getLastName());
//System.out.println(fName + " " + fName.length());
//System.out.println(lName + " " + lName.length());
if (term == fName){
System.out.println(a.get(i));
} else if (term == lName){
System.out.println(a.get(i));
}
}
}
In Java, you need to use .equals() to compare strings. E.g. instead of this:
if (term == fName){
you need to do this:
if (term.equals(fName)){
Otherwise, you are comparing references only.
Btw, this is not a binary search, it's a linear search. You can see one implementation of binary search e.g. here:
http://leepoint.net/notes-java/algorithms/searching/binarysearch.html
though to compare strings you would use .compareTo / .compareToIgnoreCase methods on the String class instead of < / > operators.

Prefix '0' to the int variable which less than '10', How?

Is there any simple method to concatenate '0' before an int variable.
Like:
int i = 2;
// produce
i = someMethod(i);
// output:
i = 02
If you mean "concatenate", then you can define someMethod() as follows:
string someMethod(int i){
return string.Format("{0:d2}", i);
}
The "2" in the string format defines the number of characters in the output.

Resources