Java NumberFormatException Error - java

Hey guys this is a code where I am trying to make java read a text file.I have some float values I want the program to read but it is throwing a Number Format Exception.The text file "h.txt" is a notepad file that is encoded in ANSI.
package javaapplication1;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.Locale;
import java.lang.*;
public class JavaApplication1 {
int[][] adj=new int[50][50];
String line;
public JavaApplication1(int[][] adj) {
// TODO Auto-generated constructor stub
this.adj=adj;
}
public void fileinput2() {
try {
BufferedReader file=new BufferedReader(new FileReader("h.txt"));
try {
while((line=file.readLine())!=null){
String[] s=line.split("\t+")
for(int i=0;i<s.length;i++)
{
float x=Float.valueOf(s[i].trim());
System.out.print(x+" ");
}
System.out.println();
}
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
{
int[][] adj=new int[50][50];
JavaApplication1 m=new JavaApplication1(adj);
m.fileinput2();
}
}
}
}
The h.txt is a text file whose first line is
0 0.25 3
Java is giving me a NumberFormatException:-
java.lang.NumberFormatException: For input string: "0.25"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at javaapplication1.JavaApplication1.fileinput2(JavaApplication1.java:35)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:70)
Kindly help me out.Thanks :)

0.25
is not valid Integer value hence its failing to parse value use
appropiate datatype like. double or float for your requirement.
i.e. Float.parseFloat(variable)

Change your split line to:
String[] s = line.split(" ");
And change your for loop to:
for (String string : s) {
if (!string.isEmpty()) {
float x = Float.parseFloat(string);
System.out.print(x + " ");
}
}

Related

Parse .prn file to html

I am trying to convert a .prn file to html. But due to file format, I am not able to parse in a way I want.
I tried many approaches. some of are:
package main;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PrnToHtml {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(".\\Workbook2.prn"));
FileWriter writer = new FileWriter("output_prn.html")) {
writer.write("<html><body><h3>PRN to HTML</h3><table border>\n");
String currentLine;
while ((currentLine = reader.readLine()) != null) {
writer.write("<tr>");
for(String field: currentLine.split("\\s{2,}")) // "\\s{2,}"
writer.write("<td>" + field + "</td>");
writer.write("</tr>\n");
}
writer.write("</table></body></html>\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of this will be html page looks like this:
prn file\data looks like this:
Other this I tried to read this is:
package main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PRNToHtml {
private static final String DILIM_PRN = " ";
private static final Pattern PRN_SPLITTER = Pattern.compile(DILIM_PRN);
public static void main(String[] args) throws URISyntaxException, IOException {
try (#SuppressWarnings("resource")
Stream<String> lines = new BufferedReader(new FileReader(".\\Workbook2.prn")).lines()) {
List<String[]> inputValuesInLines = lines.map(l -> PRN_SPLITTER.split(l)).collect(Collectors.toList());
for (String[] strings : inputValuesInLines) {
for (String s : strings) {
System.out.print(s.replaceAll("\\s+", "") + " ");
}
System.out.println();
}
}
}
}
output of this is the exactly same looking in prn data file. But when I am trying to embed in html, it is looking weird like this:
Help will be appreciated.
Thank you :)

Java split not working consistently

I have the following code below the output.
My issue is that the split function is not working correctly/consistently.
I want to split on each "$".
Reason being is that I want to parse the GGA and RMC data.
Before anyone spends to much time, is this the right way to do this?
My steps:
Read GPS data
Store sentence type (GGA, RMC) in variables that only store the most recent data
Parse those variables and pass to program and then database?
[
$GPGSV,,,,,,,,,*43
$GPRMC,055106.000,A,,N,,W,0.00,61.40,,,,A*4D]
[
$GPVTG,,,,,,T,,M,,,,K,A*3E
$GPGGA,055107.000,,N,,W,,,,M,-33.3,M,,0000*6T
$GPGLL,,N,,W,055107.000,A,A*44]
[
$GPRMC,055107.000,A,,N,,W,0.00,,,,,A*4F
$GPVTG,,,,,,T,,M,0.00,,0.0,,A*3E]
[
$GPGGA,055108.000,3,N,,W,1,09,0.9,,,M,,0000*62]
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener; import jssc.SerialPortException;
import java.util.Arrays;
//import java.awt.List;
//import java.util.Base64;
//import java.io.BufferedReader;
//import java.io.ByteArrayInputStream;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.lang.*;
//import static java.util.Arrays.asList;
//import java.util.List;
//import java.util.stream.Collectors;
//import org.apache.commons.lang3.StringUtils;
public class test {
static List<String> datat = new ArrayList<String>();
static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("COM1");
try {
serialPort.openPort();//Open ports
serialPort.setParams(4800, 8, 1, 0);//Set params
int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
serialPort.setEventsMask(mask);//Set mask
serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
/*
* In this class must implement the method serialEvent, through it we learn about
* events that happened to our port. But we will not report on all events but only
* those that we put in the mask. In this case the arrival of the data and change the
* status lines CTS and DSR
*/
static class SerialPortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
// if(event.isRXCHAR()){//If data is available
// if(event.getEventValue() < 577){//Check bytes count in the input buffer
//Read data, if 10 bytes available
try {
String getdata = serialPort.readString(event.getEventValue()+1);
String[] parts= getdata.split("$");
if(!datat.isEmpty()){
datat.set(datat.size() - 1, datat.get(datat.size() - 1) + parts[0]);
}
//data.set(data.size() - 1, data.get(data.size() - 1) + parts[0]);
for (int i=1; i<parts.length; i++) {
datat.add(parts[i]);
// System.out.println(Arrays.toString(parts));
}
String[] data2 = datat.toArray(new String[0]);
for(String s : data2)
{
data2 = s.split("$");
List<String> data3 = Arrays.asList(data2);
// int testing = data3.size();
System.out.println(data3);
}
}
catch (SerialPortException ex) {
}
}
}
}
The split function takes a regular expression, not a string, You are using a special character in a regular expresion ($) then you need to scape that character
String s= "$........$...$....";
String[] data2= s.split("\\$");

Calling method from different class (different than other questions)

So I'm relatively new to java and I'm trying to use a method from a different class inside my main.
The method I'm using to pull doesn't contain any data initially but pulls the data from a text doc.
I've included the code that calls the other class method that loads the data from the file. It sill doesn`t work, so where is my mistake?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalRobert {
public static void main(String[] args) {
//output of animalList class here
}
Here is the class I'm trying to pull from:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class animalList {
public void animalDetails () {
int i = 0;
String animalInfo = "C:/Users/Robert/Documents/animals.txt";
String animalHabitat = "‪C:/Users/Robert/Documents/habitats.txt";
try {
File animalFile = new File(animalInfo);
FileReader animalReader = new FileReader(animalFile);
BufferedReader animalList = new BufferedReader (animalReader);
StringBuilder animalDetailList = new StringBuilder();
String line;
while ((line = animalList.readLine()) != null) {
for (i = 0; i <4 ; i++) {
System.out.println(line);
animalList.readLine();
}
}
animalReader.close();
System.out.println(animalDetailList.toString());
}
catch (IOException e) {
}
}
}
So I want to have the output of the animalList class in my main, but I don't know how to bring it over because I'm not necessarily bring over variable, but a process. The full thing should bring the first line and four past it (so a total of the first five lines in the doc). Hopefully that makes things easier to see my problem.
This is a mcve of AnimalList :
public class AnimalList {//use java naming convention
public void animalDetails () {
//mcve should be runnable. The problem you ask help with is not
//reading from file, so remove file reading functionality to make it mcve
StringBuilder animalDetailList = new StringBuilder();
animalDetailList.append("Family: Cats").append("\n")
.append("Type : Panther").append("\n")
.append("Weight: 250kg").append("\n")
.append("Color : Pink");
System.out.println(animalDetailList.toString());
}
}
Invoke its method from another class:
public class FinalRobert {
public static void main(String[] args) {
//to invoke animalDetails() method use
AnimalList aList = new AnimalList();
aList.animalDetails();
//if you do not need the aList refrence you could use
//new AnimalList().animalDetails();
}
}
Output
Family: Cats Type : Panther Weight: 250kg Color :
Pink
I hope this might help you.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalRobert {
public static void main(String[] args) {
animalList list = new animalList();
list.animalDetails();
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class animalList {
public String animalDetails () {
int i = 0;
String output="";
String animalInfo = "C:/Users/Robert/Documents/animals.txt";
String animalHabitat = "‪C:/Users/Robert/Documents/habitats.txt";
try {
File animalFile = new File(animalInfo);
FileReader animalReader = new FileReader(animalFile);
BufferedReader animalList = new BufferedReader (animalReader);
String line;
while ((line = animalList.readLine()) != null & i<4) {
System.out.println(line);
output = output + "\n"+ line;
i++;
}
animalReader.close();
System.out.println(output);
}
catch (IOException e) {
}
return output;
}
}

Searching a CSV file Java

Im trying to a specific String of number in a csv file and I keep getting an a FileNotFound exception even though the files exists. I cant seem to fix the problem
Sample Csv file
12141895, LM051
12148963, Lm402
12418954, Lm876
User Input : 12141895
Desired Result : True
import javax.swing.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.List;
public class tester
{
public static void main (String [] args ) throws IOException
{
boolean cool = checkValidID();
System.out.println(cool);
}
public static boolean checkValidID() throws IOException
{
boolean results = false;
Scanner scan = new Scanner(new File("C:\\Users\\Packard Bell\\Desktop\\ProjectOOD\\IDandCourse.csv"));
String s;
int indexfound=-1;
String words[] = new String[500];
String word = JOptionPane.showInputDialog("Enter your student ID");
while (scan.hasNextLine())
{
s = scan.nextLine();
if(s.indexOf(word)>-1)
indexfound++;
}
if (indexfound>-1)
{
results = true;
}
else
{
results = true;
}
return results;
}
}
use:
import java.io.File;
import java.io.FileNotFoundException;
Also, in your function declaration try using
public static boolean checkValidID() throws FileNotFoundException
and likewise with the main function.
If the file is present and named correctly, this should handle it.

adding value on treeset

ı read text. my text is like that
AYSE;SERDAR-9.8;EMRE-5.2;AYTAC-3.3
FATMA;OYTUN-8.8;ORKUN-7.5;ONUR-5.4;UMUT-4.4;BERK-3.3;CAN-3.2
DERYA;VELI-7.7;ALI-6.5;SUAT-6.0;YAVUZ-5.0;OYTUN-4.2;ORKUN-3.1
DILARA;DOGUS-8.8;VELI-7.4;ALI-6.5;SUAT-5.5;YAVUZ-3.1
BEGUM;SUAT-6.6;YAVUZ-5.1;OYTUN-4.3;ORKUN-4.0
BERIL;CANER-8.7;DOGUS-7.5;VELI-6.2;ALI-6.1;SUAT-5.8;YAVUZ-4.8;OYTUN-4.0
FUNDA;ORKUN-9.7;ONUR-8.3;UMUT-7.2;BERK-6.5;CAN-5.5
ISIL;AYTAC-8.3;CANER-7.4;DOGUS-6.5;VELI-5.5;ALI-5.4;SUAT-4.4;YAVUZ-4.0;OYTUN-3.9;ORKUN-3.5;ONUR-3.4;UMUT-3.2;BERK-3.1;CAN-3.0
ELIF;EMRE-7.4;AYTAC-6.1
ı cant add "u.eleman" and "u.uyum" values to "treeset tSU". it gives memory address when ı do syso ı cant see them in the tSU TREESET. I want to add all of them to treeset. How can ı do that.. please help
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeSet;
public class Rapor {
static class Uyum implements Comparable<Uyum> {
String eleman;
Double uyum;
public int compareTo(Uyum u) {
if (uyum < u.uyum)
return -1;
if (uyum > u.uyum)
return 1;
return 0;
}
}
public static void main(String[] args) {
FileInputStream fIS;
try {
fIS = new FileInputStream("C:\\deneme\\rapor.txt");
Reader r;
r = new InputStreamReader(fIS, "UTF-8");
BufferedReader bR = new BufferedReader(r);
String satır;
String[] point, p2;
while ((satır = bR.readLine()) != null) {
point = satır.split(";");
String kelime = point[0];
HashMap<String, TreeSet<Uyum>> uyumlar = new HashMap<String, TreeSet<Uyum>>();
TreeSet<Uyum> tSU = new TreeSet<Uyum>() ;
Uyum u ;
for (int i = 1; i < point.length; i++) {
p2=point[i].split("\\-");
u = new Uyum();
u.eleman = p2[0];//EMRE,AYTAC,..
u.uyum = Double.parseDouble(p2
[1]);//7.8,9.5
tSU.add(u);
}
uyumlar.put(kelime, tSU);
System.out.println(uyumlar);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// main end
}// class end
it gives memory address when ı do syso ı cant see them in the tSU TREESET.
No, it does not print the memory address. It prints the class name, an # and the hash code for the object in hexadecimal - that's what Object.toString() does by default.
If you want your Uyum objects to be printed differently, then override the toString() method in your class Uyum.

Categories