Changing a String into an int - java

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.

Related

Trouble Sorting an array list

Is there a better way to sort this, to get the correct order? Thanks
import java.io.*;
import java.util.*;
public class JpgDirToHtm
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter the path of the folder whose contents you wish to insert into an html file: ");
String path = kb.nextLine();
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
ArrayList<String> htmlTextList = new ArrayList<String>();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
htmlTextList.add(listOfFiles[i].getName() );
}
}
Collections.sort(htmlTextList);
System.out.println(htmlTextList);
}
}
This is what it prints
[1.jpeg, 10.jpg, 11.jpeg, 12.jpeg, 13.jpeg, 14.jpeg, 16.jpg, 17.jpg, 18.jpg, 19.jpg, 2.jpeg, 20.jpg, 21.jpg, 22.jpg, 23.jpg, 24.jpg, 25.jpg, 3.jpg, 5.jpg, 7.jpeg, 9.jpg]
I need 2.jpeg to come after 1.jpeg et cetera.
Sorry, there is probably a simple fix but I haven't found anything on google. I am new to programming.
Everything else works really well. The whole program can take thousands of photos and automatically place them, sized correctly, in html web pages at a given number of photos per page that you can set. If any one is interested in having the rest of the code I will post it.
Write your own comparator:
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
String filename1 =o1.substring(0,o1.indexOf("."));
String filename2 =o2.substring(0,o2.indexOf("."));
return Integer.valueOf(filename1).compareTo(Integer.valueOf(filename2));
}
});
This will convert the filename to an integer and compare it.
But take care, it only works if your filenames are numbers!
You would have to write your own comparator and take care of the scenario of the flie starting with a number or a string:
public class JpgDirToHtm
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter the path of the folder whose contents you wish to insert into an html file: ");
String path = kb.nextLine();
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
ArrayList<String> htmlTextList = new ArrayList<String>();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
htmlTextList.add(listOfFiles[i].getName() );
}
}
Collections.sort(htmlTextList, new Sortbyname());
System.out.println(htmlTextList);
}
}
class Sortbyname implements Comparator<String>
{
// Used for sorting in ascending order of
// roll name
public int compare(String a, String b)
{
String tempA = a.split("\\.")[0];
String tempB = b.split("\\.")[0];
try
{
return Integer.parseInt(tempA)-Integer.parseInt(tempB);
}
catch (Exception e)
{
return a.compareTo(b);
}
}
}
The code catches any exceptions with formatting the number and just falls back to String compare.

Read strings from .txt file to and put contents into a 2d array

Hi, so I am supposed to read the lines from a text file, and output
the data into a 2D array, I have read the lines but I am confused as
to how to input the contents to the 2D array.
This is the file :
eoksibaebl
ropeneapop
mbrflaoyrm
gciarrauna
utmorapply
wnarmupnke
ngrelclene
alytueyuei
fgrammarib
tdcebykxka
My problem is how do I put these strings into the the 2d array as shown below.
public class WordFinder {
public static final int N = 10;
public static char[][] grid = new char[N][N];
public static final String GRID_FILE = "grid.txt";
public static void initGrid() {
try {
File file = new File(GRID_FILE);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
I am quite new to JAVA, so any help would be much appriciated!
Here's a quick modification to your code to make it work. Read a line as a string, then iterate over the characters in the string and place them in the char[][] array.
import java.util.*;
import java.io.*;
public class WordFinder {
public static final int N = 10;
public static char[][] grid = new char[N][N];
public static final String GRID_FILE = "grid.txt";
public static void initGrid() {
try {
File file = new File(GRID_FILE);
Scanner scanner = new Scanner(file);
for (int i = 0; scanner.hasNext(); i++) {
String line = scanner.next();
for (int j = 0; j < N; j++) {
grid[i][j] = line.charAt(j);
}
}
scanner.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
public static void main(String[] args) {
initGrid();
for (char[] row : grid) {
for (char cell : row) {
System.out.print(cell);
}
System.out.println();
}
}
}
Output:
eoksibaebl
ropeneapop
mbrflaoyrm
gciarrauna
utmorapply
wnarmupnke
ngrelclene
alytueyuei
fgrammarib
tdcebykxka
Careful, though: this design can crash on input files that are something other than a 10x10 grid of chars. Consider using an ArrayList to dynamically match the size of your text file, or at least you may add to your error handling:
catch (FileNotFoundException | ArrayIndexOutOfBoundsException e) {
System.out.println("Something terrible happened.");
System.exit(1);
}

Issue with scanner in main method vs in constructor java?

SOLVED
I'm having an issue using Scanners nextInt() method in a class constructor.
it works fine if used in a main method like the code below however when doing the same thing in a constructor I get an inputmismatchexception,
what could be the possible issues?
public class QuickTest{
public static void main(String[] args) throws Exception{
java.io.File myFile = new java.io.File("tograph.txt");
java.util.Scanner input = new java.util.Scanner(myFile);
int numberOfPoints = input.nextInt();
String[] myArray = new String[numberOfPoints];
//need to use nextLine once after reading in number of points to get to next line
input.nextLine();
int count = 0;
while(input.hasNext() == true){
myArray[count] = input.nextLine();
count++;
}
input.close();
for(int i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
the class version
public class MyGraph{
//filled with strings from file
String[] points;
java.io.File file;
java.util.Scanner input;
//length of points array
int numPoints;
public MyGraph(String file){
this.file = new java.io.File(file);
this.input = new java.util.Scanner(file);
this.numPoints = this.input.nextInt();
this.points = new String[this.numPoints];
fillGraphArray();
}
//after getting the number of vertices we populate the array with every
//line after those points untill the end
private void fillGraphArray(){
//used once after reading nextInt()
this.input.nextLine();
int count = 0;
while(this.input.hasNext() == true){
points[count] = input.nextLine();
count++;
}
input.close();
}
//test method to be delted later
public String[] getPoints(){
return this.points;
}
//may need a method to close the file
}
When I use the debugger the main method version will get the number of points from the file and then fill the array with a string from each following line in the file however the class version throws the exception

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).

Creating array from reading a file

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);
}
}

Categories