Reputation: 25
I have a text file with the name of "w1_slave" as follows:
3c 00 4b 46 ff ff 0d 10 16 : crc=16 YES
3c 00 4b 46 ff ff 0d 10 16 t=29937
From the above, I only need to extract the integer number 29937, and my code is:
public static void main(String[] args) throws IOException {
// create token1
String token1 = "";
// create Scanner inFile1
@SuppressWarnings("resource")
// detect delimiter "," and " "
Scanner w1Slave = new Scanner(new File("C:/Users/Hamid/Desktop/w1_slave.txt")).useDelimiter(",| ");
List<String> temps = new ArrayList<String>();
// while loop
while (w1Slave.hasNext()) {
// find next line
token1 = w1Slave.next();
temps.add(token1);
}
w1Slave.close();
String[] tempsArray = temps.toArray(new String[0]);
int tempsArrayLength = tempsArray.length - 1;
System.out.println(tempsArray[tempsArrayLength]);
The output is t=29937. Could you tell me how I can extract just 29937 as an integer or double number, please?
Upvotes: 2
Views: 121
Reputation: 22631
The easiest way would be to add =
as a delimiter - replace
.useDelimiter(",| ");
with
.useDelimiter(",|= ");
To convert it to a double
, use
double value = 0;
try {
value = Double.parseDouble(temps.get(temps.size() - 1));
} catch (NumberFormatException e) {
// not a number - do something
}
You don't need to convert the list to an array - you can delete this part of your code:
String[] tempsArray = temps.toArray(new String[0]);
int tempsArrayLength = tempsArray.length - 1;
System.out.println(tempsArray[tempsArrayLength]);
Upvotes: 5
Reputation: 39
You was very near to your code. i think you need to modify your code like this
public static void main(String[] args) throws IOException {
// create token1
String token1 = "";
// create Scanner inFile1
@SuppressWarnings("resource")
// detect delimiter "," and " "
Scanner w1Slave = new Scanner(new File(C:/Users/Hamid/Desktop/w1_slave.txt")).useDelimiter(",| ");
List<String> temps = new ArrayList<String>();
// while loop
while (w1Slave.hasNext()) {
// find next line
token1 = w1Slave.next();
temps.add(token1);
}
w1Slave.close();
String[] tempsArray = temps.toArray(new String[0]);
int tempsArrayLength = tempsArray.length - 1;
String str[]=tempsArray[tempsArrayLength].split("=");
// System.out.println(tempsArray[tempsArrayLength]);
int i=Integer.parseInt(str[1]);
System.out.println(i);
}
Upvotes: 1
Reputation: 224
My suggestion would be to use the substring function.
String strNumber = tempsArray[tempsArrayLength].substring(2);
Then use parseInt to get the integer value.
int nNumber = Integer.parseInt(strNumber);
Upvotes: 1
Reputation: 3164
Use the parseInt or parseDouble functions:
int number = Integer.parseInt(tempsArray[tempsArrayLength]);
or
double number = Double.parseDouble(tempsArray[tempsArrayLength]);
Upvotes: 0