Creating array from reading a file - java

I have a file with the following:
5
212:Float On:Modest Mouse
259:Cherub Rock:Smashing Pumpkins
512:Won't Get Fooled Again:The Who
417:Teen Age Riot:Sonic Youth
299:PDA:Interpol
I need to create a array but I need to take into account the integer it starts with, then read the rest as strings taking into account the initial line containing only an integer. I've made the method to read the file and print, just don't know how to split it up.

An example of how to do it:
String s = "212:Float On:Modest Mouse"; // your input - a line from the file
String[] arr = s.split(":");
System.out.println(arr[0]); // your int
// The rest of the array elements will be the remaining text.
// You can concatenate them back into one string if necessary.

you can read file using Scanner
readlines = new Scanner(filename);
while(readlines.hasNextLine())
{
String line = readlines.nextLine();
String[] values = line.split(":");
int firstColumn = -1;
if (values.length > 0) {
try {
firstColumn = Integer.parseInt(values[0]);
} catch (NumberFormatException ex) {
// the value in the first column is not an integer
}
}
}

I've grown a habit of reading the entire file into a List, then handling the List in memory. Doing this is not the only option.
Once I have the file read in, I look at the first line to know how many tracks to expect in the remaining file. I then would loop through the remaining List to either get the number of tracks from the first line or until I reach the end of the list, in the event that the number of tracks (from the first line) exceeds the actual amount of tracks that are in the file.
As I go through the tracks I would use substring to break the line apart, and convert just the first part.
Update
Base on your comment, I've updated to use split instead of substring. Then some basic alignment formatting for output
public static void main(String[] args) throws Exception {
String yourFile = "path to your file.txt";
List<String> yourFileLines = new ArrayList<>(Files.readAllLines(Paths.get(yourFile)));
// You know the first line is suppose to be the number of tracks so convert it to a number
int numberOfTracks = Integer.valueOf(yourFileLines.get(0));
// Either go to the number of tracks or till the end of file
List<Track> tracks = new ArrayList<>();
for (int i = 1; (i <= numberOfTracks && i < yourFileLines.size()); i++) {
String currentFileLine = yourFileLines.get(i);
String[] currentFileLinePieces = currentFileLine.split(":");
Track currentTrack = new Track();
currentTrack.TrackTime = Integer.valueOf(currentFileLinePieces[0]);
currentTrack.TrackTitle = currentFileLinePieces[1];
currentTrack.TrackArtist = currentFileLinePieces[2];
tracks.add(currentTrack);
}
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "TITLE", "ARTIST", "TIME"));
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "-----", "------", "----"));
for (Track currentTrack : tracks) {
System.out.println(currentTrack);
}
}
public static class Track {
public int TrackTime;
public String TrackTitle;
public String TrackArtist;
#Override
public String toString() {
return String.format("%-20s\t\t%-20s\t\t%-20d", TrackTitle, TrackArtist, TrackTime);
}
}
Results:
Here's an example using a Scanner, and breaking everything into methods. You should be able to use List and ArrayList. Results are the same.
public static void main(String[] args) throws Exception {
String yourFile = "data.txt";
List<String> yourFileLines = readFile(yourFile);
if (yourFileLines.size() > 0) {
// You know the first line is suppose to be the number of tracks so convert it to a number
int numberOfTracks = Integer.valueOf(yourFileLines.get(0));
List<Track> tracks = getTracks(numberOfTracks, yourFileLines);
printTracks(tracks);
}
}
public static List<String> readFile(String pathToYourFile) {
List<String> yourFileLines = new ArrayList();
try {
File yourFile = new File(pathToYourFile);
Scanner inputFile = new Scanner(yourFile);
while(inputFile.hasNext()) {
yourFileLines.add(inputFile.nextLine().trim());
}
} catch (Exception e) {
System.out.println(e);
}
return yourFileLines;
}
public static List<Track> getTracks(int numberOfTracks, List<String> yourFileLines) {
List<Track> tracks = new ArrayList();
// Either go to the number of tracks or till the end of file
for (int i = 1; (i <= numberOfTracks && i < yourFileLines.size()); i++) {
String currentFileLine = yourFileLines.get(i);
String[] currentFileLinePieces = currentFileLine.split(":");
Track currentTrack = new Track();
currentTrack.TrackTime = Integer.valueOf(currentFileLinePieces[0]);
currentTrack.TrackTitle = currentFileLinePieces[1];
currentTrack.TrackArtist = currentFileLinePieces[2];
tracks.add(currentTrack);
}
return tracks;
}
public static void printTracks(List<Track> tracks) {
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "TITLE", "ARTIST", "TIME"));
System.out.println(String.format("%-20s\t\t%-20s\t\t%-20s", "-----", "------", "----"));
for (Track currentTrack : tracks) {
System.out.println(currentTrack);
}
}
public static class Track {
public int TrackTime;
public String TrackTitle;
public String TrackArtist;
#Override
public String toString() {
return String.format("%-20s\t\t%-20s\t\t%-20d", TrackTitle, TrackArtist, TrackTime);
}
}

Related

How to convert ArrayList<String> to int[] in Java

I read Bert Bates and Katie Sierra's book Java and have a problem.
The Task: to make the game "Battleship" with 3 classes via using ArrayList.
Error: the method setLocationCells(ArrayList < String >) in the type
SimpleDotCom is not applicable for the arguments (int[])
I understand that ArrayList only will hold objects and never primatives. So handing over the list of locations (which are int's) to the ArrayList won't work because they are primatives. But how can I fix it?
Code:
public class SimpleDotComTestDrive {
public static void main(String[] args) {
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while(isAlive) {
String guess = helper.getUserInput("Enter the number");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals("Kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}
public class SimpleDotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}
public String checkYourself(String stringGuess) {
String result = "Miss";
int index = locationCells.indexOf(stringGuess);
if (index >= 0) {
locationCells.remove(index);
if(locationCells.isEmpty()) {
result = "Kill";
} else {
result = "Hit";
}
}
return result;
}
}
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0)
return null;
} catch (IOException e) {
System.out.println("IOException:" + e);
}
return inputLine;
}
}
convert ArrayList to int[] in Java
Reason for Basic Solution
Here's a simple example of converting ArrayList<String> to int[] in Java. I think it's better to give you an example not specific to your question, so you can observe the concept and learn.
Step by Step
If we have an ArrayList<String> defined below
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
Then the easiest solution for a beginner would be to loop through each list item and add to a new array. This is because the elements of the list are type String, but you need type int.
We start by creating a new array of the same size as the List
int[] numbers = new int[numbersInAList.size()];
We then iterate through the list
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
Then inside the loop we start by casting the String to int
int num = Integer.parseInt(numbersInAList.get(ndx));
But there's a problem. We don't always know the String will contain a numeric value. Integer.parseInt throws an exception for this reason, so we need to handle this case. For our example we'll just print a message and skip the value.
try {
int num = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
We want this new num to be placed in an array, so we'll place it inside the array we defined
numbers[ndx] = num;
or combine the last two steps
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
Final Result
If we combine all of the code from "Step by Step", we get the following
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
int[] numbers = new int[numbersInAList.size()];
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
try {
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
}
Important Considerations
Note there are more elegant solutions, such as using Java 8 streams. Also, it's typically discouraged to store ints as Strings, but it can happen, such as reading input.
I can't see where you call setLocationCells(ArrayList<String>) in your code, but if the only problem is storing integers into an ArrayList there is a solution:
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(1);
myArray.add(2);
It is true that you can't use primitive types as generics, but you can use the Java wrapper types (in this case, java.lang.Integer).

reverse a stack and concatenate a popped stack

I'm trying to push any array list to a stack in reverse then concatenate a popped stacked. I getting the information from a file then storing it into an array List. Then i pushed the array List into a stack. now when i print the stack out its just printing the array List how can i pop the stack and concatenate it? here is my code so far
public static LinkedListStack myStack = new LinkedListStack();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
song.add(line = inFile.next());
}
for(int i = 0; i < song.size(); i++)
{
myStack.push1(song);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
if(!myStack.empty())
{
System.out.println(myStack.pop1());
} else
{
System.out.println("Sorry stack is empty");
}
}
output looks like this now :[Mary, had, a, little, lamb, Whose, fleece, was, white, as, snow, Everywhere, that, Mary, went, The, lamb, was, sure, to, go]
I'm trying to get it to look like this:
lamb little a had Mary
snow as white was fleece Whose
went Mary that Everywhere
go to sure was lamb The
i have made a custom class for the push and pop
{
private Node first;
/**
Constructs an empty stack.
*/
public LinkedListStack()
{
first = null;
}
/**
Adds an element to the top of the stack.
#param element the element to add
*/
public void push1(Object element)
{
Node newNode = new Node();
newNode.data = element;
newNode.next = first;
first = newNode;
}
/**
Removes the element from the top of the stack.
#return the removed element
*/
public Object pop1()
{
if (first == null) { throw new NoSuchElementException(); }
Object element = first.data;
first = first.next;
return element;
}
/**
Checks whether this stack is empty.
#return true if the stack is empty
*/
public boolean empty()
{
return first == null;
}
class Node
{
public Object data;
public Node next;
}
}
I fixed the problems in your code. Here is the working version along with some comments. This assumes the sentences in the file are separated by new lines and the words are separated by white spaces.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GeneralTest {
//You want the same ordering for sentences. This collection
//therefore should be a list (or a queue)
//I have not changed the name so you can see how it makes a
//difference
public static List<LinkedListStack> myStack = new ArrayList<>();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
//Here you need to use nextLine() instead of next()
song.add(inFile.nextLine());
}
//This loop is the main location your original code goes wrong
//You need to create a stack for each sentence and add it to the
//list. myStack will hold a list of stacks after this loop is done
for(int i = 0; i < song.size(); i++)
{
String songString = (String) song.get(i);
String[] sga = songString.split(" ");
LinkedListStack rowStack = new LinkedListStack();
for(int j=0; j < sga.length; j++) rowStack.push1(sga[j]);
myStack.add(rowStack);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
//To get all values in a collection you need to
//loop over it. A single if will not work
for(LinkedListStack rs : myStack)
{
//Each entry in the list is a LinkedListStack
//So you can pop them and print the results with
//appropriate separators
while(!rs.empty())
System.out.print(rs.pop1() + " ");
System.out.println();
}
}
}
Now, your code has many other problems. For example, you really should use generics when you create a collection class.
The main problem with your code is that to produce the output you have described, you will need a queue of stacks. I have implemented the concept using ArrayList to show the source of the problem. But if you want to learn data structures (or if this is a homework problem), then you should try implementing and using a queue as well.

Trying to display contents of ArrayList. Getting [Ljava.lang.String;#232204a1

I am attempting to output the contents of an ArrayList, but no matter which approach I try I seem get the location of the Array rather than the contents of the Array. Running each of the following together gives me:
run:
[[Ljava.lang.String;#55f96302, [Ljava.lang.String;#232204a1, [Ljava.lang.String;#4554617c, [Ljava.lang.String;#7f31245a, [Ljava.lang.String;#2503dbd3, [Ljava.lang.String;#5cad8086]
[Ljava.lang.String;#232204a1
[Ljava.lang.String;#232204a1
[Ljava.lang.String;#232204a1
Here's the code snippet:
// Each of the following approaches results in
// [Ljava.lang.String;#232204a1
// instead of the actual value of the ArrayList.
String test = accountNumbers.get(1);
System.out.println(test);
System.out.println(accountNumbers.get(1));
System.out.println(accountNumbers.get(1).toString());
// This actually outputs:
// [[Ljava.lang.String;#55f96302, [Ljava.lang.String;#232204a1, [Ljava.lang.String;#4554617c, [Ljava.lang.String;#7f31245a, [Ljava.lang.String;#2503dbd3, [Ljava.lang.String;#5cad8086]
String str = Arrays.toString(accountNumbers.toArray());
System.out.println(str);
I'm not really sure what's causing this. Is there some way to get the contents to display?
EDIT: Here's the entire method. An answer on another question (here) advised me to try using ArrayList instead of the approach I was using. I adapted the suggestion, but I felt that the problems were better placed in a new question rather than as an edit to that question.
protected static void loadAccountInformationFromFile() throws Exception
{
Scanner account = new Scanner(new File(INPUT_ACCOUNT_FILE)).useDelimiter(",");
int sortCount = 1;
List<String> accountNumbers = new ArrayList<>();
List<String> firstNames = new ArrayList<>();
List<String> lastNames = new ArrayList<>();
List<String> balances = new ArrayList<>();
List<String> lastVariables = new ArrayList<>();
do {
String[] temp1 = account.next().split(",");
String temp2 = "" + temp1;
if (sortCount == ACCOUNT_NUMBER_COUNT) {
accountNumbers.add(temp2);
} else if (sortCount == FIRST_NAME_COUNT) {
firstNames.add(temp2);
} else if (sortCount == LAST_NAME_COUNT) {
lastNames.add(temp2);
} else if (sortCount == BALANCE_COUNT) {
balances.add(temp2);
} else if (sortCount == LAST_VARIABLE_COUNT) {
lastVariables.add(temp2);
}
if (sortCount < MAX_VALUES_PER_LINE) {
sortCount++;
} else {
sortCount = 1;
}
} while (account.hasNext());
// Each of the following approaches results in
// [Ljava.lang.String;#232204a1
// instead of the actual value of the ArrayList.
String test = accountNumbers.get(1);
System.out.println(test);
System.out.println(accountNumbers.get(1));
System.out.println(accountNumbers.get(1).toString());
// This actually outputs:
// [[Ljava.lang.String;#55f96302, [Ljava.lang.String;#232204a1, [Ljava.lang.String;#4554617c, [Ljava.lang.String;#7f31245a, [Ljava.lang.String;#2503dbd3, [Ljava.lang.String;#5cad8086]
String str = Arrays.toString(accountNumbers.toArray());
System.out.println(str);
account.close();
// I want to adapt what I previously used to access the ArrayLists.
// Bank bank = new Bank();
//
// bank.openAccount(new CheckingAccount(10100, new Customer("Adam", "Apple"),500.00,false));
// bank.openAccount(new CheckingAccount(10101, new Customer("Beatrice", "Bagel"),2000.00,true));
// bank.openAccount(new SavingsAccount(2010, new Customer("Adam", "Apple"),5000.00,0.02));
}
EDIT 2: Here are the class variables:
private final static String INPUT_ACCOUNT_FILE = "accountInfo.txt";
private static final int ACCOUNT_NUMBER_COUNT = 0;
private static final int FIRST_NAME_COUNT = 1;
private static final int LAST_NAME_COUNT = 2;
private static final int BALANCE_COUNT = 3;
private static final int LAST_VARIABLE_COUNT = 4;
private final static int MAX_VALUES_PER_LINE = 5;
EDIT 3: For the benefit of those who may read this question late and be confused by some of the comments on the correct answer, part of my issue was related to an issue with the text file itself. This is an example of the formatting of the text file:
10100,First,Last,Balance,value
10101,First,Last,Balance,value
20100,First,Last,Balance,value
Also: To get the ArrayLists to store the correct strings I had to change sortCount from:
int sortCount = 1;
to
int sortCount = 0;
Because when it was set at 1 it would store the first name in the account number string.
The problem is not in your "displaying" but in the way you read the contents from the file.
Your code prints out correctly "addresses" because the strings in accountNumbers instance are really these values (because you put array of strings into one single string). So what really happens is that in your temp2 String is your temp1.toString().
You are using wrong delimiter (you should use default one for whitespaces instead):
Scanner account = new Scanner(new File(INPUT_ACCOUNT_FILE));
And then assign values like:
if (temp1.length > ACCOUNT_NUMBER_COUNT) {
accountNumbers.add(temp1[ACCOUNT_NUMBER_COUNT]);
if (temp1.length > FIRST_NAME_COUNT) {
firstNames.add(temp1[FIRST_NAME_COUNT]);
if (temp1.length > LAST_NAME_COUNT) {
lastNames.add(temp1[LAST_NAME_COUNT]);
if (temp1.length > BALANCE_COUNT) {
balances.add(temp1[BALANCE_COUNT]);
if (temp1.length > LAST_VARIABLE_COUNT) {
lastVariables.add(temp1[LAST_VARIABLE_COUNT]);
}
Your temp2 and sort variables are not needed.
Anyway it is a bit weird to use these collections. I would rather suggest to do it like:
Scanner scanner = new Scanner(new File(INPUT_ACCOUNT_FILE));
Collection<Account> bank = new ArrayList<>();
while (scanner.hasNext()) {
String[] fields = scanner.next().split(",");
if (fields.length < MAX_VALUES_PER_LINE) {
continue; // incomplete row, skip it or maybe throw some exception?
}
String number = fields[ACCOUNT_NUMBER_COUNT];
Customer customer = new Customer(fields[FIRST_NAME_COUNT], fields[LAST_NAME_COUNT]);
double balance = Double.valueOf(fields[BALANCE_COUNT]);
String type = fields[LAST_VARIABLE_COUNT];
Account a = null;
switch (type) {
case "N": {
a = new CheckingAccount(number, customer, balance);
break;
}
case "0.02": {
a = new SavingsAccount(number, customer, balance);
break;
}
default: {
continue; // unknown type of account, skip it or maybe throw some exception?
}
}
bank.add(a);
}
String temp2 = "" + temp1;
You are trying to concat a blank with a string array, this is equals with
String temp2 = "" + temp1.toString();
Note that toString() of Array will return object references, not the value.
So you should try to convert array to some Java Collection class that implements the toString() method like ArrayList
String temp2 = "" + Arrays.asList(temp1).toString();
or you can also do
String temp2 = "" + Arrays.toString(temp1);
Both will give you the String value (and some "[" and "]" too, I guess, because of the toString() implementation of ArrayList and Arrays, you can work it out).

Initializing an ordered map?

I'm having trouble on how to create a new ordered map that reads a file char by char. Here is the beginning of my program
public class Practice {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the file name to random write: ");
String fileName = keyboard.nextLine();
System.out
.print("Enter nGram length, 1 is like random, 12 is like the book: ");
int nGramLength = keyboard.nextInt();
keyboard.close();
Practice rw = new Practice(fileName, nGramLength);
rw.printRandom(500);
}
private HashMap<String, ArrayList<Character>> all;
private int nGramLength;
private String fileName;
private StringBuilder theText;
private static Random generator;
private String nGram;
public Practice(String fileName, int nGramLength) {
this.fileName = fileName;
this.nGramLength = nGramLength;
generator = new Random();
makeTheText();
setRandomNGram();
setUpMap(); // Algorithm considered during section.
}
private void makeTheText() {
Scanner inFile = null;
try {
inFile = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
theText = new StringBuilder();
while (inFile.hasNextLine()) {
theText = theText.append(inFile.nextLine().trim());
theText = theText.append(' ');
}
}
public void setRandomNGram() {
generator = new Random();
int temp = theText.length() - nGramLength - 1;
int start = generator.nextInt(temp);
nGram = theText.substring(start, start + nGramLength);
}
// Read theText char by char to build a OrderedMaps where
// every possible nGram exists with the list of followers.
// This method need these three instance variables:
// nGramLength theText all
private void setUpMap() {
// TODO: Implement this method
for(int i = 0; i < nGramLength; i++)
{
ArrayList<Character> key = all.get(i);
}
}
// Print chars random characters. Please insert line breaks to make your
// output readable to the poor grader :-)
void printRandom(int howMany) {
// TODO: Implement this method
}
}
I need to work on the last two methods, but I am confused as to how to iterate through a hashmap
You can iterate over a HashMap by iterating over its entrySet(). That will give you both the key and value:
for (Map.Entry<String, ArrayList<Character>> entry : all) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Alternatively you can iterate only over its keySet() or valueSet(), but it sounds as if you want both key and value here.
The answer is that you do not iterator over a map. Maps do not have an iterator because that would make no sense. What would it iterator over the keys the values or both. The solution is turn your keys or values into a collection. You do this with the values method (returns a collection of the values) and keySet method (returns a set of the keys in the map) You can then call those collection's iterator methods.

Changing a String into an int

I have an array of string objects that was read from a file. Some of these strings I need to use as ints. I wrote a method to read the file but now I just don't know how to get the numbers from the file, here is the file
29,,
Chute,1,0
Chute,2,0
Chute,3,0
Chute,4,0
Chute,5,0
Chute,6,0
Chute,7,0
Chute,8,0
Chute,9,0
Chute,0,1
Chute,0,2
Chute,0,3
Chute,9,1
Chute,9,2
Chute,9,3
Ladder,0,5
Ladder,1,5
Ladder,2,5
Ladder,3,5
Ladder,4,5
Ladder,5,5
Ladder,6,5
Ladder,7,5
Ladder,8,5
Ladder,9,5
Ladder,9,6
here is my method
public void readBoard(String file)throws FileNotFoundException
{
File clboard = new File ("myBoard.csv");
Scanner x = new Scanner(clboard);
while(x.hasNext())
{
String c = x.nextLine();
String [] myboard =c.split(",");
}
}
Try
int numOne = Integer.parseInt(myboard[1]);
int numTwo = Integer.parseInt(myboard[2]);
immediately after your split line.
String [] myboard = c.split(",");
if (myboard.length < 3) {
// error message
} else {
int i1 = Integer.parseInt(myboard[1]);
int i2 = Integer.parseInt(myboard[2]);
}
You might also want to add a try/catch to handle NumberFormatException (which occurs when you try to convert something that isn't a number).
public void readBoard(String file)throws FileNotFoundException
{
File clboard = new File ("myBoard.csv");
Scanner x = new Scanner(clboard);
while(x.hasNext()) {
List<Integer> number = new ArrayList<Integer>();
String c = x.nextLine();
String [] myboard =c.split(",");
for (String candid8 : myboard) {
try {
number.add(Integer.parseInt(candid8));
} catch (NumberFormatException e) {
}
}
}
}
Your numbers will now be in the number object, which is a List. If it's a more complex grammar, look into jflex, as that seems to be the recommendation of Google.

Categories