I would like to read and write a Lowrance .usr file. This is a binary file with a particular data structure that I have managed to decode and have written a program in visual basic that does the necessary reading and writing. I am in the process of migrating this software to my android phone.
The Structure as I have defined it in VB is:
Public Structure WAYPOINT
Public wWaypointNum As Integer
Public dwLatitudeMM As Long
Public dwLongitudeMM As Long
Public dwAltitudeFT As Long
Public dwWaypointNmLength As Long
Public abWaypointName As Char()
Public wWaypointDescLength As Long
Public abWaypointDescription As Char()
Public dwWaypointTime As Long
Public dwWaypointSymbol As Long
Public wWaypointStatus As Integer
End Structure
The File is then read with the following code:
Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
Dim i As Integer
Dim objBR As BinaryReader
Dim objFS As FileStream
Dim objWP As New WAYPOINT
Dim objwVer As Integer
Dim objwSVer As Integer
Dim objNoWaypoints As Integer
Dim objNoRoutes As Integer
Dim TempLat As Double
Dim TempLng As Double
Dim LatString As String
Dim LngString As String
objFS = New FileStream("c:\Binary\Binary File\Binary File\waverider.usr", FileMode.Open)
objBR = New BinaryReader(objFS)
objBR.BaseStream.Seek(0, SeekOrigin.Begin)
objwVer = objBR.ReadInt16
objwSVer = objBR.ReadInt16
objNoWaypoints = objBR.ReadInt16
For i = 1 To objNoWaypoints
objWP = Nothing
With objWP
.wWaypointNum = objBR.ReadInt16
.dwLatitudeMM = objBR.ReadInt32
.dwLongitudeMM = objBR.ReadInt32
.dwAltitudeFT = objBR.ReadInt32
.dwWaypointNmLength = objBR.ReadInt32
.abWaypointName = objBR.ReadChars(.dwWaypointNmLength)
.wWaypointDescLength = objBR.ReadInt32
.abWaypointDescription = objBR.ReadChars(.wWaypointDescLength)
.dwWaypointTime = objBR.ReadInt32
.dwWaypointSymbol = objBR.ReadInt32
.wWaypointStatus = objBR.ReadInt16
End With
TempLat = objWP.dwLatitudeMM / EarthRad
TempLat = Math.Exp(TempLat)
TempLat = (2 * Math.Atan(TempLat)) - (Math.PI / 2)
TempLat = TempLat * RadToDeg
LatString = DegToDecMin(TempLat, "Lat")
TempLng = objWP.dwLongitudeMM / EarthRad
TempLng = Math.Exp(TempLng)
TempLng = (2 * Math.Atan(TempLng)) - (Math.PI / 2)
TempLng = TempLng * RadToDeg
LngString = DegToDecMin(TempLng, "Lng")
With lvWaypoints
Dim lv As ListViewItem = .Items.Add(objWP.abWaypointName)
With lv
.SubItems.Add(objWP.abWaypointDescription)
.SubItems.Add(LatString)
.SubItems.Add(LngString)
End With
End With
Next i
'\\ Read Routes
'objNoRoutes = objBR.ReadInt16 'Number of Routes
End Sub
The data is then decoded with:
Public Function DegToDecMin(ByVal DecDeg As Double, ByVal LatLng As String) As String
Dim ReturnValue As String
Dim Pos As String
If LatLng = "Lat" Then
If DecDeg < 0 Then Pos = "S" Else Pos = "N"
Else
If DecDeg < 0 Then Pos = "W" Else Pos = "E"
End If
Dim mDeg As Double = Math.Abs(DecDeg)
Dim mWholeDeg As Double = Math.Truncate(mDeg)
Dim mRemDegS As String = String.Format("{0:##.000}", (mDeg - mWholeDeg) * 60)
If InStr(mRemDegS, ".") = 2 Then mRemDegS = "0" & mRemDegS
If InStr(mRemDegS, ".") = 1 Then mRemDegS = "00" & mRemDegS
ReturnValue = mWholeDeg.ToString & Chr(176) & mRemDegS & "'" & Pos
Return ReturnValue
End Function
Are there similar functions in Java that can achieve the same objective
For the Java only syntax is changes according the Java Syntax,
First you need to create a bean file like below,
public class WayPoint
{
public int wWaypointNum;
public int dwLatitudeMM;
public dwLongitudeMM;
...
}
Second you required File API to read and write into and from file. For this you can use File, FileInputStream,FileOutputStream,DataInputStream,DataOutputStream.
Related
I want to get indexes of all the occurences of string_to_be_search
Input:
String line="hello this is prajakta , how are you?? hello this is prajakta!"
String text_to_search= "hello this is prajakta"
Here the occurrences of text_to_search is 2 so I need list of starting indexes
Output:
List l=[0,39]
Also I have tried a code below
public List getIndexesOfMultipleOccuredString(String originalString,String textToSearch) {
int i, last = 0, count = 0;
List l = new ArrayList();
do {
i = originalString.indexOf(textToSearch, last);
if (i != -1) l.add(i);
last = i + textToSearch.length();
} while (i != -1);
return l;
}
BUT
if my input is as follows
String line="hello this is prajakta ,i love to drive car and i am a carpainter"
String text_to_search="car"
Output:
It gives me two indexes as carpainter contains car which i don't want
Output should be [39]
This is how you do it using regex(word matching)
String line= "hello this is prajakta , how are you?? hello this is prajakta!";
String text_to_search = "\\bhello this is prajakta\\b";
ArrayList<Integer> list = new ArrayList<>();
Pattern p = Pattern.compile(text_to_search);
Matcher m = p.matcher(line);
while (m.find()) {
list.add(m.start());
}
Log.i("All occurrences", "values are " + list.toString());
Output: [0, 39]
If you search using these strings
String line="hello this is prajakta ,i love to drive car and i am a carpainter";
String text_to_search="car";// use as "\\bcar\\b"
Output [40]
final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
final EditText ed11 = (EditText)findViewById(R.id.totalweight);
recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
total_wt=ed11.getText().toString();
int rec = Integer.parseInt(recy_wt);
int nrec = Integer.parseInt(nonrec_wt);
ed11.setText(String.valueOf(rec + nrec));
The input I am giving is,ed7=10kg and ed8=20kg,and it will be displayed in ed11
as 30kg,but the app is unfortunately stopping.
If I am not writing 'kg',it is correctly displaying the totalwt.
But I want to display 'kg' in the answer.
There is already a solution here (can't flag as duplicate)
Find and extract a number from a string
Extract the digit part from the string and then parse it to an integer
Try this out
String regexp = "/^[0-9]+kg$/g"; //It accepts only '<number><kg>' format
int weight = 0;
if (recy_wt.matches(regexp) && nonrec_wt.matches(regex)) {
//It's valid input
Scanner scan = new Scanner(recy_wt);
weight = Integer.parseInt(scan.findInLine("\\d+(\\.\\d+)?"));
Scanner scan = new Scanner(nonrec_wt);
weight += Integer.parseInt(scan.findInLine("\\d+(\\.\\d+)?"));
}
ed11.setText(String.valueOf(weight + "Kg"));
If the only possible unit is kg, then try like this
final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
final EditText ed11 = (EditText)findViewById(R.id.totalweight);
int weight = 0;
recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
recy_wt = recy_wt.replace("kg","");
nonrec_wt = nonrec_wt.replace("kg","");
weight += Integer.parseInt(recy_wt) + Integer.parseInt(nonrec_wt);
ed11.setText(weight + "kg");
This will work:-
recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
String n=recy_wt.replace("kg","");
String n1=nonrec_wt.replace("kg","");
weight += Integer.parseInt(n) + Integer.parseInt(n1);
ed11.setText(weight + "kg");
storing the replaced one in a string and then converting to int will help.
I am working on writing a simple temperature conversion program, to familiarize myself with Android programming. The user types in a number to an EditText, and it converts it from Fahrenheit to Celsius, or vice versa, then puts the answer in a TextView. I want to append a Unicode Celsius/Fahrenheit symbol to the end of the answer before displaying it. When I don't have it appending the symbol, it works fine and displays the correct number, but when it is trying to append the symbol to the end, the output displays all wrong, with a long string of numbers at the end (and still no Unicode symbol).
Here's my code:
This is the converter utility class:
public class ConverterUtil {
//Convert to celsius
public static String convertFahrenheitToCelsius(float fahrenheit) {
float temperature = (fahrenheit - 32) * 5 / 9;
DecimalFormat df = new DecimalFormat("#.#");
return df.format(temperature) + R.string.celsius_symbol;
}
//Convert to fahrenheit
public static String convertCelsiustoFahrenheit(float celsius) {
float temperature = (celsius * 9) / 5 + 32; //Append the unicode Celsius symbol (\u2103), then return
DecimalFormat df = new DecimalFormat("#.#");a
return df.format(temperature) + R.string.fahrenheit_symbol; //Append the unicode Fahrenheit symbol (\u2109), then return
}
}
And this is where I call it:
public void calculateTemperature(){
RadioButton celsiusButton = (RadioButton) findViewById(R.id.button2);
TextView output = (TextView) findViewById(R.id.output);
if (text.getText().length() == 0) {
output.setText("");
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
String outputText = celsiusButton.isChecked() ? ConverterUtil.convertFahrenheitToCelsius(inputValue) : ConverterUtil.convertCelsiustoFahrenheit(inputValue);
output.setText(outputText);
}
If I take out the part where I append the Unicode symbols, it looks like this:
And if I put that back in, I get this:
How do I fix that?
Looks like the resourceID of your fahrenheit_symbol & celsius_symbol are getting appended to your text than the actual character.
Try this,
public class ConverterUtil {
//Convert to celsius
public static String convertFahrenheitToCelsius(Context context, float fahrenheit) {
float temperature = (fahrenheit - 32) * 5 / 9;
DecimalFormat df = new DecimalFormat("#.#");
return df.format(temperature) + context.getResources().getString(R.string.celsius_symbol);
}
//Convert to fahrenheit
public static String convertCelsiustoFahrenheit(Context context, float celsius) {
float temperature = (celsius * 9) / 5 + 32; //Append the unicode Celsius symbol (\u2103), then return
DecimalFormat df = new DecimalFormat("#.#");a
return df.format(temperature) + context.getResources().getString(R.string.fahrenheit_symbol); //Append the unicode Fahrenheit symbol (\u2109), then return
}
}
Change where you call it like this,
public void calculateTemperature(){
RadioButton celsiusButton = (RadioButton) findViewById(R.id.button2);
TextView output = (TextView) findViewById(R.id.output);
if (text.getText().length() == 0) {
output.setText("");
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
String outputText = celsiusButton.isChecked() ? ConverterUtil.convertFahrenheitToCelsius(YourActivity.this, inputValue) : ConverterUtil.convertCelsiustoFahrenheit(YourActivity.this, inputValue);
output.setText(outputText);
}
Change
return df.format(temperature) + R.string.fahrenheit_symbol;
return df.format(temperature) + R.string.celsius_symbol;
to
return df.format(temperature) + getString(R.string.fahrenheit_symbol);
return df.format(temperature) + getString(R.string.celsius_symbol);
R.string.fahrenheit_symbol and R.string.celsius_symbol are both integers. You will need to look up the relevant string resource using Context.getResources().getString().
You will need to pass a Context (such as the calling Activity) to your ConverterUtil.
example i have
String = "makan"
how to check last character is "n"
and character number 4 = "a"
and character number 3 = "k"
how to check third charcter of last word,
thanks
You can use the strings method as
char c= "string".charAt(index);
To get the characters in the string.
Edit
You can get the string as array of char as-
String str = "string";
char[] charArray = str.toCharArray();
It depends on the language you are using, but in general read the character by index number (-1 because they start at 0) using []. Or with charAt like Sanjeet said.
Java:
String name = "makan";
bool lastCharacterIsN = name[name.length - 1] == 'n';
bool fourthCharacterIsA = name[3] == 'a';
bool thirdCharacterIsK = name[2] == 'k';
Javascript:
var name = "makan";
var lastCharacterIsN = name[name.length - 1] === 'n';
var fourthCharacterIsA = name[3] === 'a';
var thirdCharacterIsK = name[2] === 'k';
You can do this very simply like this.
String _makan = "makan";
int _length = _makan.length();
System.out.println(" Index of n " +_makan.indexOf("n"));
System.out.println("Length of String : " + _length);
System.out.println("character at last : " + _makan.charAt(_length-1));
System.out.println("character number 3 : " + _makan.charAt(2));
System.out.println("character number 4: " + _makan.charAt(3));
I have this code for my calculator:
public void onClick(View v) {
try {
double price = Double.parseDouble(InputPrice.getText()
.toString());
double percent = Double.parseDouble(InputPercent.getText()
.toString());
double priceValue = price * percent / 100.0f;
double percentValue = price - priceValue;
PriceToGet.setText(String.valueOf(priceValue));
PriceToPay.setText(String.valueOf(percentValue));
PriceToGet.setText(String.format("%.02f", priceValue));
PriceToPay.setText(String.format("%.02f", percentValue));
The Input and the Output are coming without commas like this:
Input: 333333333
Output: 134555.44
Output: 17475.66
This was just an example for Output and Input.
How do I like the user see them is:
Input: 333,333,333
Output: 134,555.44
Output: 17,475.66
Thanks
Update:
I added decimal in my onclick code:
DecimalFormat formatter = new DecimalFormat("#,###,###");
I used this code but its closing the App after I press the button:
String PriceToGet = formatter.format(String.format("%.02f", priceValue));
And when I am using this method:
String PriceToGet = formatter.format("%.02f", priceValue);
Its force me to change it to:
String PriceToGet = formatter.format(priceValue);
What to do?
You need to use DecimalFormat
You will find the complete answer here
This is how you can convert one of your integers to strings.
int x = 1000000;
DecimalFormat formatter = new DecimalFormat("#,###,###");
String number_string = formatter.format(x);
System.out.println(number_string);
// Outputs 1,000,000
This JS function from Css Tricks - http://css-tricks.com/snippets/javascript/comma-values-in-numbers/
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3) {
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}