this method runs an exception and i didn't find why.
private void loadTrace () {
BufferedReader reader = new BufferedReader(
new StringReader(logTextArea.getText()));
String str;
try {
while(reader != null)
{
str =reader.readLine();
String [] splitted = str.split("\\|");
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();
String Chemin;
String Type = "action" ;
String Description;
if (d!=null) {
Description=d;
}
else Description ="Afficher onglet";
if (c!= null) {
Chemin= b+"."+c;
}
else Chemin =b;
String trace =Type+" "+Description +" "+Chemin ;
ArrayList<String> p = new ArrayList<String>();
p.add(trace);
System.out.println(p);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
Without knowing the exception I can guess one of the potential issue is in these lines:-
String [] splitted = str.split("\\|");
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();
You are accessing splitted without checking if it is null or size so you may run into ArrayIndexOutOfBound exception if splitted length is less than 3. So modify the code this way-
String [] splitted = str.split("\\|");
if(splitted!=null && splitted.length==3){
String b = splitted[0].trim();
String c = splitted[1].trim();
String d = splitted[2].trim();
}
The NullPointerException you get now that you've fixed the ArrayIndexOutOfBound is because of the test you use in your while loop:
while(reader != null)
{
...
}
reader will always be non-null so this loop will never end. You need to test if
reader.readLine()
returns null (indicating EOF).
I guess you get an ArrayIndexOutOfBoundException, right?
(You need to tell us, what Exception you receive)
The problem could be in the following lines. You should check the size of the array and not just "hope" that it has three parts.
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();
Related
I am trying to get the location data from this string using String.split("[,\\:]");
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
String[] str = location.split("[,\\:]");
How can i get the data like this.
str[0] = 27.980194
str[1] = 46.090199
str[2] = 0.48
str[3] = 1
str[4] = 6
Thank you for any help!
If you just want to keep the numbers (including dot separator), you can use:
String[] str = location.split("[^\\d\\.]+");
You will need to ignore the first element in the array which is an empty string.
That will only work if the data names don't contain numbers or dots.
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
Matcher m = Pattern.compile( "\\d+\\.*\\d*" ).matcher(location);
List<String> allMatches = new ArrayList<>();
while (m.find( )) {
allMatches.add(m.group());
}
System.out.println(allMatches);
Quick and Dirty:
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
List<String> strList = (List) Arrays.asList( location.split("[,\\:]"));
String[] str = new String[5];
int count=0;
for(String s : strList){
try {
Double d =Double.parseDouble(s);
str[count] = d.toString();
System.out.println("In String Array:"+str[count]);
count++;
} catch (NumberFormatException e) {
System.out.println("s:"+s);
}
}
When I try to compile my code I get the message
Main.java:31: error: not a statement
String bed = f.split(" ")
and also
error: ';' expected
String bed = f.split(" ");
I don't understand what's going on. I need to assign part of a file to a string.
Here's the code :
import java.util.Scanner;
import java.io.*;
public class Main{
public static void main(String[] args){
if ( args[0] == null){
System.out.println("File not Found");
return;
}
try {
File driver = new File (args[0]);
Scanner j = new Scanner( driver );
int i = 0;
while( j.hasNextLine()) {
String f = j.nextLine();
if (f.isEmpty() || f.startsWith("/")){ //If the String f is empty or has / it will continue reading the nextline after the / or space
continue;
if (f.startsWith("d")) {
String d = f.split(" ");
}
if (f.startsWith("b")) {
String b = f.split(" ");
}
if (f.startsWith("bed"))
String bed = f.split(" ");
}
System.out.println(f);
}
}
catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
catch (Exception ex) {
System.out.println(ex.getMessage);
}
}
}
.split() method returns an array so you should store it in an array, not in a string. Your code should be string b[]=f.split(" ") rather than storing it in string b
The split method returns splits the string based on the regex and returns an String array.
What you have here is String d = f.split(" ");, here you are trying to assign a string array to a string, and that is wrong.
It should instead say String[] d = f.split(" ");
I had this error.
I found a solution like below.
Error code
String a = "I goto the school";
String [] b = a.split("\\\s"); // error not a statement
Run code
try
{
String a = "I goto the school";
String [] b = a.split("\\\s");
}
catch(exception e)
{
}
I've been working on this for a few days now and I just can't make any headway. I've tried using Scanner and BufferedReader and had no luck.
Basically, I have a working method (shortenWord) that takes a String and shortens it according to a text file formatted like this:
hello,lo
any,ne
anyone,ne1
thanks,thx
It also accounts for punctuation so 'hello?' becomes 'lo?' etc.
I need to be able to read in a String and translate each word individually, so "hello? any anyone thanks!" will become "lo? ne ne1 thx!", basically using the method I already have on each word in the String. The code I have will translate the first word but then does nothing to the rest. I think it's something to do with how my BufferedReader is working.
import java.io.*;
public class Shortener {
private FileReader in ;
/*
* Default constructor that will load a default abbreviations text file.
*/
public Shortener() {
try {
in = new FileReader( "abbreviations.txt" );
}
catch ( Exception e ) {
System.out.println( e );
}
}
public String shortenWord( String inWord ) {
String punc = new String(",?.!;") ;
char finalchar = inWord.charAt(inWord.length()-1) ;
String outWord = new String() ;
BufferedReader abrv = new BufferedReader(in) ;
// ends in punctuation
if (punc.indexOf(finalchar) != -1 ) {
String sub = inWord.substring(0, inWord.length()-1) ;
outWord = sub + finalchar ;
try {
String line;
while ( (line = abrv.readLine()) != null ) {
String[] lineArray = line.split(",") ;
if ( line.contains(sub) ) {
outWord = lineArray[1] + finalchar ;
}
}
}
catch (IOException e) {
System.out.println(e) ;
}
}
// no punctuation
else {
outWord = inWord ;
try {
String line;
while( (line = abrv.readLine()) != null) {
String[] lineArray = line.split(",") ;
if ( line.contains(inWord) ) {
outWord = lineArray[1] ;
}
}
}
catch (IOException ioe) {
System.out.println(ioe) ;
}
}
return outWord;
}
public void shortenMessage( String inMessage ) {
String[] messageArray = inMessage.split("\\s+") ;
for (String word : messageArray) {
System.out.println(shortenWord(word));
}
}
}
Any help, or even a nudge in the right direction would be so much appreciated.
Edit: I've tried closing the BufferedReader at the end of the shortenWord method and it just results in me getting an error on every word in the String after the first one saying that the BufferedReader is closed.
So I took at look at this. First of all, if you have the option to change the format of your textfile I would change it to something like this (or XML):
key1=value1
key2=value2
By doing this you could later use java's Properties.load(Reader). This would remove the need for any manual parsing of the file.'
If by any change you don't have the option to change the format then you'll have to parse it yourself. Something like the code below would do that, and put the results into a Map called shortningRules which could then be used later.
private void parseInput(FileReader reader) {
try (BufferedReader br = new BufferedReader(reader)) {
String line;
while ((line = br.readLine()) != null) {
String[] lineComponents = line.split(",");
this.shortningRules.put(lineComponents[0], lineComponents[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
When it comes to actually shortening a message I would probably opt for a regex approach, e.g \\bKEY\\b where key is word you want shortened. \\b is a anchor in regex and symbolizes a word boundery which means it will not match spaces or punctuation.
The whole code for doing the shortening would then become something like this:
public void shortenMessage(String message) {
for (Entry<String, String> entry : shortningRules.entrySet()) {
message = message.replaceAll("\\b" + entry.getKey() + "\\b", entry.getValue());
}
System.out.println(message); //This should probably be a return statement instead of a sysout.
}
Putting it all together will give you something this, here I've added a main for testing purposes.
I think you can have a simpler solution using a HashMap. Read all the abbreviations into the map when the Shortener object is created, and just reference it once you have a word. The word will be the key and the abbreviation the value. Like this:
public class Shortener {
private FileReader in;
//the map
private HashMap<String, String> abbreviations;
/*
* Default constructor that will load a default abbreviations text file.
*/
public Shortener() {
//initialize the map
this.abbreviations = new HashMap<>();
try {
in = new FileReader("abbreviations.txt" );
BufferedReader abrv = new BufferedReader(in) ;
String line;
while ((line = abrv.readLine()) != null) {
String [] abv = line.split(",");
//If there is not two items in the file, the file is malformed
if (abv.length != 2) {
throw new IllegalArgumentException("Malformed abbreviation file");
}
//populate the map with the word as key and abbreviation as value
abbreviations.put(abv[0], abv[1]);
}
}
catch ( Exception e ) {
System.out.println( e );
}
}
public String shortenWord( String inWord ) {
String punc = new String(",?.!;") ;
char finalchar = inWord.charAt(inWord.length()-1) ;
// ends in punctuation
if (punc.indexOf(finalchar) != -1) {
String sub = inWord.substring(0, inWord.length() - 1);
//Reference map
String abv = abbreviations.get(sub);
if (abv == null)
return inWord;
return new StringBuilder(abv).append(finalchar).toString();
}
// no punctuation
else {
//Reference map
String abv = abbreviations.get(inWord);
if (abv == null)
return inWord;
return abv;
}
}
public void shortenMessage( String inMessage ) {
String[] messageArray = inMessage.split("\\s+") ;
for (String word : messageArray) {
System.out.println(shortenWord(word));
}
}
public static void main (String [] args) {
Shortener s = new Shortener();
s.shortenMessage("hello? any anyone thanks!");
}
}
Output:
lo?
ne
ne1
thx!
Edit:
From atommans answer, you can basically remove the shortenWord method, by modifying the shortenMessage method like this:
public void shortenMessage(String inMessage) {
for (Entry<String, String> entry:this.abbreviations.entrySet())
inMessage = inMessage.replaceAll(entry.getKey(), entry.getValue());
System.out.println(inMessage);
}
java.lang.ArrayIndexOutOfBoundsException
how to remove this exception
public static void main(String[] args) throws ClassNotFoundException, SQLException {
FileUpdate obj = new FileUpdate();
obj.run();
}
public void run() throws SQLException, ClassNotFoundException {
String csvFile = "/home/IMRAN/file.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date dateobj = new Date();
String dt = df.format(dateobj);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Rforms", "root", "root12");
Statement st = con.createStatement();
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] emp = line.split(cvsSplitBy);
// if (emp[0] != null && emp[1] != null ) {
// for(int x = 0; x < emp.length; x++) {
String t = (String) emp[0].trim();
String t2 = (String) emp[1].trim();
}
}
Problem is not clear... java.lang.ArrayIndexOutOfBoundsException occours when you try to access to an object (array element) that does not exist. For example, your array is 7 elements long and you try to access element[8]
Are you sure emp[0] is not null?
You should check length of the emp array before accessing its elements.
if(emp!=null && emp.length==2){
String t = (String) emp[0].trim();
String t2 = (String) emp[1].trim();
}
This code below tells that emp should always have 2 or more elements.
else you got java.lang.ArrayIndexOutOfBoundsException.
...
String t = (String) emp[0].trim();
String t2 = (String) emp[1].trim();
...
Hi Let's assume that you have place CSV file and content correctly in that case you can place conditions check per below
String[] emp = line.split(cvsSplitBy);
if (emp.length > N) {
String t = (String) emp[0] !=null ?emp[0].trim():"";
String t2 = (String)emp[1] !=null ?emp[1].trim():"";
}
Note that you are aware of number values fetch from the line .
or you can utilize List. this will completely take you out from this issue.
List lst= Arrays.asList(emp);
Refer java docs for how to utilize List and fetch list from it.
I want to write a java method that takes a string in input and outputs another string following this rule:
input output
"123456" "12:34:56"
"23456" "02:34:56"
"3456" "00:34:56"
"456" "00:04:56"
"6" "00:00:06"
Any help would be appreciated. Thanks.
I would advice to use DateFormat as below. This will take care of all the burdens of conversion.
DateFormat formatFrom = new SimpleDateFormat("HHmmss");
DateFormat formatTo = new SimpleDateFormat("HH:mm:ss");
String origTimeString = "456";
String newDateString = null;
try {
String formattedString =
String.format("%06d", Integer.parseInt(origTimeString));
Date date = formatFrom.parse(formattedString);
newDateString = formatTo.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Updated string : " + newDateString);
Copy this method and use it.
1) If string length is more than 6, it's going to return "ERROR".
2) First fixes the String with '0'
3) Second fixes the String with ':'
4) StringBuilder is used for concat. Avoid using '+' operator for concat.
5) Method 'getDate' is static because of 'main' method is static, too.
public static String getDate(String variable){
StringBuilder aux= new StringBuilder();
StringBuilder string= new StringBuilder();
int length = variable.length();
if(length>6 || length<=0){
return "ERROR";
}else{
//first to fill blanks with 0
for(int i=0;i<6-length;i++){
aux.append("0");
}
variable = aux.append(variable).toString();
//second to put :
for(int i=0;i<6;i++){
if(i%2==0 && i!=0){
string.append(":");
}
string.append(variable.charAt(i));
}
return string.toString();
}
}
public static void main(String[] args) {
System.out.print(getDate("464"));
}