I am getting the error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 28
at assignment.assgn1.main(assgn1.java:44)
I would be very grateful if someone could point out the error
package assignment;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
public class assgn1 {
public static void main(String[] args) throws IOException
{
try{
CSVReader csvReader = new CSVReader(new FileReader("E:/AviationData.txt"),'\t','\n');
PrintWriter NYreports = new PrintWriter("E:/NYReports.txt");
String [] nextLine;
int x;
int sum=0;
double totalFatal=0;
Integer largest = 0;
Integer smallest = 0;
String [] token = null;
//read first line, but it will not be counted with the rest of the records
nextLine = csvReader.readNext();
//create a map for unique Broad Phase in flight fields
Map<String, Integer> broadPhase = new HashMap <String, Integer>();
//create an array list that will take in integer values of Fatal Injuries
ArrayList <Integer> intList = new ArrayList<Integer>();
while ((nextLine = csvReader.readNext()) !=null){
sum++;
String field = nextLine[0];
//using regex values!
token = field.split("\\s\\|\\s");
//for (String s: token){
//System.out.println(s);
//}
if(token[28].equals(" ")){
broadPhase.put(token[28],0);
}
if(!token[28].equals(" ") && !token[28].equals("")){
broadPhase.put(token[28], 1);
}
//search for Fatal Injury values
if(!token[23].isEmpty()){
x=Integer.parseInt(token[23]);
//add to ArrayList
intList.add(x);
totalFatal = x + totalFatal;
}
if(token[4].contains(", NY") && token[5].contains("/2015")){
NYreports.println(nextLine[0]);
}
}
for(int i =0; i<intList.size()-1; i++){
if (intList.get(i) > largest);
largest = intList.get(i);
if (intList.get(i)< smallest)
smallest = intList.get(i);
}
System.out.println("There are " + sum + " records");
System.out.println("There are " + (broadPhase.size())+" unique values in Broad Phase of Flight");
totalFatal = (totalFatal/sum);
System.out.println(largest + " is the largest number of Fatal injuries");
System.out.println("The average of Fatal injuries is " + totalFatal);
NYreports.close();
csvReader.close();
}
catch (FileNotFoundException ex){
System.out.println("File not Found");
}
}
}
the error is on the line where if(token[28].equals(" ")){. is written.
what can i change to avoid it. also if any change in method used by me can be done.
ArrayIndexOutOfBoundsException generally occurs when you try to access
an index which is not present on the array
, ie.. index > length - 1 (since arrays in java are 0 based).
To avoid this error make sure that you use only valid indexes , which are
0 =< idx < length.
In the current context you may want to add an additional check to ensure that array contains that index along with the normal if conditions.
something like
if(token.length > 28 && token[28].equals(" ")){
broadPhase.put(token[28],0);
}
The error is because token[28] doesn't exist. In other words, your split() call is returning an array that isn't as long as you think it is. I would check your input to see whether or not your input is correct.
On a side note, your method seems to be very... rough and hard coded. Assuming that you know the exact order the tokens are stored in, a better way to do this that would avoid the ArrayIndexOutOfBounds Exception is to loop through your tokens array using a either a for each loop or a normal for loop.
You can then parse each section while you're looping through it.
For example:
for (int i = 0; i < tokens.length; i++) {
// based on the i value, parse a different way
}
Related
I am having trouble with writing a successful code that identifies the loops (for loops, while loops, nested for loops) in an input text file(this input was taken using BufferedReader), and methods, where the output should look like this:
(for loop from line x to line x)
(while loop from line x to line x)
(method xxx from line x to line x)
I started by creating a folder that contains a text file that has a random code written in it( in my case it was a bubble sort) the code had comments, so I deleted all comments using replaceAll regex, the output with no comments is written to another .txt file, then, I used BufferedReader to read the new txt file and stored it in an ArrayList, this is where I got stuck, I tried several if statements in order to find for loops as a start.
My question is how can I get the desired output I wrote above?
package assignment1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
public class tryq3 {
public static void main(String a[]) throws Exception {
String fileName = "C://myFolder//output.txt";
Question1 DDD = new Question1();
String source = DDD.readFile(fileName);
String sourceNoBrackets = source.replaceAll("\\(.*\\)", "");
File file1 = new File("C:\\myFolder\\cleanOutput1.txt");
FileWriter fw = new FileWriter(file1);
PrintWriter pw = new PrintWriter(fw);
pw.println(sourceNoBrackets);
pw.close();
String line;
int counter = 0;
ArrayList<String> mylist = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader("C:\\myFolder\\cleanOutput1.txt"));
while((line = br.readLine())!=null) {
mylist.add(line);
}
for(int i=0;i<mylist.size();i++) {
int count=0;
if(mylist.get(i).contains("for")) {
System.out.println("for loop from " + i);
}
}
}
}
I would recommend that once the word for is found, don't just list the lines but locate where the open bracket { starts and where } is (ends). You can do the same for while loops and a method. You would need to catch cases where there would be a nested for loop; if for then { was found then another for restart the process and first state the for loop inside then the outer. I hope that helps!
for(int i=0;i<mylist.size();i++) {
int count=0;
if(mylist.get(i).contains("for") && mylist.get(i).contains("{")) {
for(int j=i;j<mylist.size();j++) {
if(mylist.get(j).contains("}"){
System.out.println("for loop from " + i);
i = j; // begin from where j left off
}
if(mylist.get(j).contains("for") && mylist.get(j).contains("{"){ // nested loop
for(int k=j;k<mylist.size();k++) {
if(mylist.get(k).contains("}"){
System.out.println("for loop from " + i);
j = k; // begin from where k left off
}
}
}
}
}
}
So the task was to read a file with the following names:
Alice
Bob
James
Richard
Bob
Alice
Alice
Alice
James
Richard
Bob
Richard
Bob
Stephan
Michael
Henry
And print out each name with its value of occurrence e.g "Alice - <4>".
I got it working, basically. The only problem I have is that the last name (Stephan - <1>) is missing in my output and I can't get it to work properly.. It's probably because I used [i-1] but as I said, I'm not getting the right solution here.
Well, here's my code..
package Assignment4;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Arrays;
public class ReportUniqueNames {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println (" This programm counts words, characters and lines!\n");
System.out.println ("Please enter the name of the .txt file:");
BufferedReader input = new BufferedReader(new InputStreamReader (System.in));
BufferedReader read = null;
String file = "";
String text = "";
String line = "";
boolean unique = true;
int nameCounter = 1;
try {
file = input.readLine();
read = new BufferedReader (new FileReader(file));
while ((line = read.readLine()) != null) {
text += line.trim() + " ";
}
} catch (FileNotFoundException e) {
System.out.println("File was not found.");
} catch (IOException e) {
System.out.println("An error has occured.");
}
String textarray[] = text.split(" ");
Arrays.sort(textarray);
for (int i=0; i < textarray.length; i++) {
if (i > 0 && textarray[i].equals(textarray[i-1])) {
nameCounter++;
unique = false;
}
if (i > 0 && !textarray[i].equals(textarray[i-1]) && !unique) {
System.out.println("<"+textarray[i-1]+"> - <"+nameCounter+">");
nameCounter = 1;
unique = true;
} else if (i > 0 && !textarray[i].equals(textarray[i-1]) && unique) {
//nameCounter = 1;
System.out.println("<"+textarray[i-1]+"> - <"+nameCounter+">");
}
}
}
}
So that's it.. Hopefully one of you could help me out.
EDIT: Wow, so many different approaches. First of all thanks for all of your help. I'll look through your suggested solutions and maybe restart from the bottom ;). Will give you a heads up when I'm done.
You could simply use a Map (that emulates a "Multiset") for the purpose of counting words:
String textarray[] = text.split(" ");
// TreeMap gives sorting by alphabetical order "for free"
Map<String, Integer> wordCounts = new TreeMap<>();
for (int i = 0; i < textarray.length; i++) {
Integer count = wordCounts.get(textarray[i]);
wordCounts.put(textarray[i], count != null ? count + 1 : 1);
}
for (Map.Entry<String, Integer> e : wordCounts.entrySet()) {
System.out.println("<" + e.getKey() + "> - <" + e.getValue() + ">");
}
You can use Scanner to read your input file (whose location is denoted by "filepath") using the new line character as your delimiter and add the words directly to an ArrayList<String>.
Then, iterate the ArrayList<String> and count the frequency of each word in your original file in a HashMap<String, Integer>.
Full Working Code:
Scanner s = new Scanner(new File("filepath")).useDelimiter("\n");
List<String> list = new ArrayList<>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
Map<String, Integer> wordFrequency = new HashMap<>();
for(String str : list)
{
if(wordFrequency.containsKey(str))
wordFrequency.put(str, wordFrequency.get(str) + 1); // Increment the frequency by 1
else
wordFrequency.put(str, 1);
}
//Print the frequency:
for(String str : list)
{
System.out.println(str + ": " + wordFrequency.get(str));
}
EDIT:
Alternatively, you can read the entire file into a single String and then split the contents of the String using \n as delimiter into a list. The code is shorter than the first option:
String fileContents = new Scanner(new File("filepath")).useDelimiter("\\Z").next(); // \Z is the end of string anchor, so the entire file is read in one call to next()
List<String> list = Arrays.asList(fileContents.split("\\s*\\n\\s*"));// Using new line character as delimiter, it adds every word to the list
I'd do it like this:
Map<String,Integer> occurs = new HashMap<String,Integer>();
int i = 0, number;
for (; i < textarray.length; i++) {
if (occurs.containsKey(textarray[i])) {
number = occurs.get(testarray[i]);
occurs.put(testarray[i], number + 1);
} else {
occurs.put(testarray[i], 1);
}
}
for(Map.Entry<String, Integer> entry : occurs.entrySet()){
System.out.println("<" + entry.getKey() + "> - " + entry.getValue());
}
System.out.println("<"+textarray[textarray.length-1]+"> - <"+nameCounter+">");
you need this after your loop because you print only till i-1 even though your loop runs correct number of times
But using a map is a better choice
Because your code prints the results for a name the first time that that name isn't the same any more. Then you are missing a print statement for the last entry. To solve this you can just add another if statement at the end of your loop that checks if this is the last time the loop will loop. The if statement would look like this:
if(i == textarray.length - 1){
System.out.println("<"+textarray[i]+"> - <"+nameCounter+">");
}
Now the loop will look like this:
for (int i=1; i < textarray.length; i++) {
if (i > 0 && textarray[i].equals(textarray[i-1])) {
nameCounter++;
unique = false;
}
if (i > 0 && !textarray[i].equals(textarray[i-1]) && !unique) {
System.out.println("<"+textarray[i-1]+"> - <"+nameCounter+">");
nameCounter = 1;
unique = true;
}
else if (i > 0 && !textarray[i].equals(textarray[i-1]) && unique) {
//nameCounter = 1;
System.out.println("<"+textarray[i-1]+"> - <"+nameCounter+">");
}
if(i == textarray.length - 1){
System.out.println("<"+textarray[i]+"> - <"+nameCounter+">");
}
}
And now the loop will also print the results for the last entry in the list.
I hope this helps :)
P.S. some of the other solutions here are far more efficient but this is a solution for your current approach.
I want to discuss the logic you used initially to solve the problem of uniqueness of values in an array of strings.
You just compared two cells of the array, and supposing if they are not equal this means that the name of textarray[i] is unique !
This is false, because it can occur later on while your "unique" boolean variable was set to true.
example:
john | luke| john|charlotte|
comparing the first and second will give you that both john and luke are unequal and comparing them again will say also that they are unequal too when the "i" of loop advances, but this is not the truth.
so lets imagine that we have no map in java, how to solve this with algorithms ?
I will help you with an idea.
1 - create a function that takes in parameter the string that you want to verify and the table
2- then loop all the table testing if the string is equal the cell of the current table if yes, return null or -1
3- if you finish looping the table until the last cell of the array, this means that your string is unique just print if on screen.
4- call this function textarray.length times
and you will have on your screen only the unique names.
First things first:
You won't need your text variable since we will be replacing it with a more appropriate data structure. You need one to store the names that you found so far in the file, along with an integer (number of occurrences) for each name that you found.
Like Dmitry said, the best data structure you can use for this particular case is Hashtable or HashMap.
Assuming that the file structure is a single name per line without any punctuation or spaces, your code would look something like this:
try {
Hashtable<String,Integer> table = new Hashtable<String,Integer>();
file = input.readLine();
read = new BufferedReader (new FileReader(file));
while ((line = read.readLine()) != null) {
line.trim();
if(table.containsKey(line))
table.put(line, table.get(line)+1);
else
table.put(line, 1);
}
System.out.println(table); // looks pretty good and compact on the console... :)
} catch (FileNotFoundException e) {
System.out.println("File was not found.");
} catch (IOException e) {
System.out.println("An error has occured.");
}
The code below is the entire program so far (just to avoid any missing pieces.
The issue I'm having is that I'm trying use the .substring(int,int) method to pull two characters from the given string and write the two characters pulled into a separate array. The problem is that every character pulled from the string using .substring() is a blank space. There are no letters pulled at all. I tested the function using a simple print method and it went to show that printing sentences.get(i).substring(j,j++) only prints blank spaces. It's populating my arrays with those empty spaces.
Any clue as to what could be causing this? My compiler isn't giving me any errors or warnings whatsoever.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JacSim {
public static void main(String [] args) throws FileNotFoundException {
Scanner userScanner = new Scanner(System.in);
System.out.println("Please enter the filename for your input file (with extension).");
String fileName = userScanner.nextLine();
File file = new File(fileName);
Scanner scanner = new Scanner( new FileInputStream(file));
List<String> sentences = new ArrayList();
while (scanner.hasNextLine()) {
String sentence = scanner.nextLine();
sentences.add(sentence);
}
System.out.println("Input Sentences:\n");
for(int i=0;i<sentences.size();i++) {
System.out.println(i + " : " + sentences.get(i));
}
List<List<String>> shingles = new ArrayList();
sentences.stream().forEach((String _item) -> {
shingles.add(new ArrayList());
});
System.out.println("\nSorted Shingle Arrays:\n");
shinglesMethod(shingles, sentences);
}
private static List shinglesMethod(List<List<String>> shingles, List<String> sentences) {
for (int i=0;i<sentences.size();i++) {
for(int j=0;j++<sentences.get(i).length();j++) {
shingles.get(i).add(sentences.get(i).substring(j,j++));
}
showList( i, shingles.get(i) );
}
return shingles;
}
private static void showList( int n, List List ) {
System.out.print(n + " : ");
List.stream().forEach((o) -> {
System.out.print( o + " " );
});
System.out.println();
}
The chunk of code to pay attention to is
for (int i=0;i<sentences.size();i++) {
for(int j=0;j++<sentences.get(i).length();j++) {
shingles.get(i).add(sentences.get(i).substring(j,j++));
}
showList( i, shingles.get(i) );
}
Forgot to clarify that the scanner is reading in the words properly and that each string is read as expected. The only issue I'm finding is with the .substring() method.
This seems to be rooted in confusion about what ++ does. j++ returns the value of j and afterwards increments j.
.substring(j,j++) will always return the empty string, because it increments j after getting a substring between j inclusive and j exclusive. substring(j, j + 1) would probably be more what you want.
You also need to use j + 1 < sentences.get(i).length(), instead of j++, because you're changing the value of j as you're trying to check it, which is almost certainly not what you want. The only place j++ should be mentioned would be in the update statement in the for loop.
j++ uses the value of j and then increments the value of j. So your code is equivalent to substring(j,j). Also, when you write x.substring(i,j), the substring begins at i and extends to the character at j - 1.
Use substring(j,j+2) instead and change the condition of your inner while loop to j<sentences.get(i).length() - 2.
Sorry if everyone sees me post a lot of silly questions today (just a preface). However this is the final for a summer class and my teacher stopped caring/explaining how to do things for my first coding class.
For this project I have to print a list of integers from a .dat file into a program in reverse order with a max of 40 possible values in the array (Did all that) The problem I am encountering is that he said the program should also be flexible enough to deal with less than 40 values. However given my current code I always encounter an error saying "nosuchelementexception". Any help would be greatly appreciate. Below is a copy of what I have:
import java.io.*; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
public class program3
{
public static void main(String [] ars) throws IOException
{
double [] Values; // creating array called value
Values = new double [40]; // establishing array with 40 cells
int k; // creating counter integer
Scanner InputFile = new Scanner( new FileReader("temp.dat")); // input file you wish to open.
for (k = 0 ; k < Values.length ; k++)
Values[k] = InputFile.nextDouble();
for (k = Values.length - 1 ; k >= 0 ; k--)
System.out.println("Cell " + k + " contains the value " + Values[k]);
InputFile.close();
}
}
The problem you are having is that the length attribute of an array refers to the declared length, not the amount of data in it.
When you try to use the length (in this case 40) to control the loop you use for reading data, you will get an error if there are fewer elements to read.
What you want to do is read more input only while there exists more input to get:
int k = 0;
while (inputFile.hasNextDouble()) {
Values[k++] = inputFile.nextDouble();
}
Also, consider using an ArrayList instead of an array. The ArrayList class allows you to store a dynamic amount of data, so you don't have to worry about pre-allocating storage space:
ArrayList<Double> values = new ArrayList<>();
while (inputFile.hasNextDouble()) {
values.add(inputFile.nextDouble());
}
You can use a while loop and a counter
import java.io.*; // Imports any file operation (ie Reading or Writing)
import java.util.Scanner; // Imports scanner class
public class program3
{
public static void main(String [] ars) throws IOException
{
double [] Values; // creating array called Values
Values = new double [40]; // establishing array has 40 cells
int counter = 0; // creating counter integer
Scanner inputFile = new Scanner( new FileReader("temp.dat")); //input file you with to open.
while(inputFile.hasNextDouble()){
Values[counter] = InputFile.nextDouble();
counter++;
}
for (i = counter - 1 ; i >= 0 ; i--)
System.out.println("Cell " + i + " contains the value " + Values[i]);
InputFile.close();
}
}
If you do not have to use an Array, use an ArrayList<Double>. This allows you to call values.add(value) to add to the list. The length is variable and you can use your same code (just replace values[i] with values.get(i))
However, if you do have to use arrays, created a method that adds to the array. Start with a 0 length array, and when an element is added, create a new array of length+1, then copy the old elements in, and add the new element at the end.
There are many other ways to go about this, but these two allow you to use your existing working code.
Array approach:
values = new double[0];
public void add(double x){
double[] temp = new double[values.length +1];
for(int i =0; i< values.lenght; i++){
temp[i] = values[i];
}
temp[temp.length-1] = x;
values = temp;
}
you should use an arrayList instead so you don't have to initially set the size of the array. This would make it so that you never have empty elements in the array.
Another option would be to initialize the array with placeholder values like -1, and then only perform the switch if the value is not -1.
Add a counter that keeps track of how many item you put into the array and use that to determine where to stop when you go to print them out.
Is there 40 elements in your .dat file. If there isnt your code probably gave the exception.
for (k = 0 ; k < Values.length ; k++)
Values[k] = InputFile.nextDouble();
If your .dat file doesn't contain 40 elemennts then value[39] can't be filled in.
An Array has a fixed size after initialising it, so you may want to use dynamic datastructure or instead use a while loop as posted below. I personally would recommend an ArrayList in this case.
You should also use the method
Scanner.hasNext() or in your particular case Scanner.hasNextDouble() Docs
to get any new elements.
So your program would then look like this:
import java.io.*; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
import java.util.ArrayList;
public class program3
{
public static void main(String [] ars) throws IOException
{
ArrayList<Double> doubles = new ArrayList<Double>();
Scanner inputFile = new Scanner( new FileReader("temp.dat"));
while (inputFile.hasNextDouble()) {
doubles.add(inputFile.nextDouble());
}
inputFile.close();
for (Double value : doubles) {
System.out.println(value);
}
}
}
Java has convenient methods in it's Collections class to allow sorting. You may want to check this out if you haven't already.
I admire your grit getting on Stack Overflow.
To reward you here's your answer.
The first for loop you have iterates over your new, empty array. That would be find except you are RETRIEVING information from the Scanner object, InputFile.
So you should in fact be iterating over that object! Not your array. No shame though. Classic mistake.
Here's my version of your code:
import java.io.FileReader;
import java.io.IOException; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
public class program3
{
public static void main( String [] ars ) throws IOException
{
double [] Values; // creating array called value
Values = new double [40]; // establishing array has 20 cells
int k; // creating counter integer
//input file you with to open.
Scanner InputFile = new Scanner( new FileReader( "temp.dat" ) );
for ( k = 0; InputFile.hasNextDouble(); k ++ )
Values[k] = InputFile.nextDouble();
for ( k = Values.length - 1; k >= 0; k-- )
System.out.println( "Cell " + k + " contains the value " + Values[k] );
InputFile.close();
}
}
Hope this helps!
okay basically im wanting to separate the elements in a string from int and char values while remaining in the array, but to be honest that last parts not a requirement, if i need to separate the values into two different arrays then so be it, id just like to keep them together for neatness. this is my input:
5,4,A
6,3,A
8,7,B
7,6,B
5,2,A
9,7,B
now the code i have so far does generally what i want it to do, but not completely
here is the output i have managed to produce with my code but here is where im stuck
54A
63A
87B
76B
52A
97B
here is where the fun part is, i need to take the numbers and the character values and separate them so i can use them in a comparison/math formula.
basically i need this
int 5, 4;
char 'A';
but of course stored in the array that they are in.
Here is the code i have come up with so far.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class dataminingp1
{
String[] data = new String[100];
String line;
public void readf() throws IOException
{
FileReader fr = new FileReader("C:\\input.txt");
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((line = br.readLine()) != null)
{
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
System.out.println("Data length: "+data.length);
String[][] root;
List<String> lines = Files.readAllLines(Paths.get("input.txt"), StandardCharsets.UTF_8);
root = new String[lines.size()][];
lines.removeAll(Arrays.asList("", null)); // <- remove empty lines
for(int a =0; a<lines.size(); a++)
{
root[a] = lines.get(a).split(" ");
}
String changedlines;
for(int c = 0; c < lines.size(); c++)
{
changedlines = lines.get(c).replace(',', ' '); // remove all commas
lines.set(c, changedlines);// Set the 0th index in the lines with the changedLine
changedlines = lines.get(c).replaceAll(" ", ""); // remove all white/null spaces
lines.set(c, changedlines);
changedlines = lines.get(c).trim(); // remove all null spaces before and after the strings
lines.set(c, changedlines);
System.out.println(lines.get(c));
}
}
public static void main(String[] args) throws IOException
{
dataminingp1 sarray = new dataminingp1();
sarray.readf();
}
}
i would like to do this as easily as possible because im not to incredibly far along with java but i am learning so if need be i can manage with a difficult process. Thank you in advance for any at all help you may give. Really starting to love java as a language thanks to its simplicity.
This is an addition to my question to clear up any confusion.
what i want to do is take the values stored in the string array that i have in the code/ input.txt and parse those into different data types, like char for character and int for integer. but im not sure how to do that currently so what im asking is, is there a way to parse these values all at the same time with out having to split them into different arrays cause im not sure how id do that since it would be crazy to go through the input file and find exactly where every char starts and every int starts, i hope this cleared things up a bit.
Here is something you could do:
int i = 0;
for (i=0; i<list.get(0).size(); i++) {
try {
Integer.parseInt(list.get(0).substring(i, i+1));
// This is a number
numbers.add(list.get(0).substring(i, i+1));
} catch (NumberFormatException e) {
// This is not a number
letters.add(list.get(0).substring(i, i+1));
}
}
When the character is not a number, it will throw a NumberFormatException, so, you know it is a letter.
for(int c = 0; c < lines.size(); c++){
String[] chars = lines.get(c).split(",");
String changedLines = "int "+ chars[0] + ", " + chars[1] + ";\nchar '" + chars[0] + "';";
lines.set(c, changedlines);
System.out.println(lines.get(c));
}
It is very easy, if your input format is standartized like this. As long as you dont specify more (like can have more than 3 variables in one row, or char can be in any column, not only just third, the easiest approach is this :
String line = "5,4,A";
String[] array = line.split(",");
int a = Integer.valueOf(array[0]);
int b = Integer.valueOf(array[1]);
char c = array[2].charAt(0);
Maybe something like this will help?
List<Integer> getIntsFromArray(String[] tokens) {
List<Integer> ints = new ArrayList<Integer>();
for (String token : tokens) {
try {
ints.add(Integer.parseInt(token));
} catch (NumberFormatException nfe) {
// ...
}
}
return ints;
}
This will only grab the integers, but maybe you could hack it around a bit to do what you want :p
List<String> lines = Files.readAllLines(Paths.get("input.txt"), StandardCharsets.UTF_8);
String[][] root = new String[lines.size()][];
for (int a = 0; a < lines.size(); a++) {
root[a] = lines.get(a).split(","); // Just changed the split condition to split on comma
}
Your root array now has all the data in the 2d array format where each row represents the each record/line from the input and each column has the data required(look below).
5 4 A
6 3 A
8 7 B
7 6 B
5 2 A
9 7 B
You can now traverse the array where you know that first 2 columns of each row are the numbers you need and the last column is the character.
Try this way by using getNumericValue() and isDigit methods. This might also work,
String myStr = "54A";
boolean checkVal;
List<Integer> myInt = new ArrayList<Integer>();
List<Character> myChar = new ArrayList<Character>();
for (int i = 0; i < myStr.length(); i++) {
char c = myStr.charAt(i);
checkVal = Character.isDigit(c);
if(checkVal == true){
myInt.add(Character.getNumericValue(c));
}else{
myChar.add(c);
}
}
System.out.println(myInt);
System.out.println(myChar);
Also check, checking character properties