How can I change this to just array? - java

I have written this code but I have to change this from saving in list to saving in array. So that every animal in my txt file should have its position in the array. There is 10 animals. Anyone can help?
public class Main {
public static void main(String[] args) {
String line = "";
int count = 0;
List<String> arrayList = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
while (line != null) {
count++;
line = br.readLine();
if (line == null)
break;
if (count == 3 || count % 3 == 1 && !line.equals("1") &&
!line.equals("5") && !line.equals("10"));
arrayList.add(line);
}
System.out.println(Arrays.toString(arrayList.toArray()));
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found.");
}catch (IOException e) {
System.err.println("Cannot read this file.");
}
}
}

With Java8+, you could do :
Path path = Paths.get("Zoo.txt");
String[] animals = Files.lines(path, Charset.defaultCharset()).toArray(String[]::new);

Based on #Ryan suggestion :
public static void main(String[] args) {
// TODO Auto-generated method stub
String line = "";
int count = 0;
int countLineNumber=0; //to count line numbers
List<String> arrayList = new ArrayList();
try {
BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
while (line != null) {
count++;
line = br.readLine();
if (line == null)
break;
if (count == 3 || count % 3 == 1 && !line.equals("1") &&
!line.equals("5") && !line.equals("10"));
arrayList.add(line);
countLineNumber++;
}
//System.out.println(countLineNumber);
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found.");
}catch (IOException e) {
System.err.println("Cannot read this file.");
}
//getting elements from arayList saving them into a array
String[] array=new String[countLineNumber];
for(int i=0;i<countLineNumber;i++){
array[i]=arrayList.get(i);
}
//display element in array
for(int k=0;k<array.length;k++){
System.out.println(array[k]);
}
}

Related

How to assign each row of an arraylist to its own array

I am able to convert my csv file into an arraylist, but I want to be able to find the mean and standard deviation of each row in my arraylist. I would like to do this by converting each row to an individual array to be able to call for future use.
BufferedReader gradeBuffer = null;
try {
String gradeLine;
gradeBuffer = new BufferedReader(new FileReader("Assignment4-datafile.csv"));
// Read in file line by line
while ((gradeLine = gradeBuffer.readLine()) != null) {
System.out.println(gradeCSVtoArrayList(gradeLine));
}
//throw exception if file not found
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (gradeBuffer != null) gradeBuffer.close();
} catch (IOException gradeException) {
gradeException.printStackTrace();
}
}
}
// Convert CSV to ArrayList using Split
public static ArrayList<String> gradeCSVtoArrayList(String gradeCSV) {
ArrayList<String> gradeResult = new ArrayList<String>();
if (gradeCSV != null) {
String[] splitData = gradeCSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
gradeResult.add(splitData[i].trim());
}
}
}
return gradeResult;
}
}
I think the first thing that you need to do is change gradeCSVtoArrayList to return a List of numbers, either Long or Double depending on if it is integer or floating point numbers.
public static ArrayList<Long> gradeCSVtoArrayList(String gradeCSV) {
ArrayList<Long> gradeResult = new ArrayList<Long>();
if (gradeCSV != null) {
String[] splitData = gradeCSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
gradeResult.add(Long.parseLong(splitData[i].trim()));
}
}
}
return gradeResult;
}
WIth this list you can find mean and standard deviation.

Creating file and writing to it (null pointer)

I want to create a method that reads from a file, then creates a file which will then write a certain subset of what was read from but I keep getting a null pointer exception at output.write(line) and I am not sure why?
public void readCreateThenWriteTo(String file, String startRowCount, String totalRowCount) {
BufferedReader br = null;
File newFile = null;
BufferedWriter output = null;
StringBuilder sb = null;
int startRowCountInt = Integer.parseInt(startRowCount);
int totalRowCountInt = Integer.parseInt(totalRowCount);
try {
br = new BufferedReader(new FileReader(file));
sb = new StringBuilder();
newFile = new File("hiya.txt");
output = new BufferedWriter(new FileWriter(newFile));
String line = "";
int counter = 0;
while (line != null) {
line = br.readLine();
if (startRowCountInt <= counter && counter <= totalRowCountInt) {
System.out.println(line);
output.write(line);
}
counter++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info("File was not found.");
e.printStackTrace();
} finally {
// Should update to Java 7 in order to use try with resources and then this whole finally block can be removed.
try {
if ( br != null ) {
br.close();
}
if ( output != null ) {
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info("Couldn't close BufferReader.");
e.printStackTrace();
}
}
}
You need to check the result of readLine() before you enter the loop:
while ((line = br.readLine()) != null) {
if (startRowCountInt <= counter && counter <= totalRowCountInt) {
System.out.println(line);
output.write(line);
}
counter++;
}

How do I skip lines when I'm reading from a text file?

I'm reading from a text file which looks like this:
1
The Adventures of Tom Sawyer
2
Huckleberry Finn
4
The Sword in the Stone
6
Stuart Little
I have to make it so that the user can enter the reference number and the program will perform binary and linear search and output the title. My teacher said to use two ArrayLists, one for the numbers and one for the titles, and output from them. I just can't figure out how to skip lines so I can add to the corresponding arraylist.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Thanks in advance, I appreciate any help!
You can check if you are in even or odd lines by doing a modulo 2 operation on the line number:
try (BufferedReader br = new BufferedReader(new FileReader("bookList.txt"))) {
String word;
int lineCount = 0;
while ((word = br.readLine()) != null ){
if (++lineCount % 2 == 0) {
numbers.add(Integer.parseInt(word));
} else {
books.add(word);
}
}
} catch (IOException e) {
e.printStackTrace();
}
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
numbers.add(Integer.valueOf(word));
word = br.readLine()
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
You could make check to see if it is actually a integer, that you read from the file. As far as I remember, there is no built in method to do this, but you can define your own as:
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Then just make a check to see if the line you have read in is a integer or not.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
if (tryParseInt(word))
numbers.add(Integer.parseInt(word))
else
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Hope this help!

Reverse Java full document

I used reverse a string, but now need the final document is the principle, and vice versa:
Hello
Bye
to
Bye
hello
and not:
olleH
eyB
As I do this?
This is my source:
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero");
System.exit(1);
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(args[0]));
String s;
try {
while ((s = br.readLine()) != null) {
StringBuilder reverse = new StringBuilder(s);
String sCadenaInvertida = reverse.reverse().toString();
System.out.println(sCadenaInvertida);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Thanks!!
Just put everything in an ArrayList and use Collections.reverse
http://www.java2s.com/Code/Java/Collections-Data-Structure/ReverseorderofallelementsofJavaArrayList.htm
pseudo code:
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("Bye");
Collections.reverse(arrayList);
System.out.println(arrayList);
Add the items to an array (first come first serve) then traverse the array in reverse
for (into I = array.length; i >= 0; i--) {
//print array[i]
}
Alternatively you can use an ArrayList if you don't know the number of lines in the document
ArrayList<String> theWords= new ArrayList<String>();
while ((s = br.readLine()) != null) {
//split line into words
String[] parts = s.split("\\s+"):
//for each word append to arraylist
for(String s : parts)
{
theWords.append(s);
} //end for loop
} //end while loop
// iterate array, from size-1 to 0
int theWordsSize = theWords.size()--;
for(int i= theWordsSize; i >= 0; i--)
{
System.out.println(theWords.get(i));
} //end for loop
here the answer, It was easy:
public class Reverse2 {
public static void main(String[] args) {
if(args.length != 1){
System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero");
System.exit(1);
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(args[0]));
ArrayList<String> lista = new ArrayList<String>();
String s;
try {
while((s=br.readLine()) != null){
lista.add(s);
}
for(int i= lista.size()-1;i>=0;i--){
System.out.println(lista.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
thanks for all the possible solutions

Java NumberFormatException Skip Line

I'm writing a program that reads in a list of numbers. Such as:
45
63
74g
34.7
75
I simply want my program to skip lines that contain any letters in them. Any help would be greatly appreciated. Thanks!
If it makes a difference, here is my code:
import java.io.*;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
int num = Integer.parseInt(nums[i]);
if (num != -1) {
sum += num;
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
catch (NumberFormatException err) {
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
When an exception is thrown, execution jumps to the catch block. In what you have, this is after the loop, so the loop doesn't continue, just add a try around parseInt.
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
try{
int num = Integer.parseInt(nums[i]);
if (num != -1) {
sum += num;
}
} catch( NumberFormatException nfe )
{
// maybe log it?
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
// catch (NumberFormatException err) {}
finally {
try {
if (reader != null){
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
Also note, you are using Integer.parseInt which will throw an exception with the input "34.7", so maybe you wish to use Double.parseDouble
How about using a regex? Like for example:
if (currentLine.matches(".*[a-zA-Z].*")) {
//letters contained.
} else {
//no letters contained.
}
see regex demo: http://regex101.com/r/rQ6oR1
you can try this :
import java.io.*;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
if (isInt(num)) {
sum += num;
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
public boolean isInt(String num)
{
boolean flag=false;
try
{
int i=Integer.parseInt(num);
flag=true;
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
return flag;
}
}
Based on your comment. if your file contain one number per line . then this would be easiest way.
Scanner sc = new Scanner(new File("QuizScores.txt"));
int sum = 0;
int count =0;
while( sc.hasNext()){
String tmpNum = sc.next();
if (isNumeric(tmpNum)){
sum = sum + (int) Double.parseDouble(tmpNum); // if you want t capture in double use Double instead.
count++;
}
}
System.out.println(sum/count);
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}

Categories

Resources