JAVA: Double.parseDouble + Double.parseDouble = String - java

I have this problem in my program:
When I do this:
double a = Double.parseDouble(zero);
double b = Double.parseDouble(data);
double c = a+b;
String d = Double.toString(c);
It returns me a String. For example, I have 0.0 in a and 4.0 in b and it returns 0.04.0.
Can someone explain to me why and what I should do instead?
EDITED: Here is my code:
private void WriteMedia(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("writemedia.txt", Context.MODE_PRIVATE));
String zero;
if(ReadMedia().isEmpty() == true)
{
zero = "0.0";
outputStreamWriter.write(zero);
}
else {zero = ReadMedia();}
double a = Double.parseDouble(zero);
double b = Double.parseDouble(data);
double c = a+b;
String d = Double.toString(c);
outputStreamWriter.write(d);
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String ReadMedia() {
String ret = "";
try {
InputStream inputStream = openFileInput("writemedia.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("estrela.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
WriteMedia(data);
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("estrela.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
WriteMedia(ret);
return ret;
}
The data is a ratingbar, zero is "0" when I start the app and it should save the rating bar to "increment"(don't know the english word). I thought it would be easy but since is like a bug just for me i'll put the tag android studio.
Here is where I call the method:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rating = ratingbar.getRating();
writeToFile(Double.toString(rating));
writeMyArray(Double.parseDouble(readFromFile()));
writeMyArray(ratingbar.getRating());
button.setText(getText(R.string.obrigado) + "!" + readFromFile() + " " + media(arraydays) + " " + ReadMedia());
}
});
It returns me the "0.0" and the ratingbar together, for example: "0.05.0"

Your problem is not related to types (other than you guessed) and it is not in the code you originally posted.
Instead, you are simply writing 2 numbers to your output stream. The following code writes 0.0:
if(ReadMedia().isEmpty() == true)
{
zero = "0.0";
outputStreamWriter.write(zero);
}
And, in addition to that, the following code writes the result you actually want:
double a = Double.parseDouble(zero);
double b = Double.parseDouble(data);
double c = a+b;
String d = Double.toString(c);
outputStreamWriter.write(d);

Related

Unable to start activity, ArrayIndexOutOfBounds in a line reader

I keep getting an ArrayIndexOutOfBoundsException, but I am not sure what part of code exactly causes this error. Any help will be appreciated a lot. The code is
while ((line = reader.readLine()) != null) {
String[] wordOnLine = line.split(",");
geo.put(wordOnLine[0] , new GeoLocation(wordOnLine[0], Double.parseDouble(wordOnLine[1]), Double.parseDouble(wordOnLine[2]),TimeZone.getTimeZone(wordOnLine[3])));
}
The error is
Unable to start activity
ComponentInfo{swindroid.suntime/swindroid.suntime.ui.Main}:
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
public List getListOfLocations() {
// String fileName = "au_locations.txt";
// BufferedReader reader = null;
// StringBuilder builder = new StringBuilder();
InputStream input = getResources().openRawResource(R.raw.au_locations);
BufferedReader reader = new BufferedReader( new InputStreamReader((input)));
String line;
StringBuilder builder = new StringBuilder();
File file = new File(getFilesDir(), "au_locations.txt");
try {
// reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
// String line;
while ((line = reader.readLine()) != null) {
// builder.append(line).append("\n");
String[] wordOnLine = line.split(",");
geo.put(wordOnLine[0] , new GeoLocation(wordOnLine[0], Double.parseDouble(wordOnLine[1]), Double.parseDouble(wordOnLine[2]),TimeZone.getTimeZone(wordOnLine[3])));
//locations.add(line);
}
if(file.exists()){
FileInputStream inputFile = openFileInput("au_locations.txt");
input = inputFile;
reader = new BufferedReader((new InputStreamReader((input))));
while ((line = reader.readLine()) != null) {
// builder.append(line).append("\n");
String[] wordOnLine = line.split(",");
geo.put(wordOnLine[0] , new GeoLocation(wordOnLine[0], Double.parseDouble(wordOnLine[1]), Double.parseDouble(wordOnLine[2]),TimeZone.getTimeZone(wordOnLine[3])));
//locations.add(line);
}
}
// return locations;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public void AddLocationHandler() throws IOException
{
String name = ((EditText) findViewById(R.id.nameText)).getText().toString();
String longi = ((EditText) findViewById(R.id.longText)).getText().toString();
String lati = ((EditText) findViewById(R.id.latText)).getText().toString();
String timezone = ((EditText) findViewById(R.id.timeText)).getText().toString();
Double locationLong;
Double loctaionLat;
TimeZone locationTimeZone;
try {
loctaionLat = parseDouble(lati);
}catch (NumberFormatException e)
{
Toast toast = Toast.makeText(getApplicationContext(), "not a valid latitude ", Toast.LENGTH_SHORT);
toast.show();
return;
}
try {
locationLong = parseDouble(longi);
}catch (NumberFormatException e)
{
Toast toast = Toast.makeText(getApplicationContext(), "not a valid longitude ", Toast.LENGTH_SHORT);
toast.show();
return;
}
if(timezone.matches("(\\+|\\-)[0-1][0-9]\\:[034][05]")){
locationTimeZone = TimeZone.getTimeZone("GMT" + timezone);
}
else
{
Toast toast = Toast.makeText(getApplicationContext(), "not a valid Time Zone ", Toast.LENGTH_SHORT);
toast.show();
return;
}
File file = new File("au_location.txt");
if(!file.exists()){
file = new File(getFilesDir(), "au_location.txt");
}
FileOutputStream fos = openFileOutput("au_locations.txt", Context.MODE_APPEND);
OutputStreamWriter f = new OutputStreamWriter(fos);
f.write(name + "," +loctaionLat + "," + locationLong + "," + "GMT" + timezone + "\n");
//fos.write(s.getBytes());
//fos.close();
Toast.makeText(getBaseContext(),"Data Saved", Toast.LENGTH_LONG).show();
f.flush();
f.close();
Toast.makeText(getBaseContext(),"New Location Added", Toast.LENGTH_LONG).show();
}

How to de- serialize the DoccatModel object in java?

I am trying to serialize a DoccatModel Object in Java (I am using OpenNLP algorithm).
It's able to serialize the object properly and I am writing that to an external file. But, I'm not able to deserialise the object back.
I am trying to use ObjectInputStream to read that file back. It's throwing an error:
"java.io.StreamCorruptedException: invalid stream header: 504B0304"
I just want to know how to de serialize the DoccatModel object back so that I can use it further.
The code is as follows. [Apologies for bad code since its still in development stage]
private static void runDocCat(String textField, String updateField, String tgtField)
{
String dbName;
String tableName;
DoccatModel model = null;
JSONArray allDesc = null;
DataConfig BSC = null;
try
{
BSC = new DataConfig();
}
catch (Exception e1)
{
e1.printStackTrace();
}
try
{
dbName = BSC.getdbName();
tableName = BSC.tablename;
String dataQuery = "SELECT ID, VOC, " + tgtField + " from " + dbName + "." + tableName;
allDesc = BSC.getJSONArray(dataQuery);
File file = new File("voc.train");
BufferedWriter output = new BufferedWriter(new FileWriter(file));
for (int i = 0; i < allDesc.length(); i++)
{
String tgt = allDesc.getJSONObject(i).getString(tgtField);
if (tgt.length() < 3)
tgt = "Unknown";
tgt = tgt.replaceAll(" ", "");
String desc = allDesc.getJSONObject(i).getString(textField);
desc = desc.replaceAll("\\r", " ").replaceAll("\\n", ".");
if (!desc.trim().equalsIgnoreCase("nothing"))
{
DocumentSample currDoc = new DocumentSample(tgt, desc);
output.write(currDoc.toString());
output.newLine();
}
}
output.close();
System.out.println("Training Data Generated!");
ObjectStream<String> lineStream = new PlainTextByLineStream(new FileReader(file));
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
model = DocumentCategorizerME.train("en", sampleStream);
System.out.println("Model Data \n\n" + model);
// Write to a file
OutputStream modelOut = null;
try
{
String modelfile = "C:\\VOC_Classification\\model.ser";
modelOut = new BufferedOutputStream(new FileOutputStream(modelfile));
model.serialize(modelOut);
System.out.println("Model Data \n\n" + model);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (modelOut != null)
try
{
modelOut.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
// try
// {
// FileOutputStream fileOut = new FileOutputStream("modelfile.ser");
// ObjectOutputStream out = new ObjectOutputStream(fileOut);
// out.writeObject(model);
// out.close();
// fileOut.close();
// System.out.printf("Serialized data is saved in modelfile.ser");
// } catch (IOException i)
// {
// i.printStackTrace();
// }
DoccatModel model_SER = null;
try
{
FileInputStream fileIn = new FileInputStream("C:\\VOC_Classification\\model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
model_SER = (DoccatModel) in.readObject();
in.close();
fileIn.close();
} catch (IOException e)
{
e.printStackTrace();
}
System.out.println("\nTraining Done!\n");
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
System.out.println(" ---------- Starting categorising process ----------");
System.out.println("\nProcess Running, Please wait...\n");
for (int i = 0; i < allDesc.length(); i++)
{
dataQuery = "SELECT ID, VOC," + tgtField + " from " + dbName + "." + tableName;
allDesc = BSC.getJSONArray(dataQuery);
String ID = allDesc.getJSONObject(i).getString("ID");
String desc = allDesc.getJSONObject(i).getString(textField);
String newdesc = desc.replaceAll("\\n", ".").replaceAll("\\r", " ");
if (!newdesc.trim().equalsIgnoreCase("nothing"))
{
double[] outcomes = myCategorizer.categorize(newdesc);
String category = myCategorizer.getBestCategory(outcomes);
if (!category.equalsIgnoreCase("Unknown"))
{
String updQuery = "UPDATE " + dbName + "." + tableName + " set " + updateField + " = " + "'"
+ category + "'" + " WHERE ID = " + ID;
BSC.executeUpdate(updQuery);
}
}
}
System.out.println(" ---------- Process Completed Successfully ----------");
System.out.println("\nCheck your table \"" + tableName + "\" for results");
System.out.print("\n\nPress 1 to finish : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int ch = Integer.parseInt(br.readLine());
} catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
BSC.connectionClose();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The OpenNLP documentation is unclear, but there is a simple way of doing this.
private DoccatModel deSerializeModel(String modelPath) throws
IOException {
FileInputStream fileInputStream = new FileInputStream(modelPath);
DoccatModel model = new DoccatModel(fileInputStream);
return model;
}

File reading from controller

I have 2 almost identical methods. But 1 can see my file , another not.It skips the method body with line = null. Dont understand why.
This doesnt work
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("file") MultipartFile file, Model model) {
if (!file.isEmpty()) {
try {
String path = "d:/" + file.getOriginalFilename();
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(path)));
stream.write(bytes);
model.addAttribute("list", addRecordsToBD(path));
stream.close();
} catch (Exception e) {
log.error("Upload failed", e);
}
}
return "show";
}
private List addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
repository.saveAndFlush(new User(users[0], users[1], users[2],
users[3], users[4]));
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
return repository.findAll();
}
But this work great
public void addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
System.out.println("User [Name = " + users[0] +
", surname = " + users[1] +
" login = " + users[2] +
" mail = " + users[3] +
" phone = " + users[4] +
"]");
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
}
}
Can some one explain me, what's the problem and why this happened ?

New Line Command ("\n") Doesn't Working While Reading Files (Android) java

String mystring="Hello"+"\n"+ "World" ;
writeToFile(mystring);
String newstring = readFromFile();
mytextview.setText(newstring);
my text view just shows "HelloWorld" without newline
I Couldn't understand why It doesn't recognizes "\n"
These are my writetofile and readfromfile functions;
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("myfilename", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
// Log.e(TAG, "File write failed: " + e.toString());
}
}
//////////////////////////////////////////////////
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("myfilename");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
//Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
// Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
what I am trying to do is saving a string to phone's internal storage and read back the same string .
you are using the BufferedReader, check the documentation for readLine()
it states:
Returns the next line of text available from this reader. A line is represented by zero or more characters followed by '\n', '\r', "\r\n" or the end of the reader. The string does not include the newline sequence.
you could manually add it back in your while loop, or use another readXYZ method.
I have found the solution as suggested by Su-Au Hwang by this way
addded manually \n by replacing ordinary \n
String[] strLines = new String[lines.size()];
for (int i = 0; i < lines.size(); i++) {
lines.set(i, lines.get(i).replace("\\n","\n"));
strLines[i] = lines.get(i);
}
return strLines;

How to calculate sum of numbers from a file?

I want to show the sum of all the numbers added from a file in TextView, currently it just reads/shows the last number from the file.
This is my current code for writing to a file:
total.setText(total.getText());
try {
FileOutputStream fos = openFileOutput("TotalSavings", Context.MODE_PRIVATE);
fos.write(total.getText().toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
This is my current code for reading from a file:
public void savingstotalbutton(View view) {
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("TotalSavings")));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
savingstotaltext.setText(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
Can anyone tell me how to do it?
Assuming the only thing on the line is an integer, can't you do something like this?
public void savingstotalbutton(View view) {
int total = 0;
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("TotalSavings")));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
//stringBuffer.append(inputString + "\n");
total = total + Integer.parseInt(inputString);
}
//savingstotaltext.setText(stringBuffer.toString());
savingstotaltext.setText(String.ValueOf(total));
} catch (IOException e) {
e.printStackTrace();
}
}
Edit: Extended answer per questions in comments
Just change int total to double total and Integer.parseInt() to Double.parseDouble() if you are using decimals. Also, if there are more characters on the line than digits/decimals, try using the following to only strip out and use the numbers as well as ensure there is content on the line:
if (inputString.length() > 0) {
String line = inputString.replaceAll("[^0-9.]", "");
total = total + Double.parseDouble(line);
}

Categories