The overarching theme of this project is to sort stuff. My full code works (sort of) but the issue is that it always sorts my data as a String and I am pretty sure its caused by that fact that I am reading the dataFile's line as a String and inputting that into the array as a string.
Object[] list = new Object[n];
if (n > 0) {
try {
BufferedReader file = new BufferedReader(new FileReader("dataFile.txt"));
for (int i = 0; i < list.length; i++) {
String t = file.readLine();
if (t != null)
list[i] = t;
}
file.close();
}
catch (FileNotFoundException e) {
System.out.println("Error accessing file.");
} catch (IOException io) {
System.out.println("There was an error reading from the file.");
}
}
If someone could point me in the correct direction on how to read a line and input it into an array as an Object, I would be grateful.
A Java String is an Object. (String extends Object)
So you can get an Object reference via assignment!
Perhaps, you can try adding content from your file to an Object array like below:-
Object[] list = new Object[n];
if (n > 0) {
try {
BufferedReader file = new BufferedReader(new FileReader("dataFile.txt"));
for (int i = 0; i < list.length; i++) {
String t = file.readLine();
Object obj = t;
if (obj != null)
list[i] = obj;
}
file.close();
}
catch (FileNotFoundException e) {
System.out.println("Error accessing file.");
} catch (IOException io) {
System.out.println("There was an error reading from the file.");
}
}
Why don't you use Java8 internal tools to ready text files:
public static Object[] readAllLinesFromFile(Path path) throws IOException {
return Files.lines(path).toArray(String[]::new);
}
Figured out the issue. This code fixes, thanks to the people who helped.
void dataType() {
for (int i = 0; i < list.length; i++) {
try {
checkINT = Integer.parseInt((String) list[i]);
list[i] = checkINT;
} catch (Exception eInt) {
try {
checkDBL = Double.parseDouble((String) list[i]);
list[i] = checkDBL;
} catch (Exception eDbl) {
// Then its a string.
}
}
}
}
Related
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm parsing Outlook SCV file to ArrayList.
Then i want to get String values of the Array list i'm getting.
Here is the code:
if(arr != null){
try{
for (int i = 1; i < arr.size(); i++) {
oneRow = new ArrayList();
oneRow.add(arr.get(i));
for (int j = 0; j < oneRow.size(); j++) {
StringBuilder strBuild = new StringBuilder();
strBuild.append(String.valueOf(oneRow.get(j).toString()));
Here is the ArrayList:
No matter what i tried, i can't get the String Value.
What i get is : [Ljava.lang.string #....
Here is the Class that makes the ArrayList which getting the CSV file and building the ArrayList:
public class ReadingCSV {
InputStream inputStream;
public ReadingCSV(InputStream inputStream){
this.inputStream = inputStream;
}
public List read(){
ArrayList resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
Note :- This Code is compiled and run using jdk V1.8
try this out this is a working code. you can Manipulate as per your need.
public List<String> read(){
ArrayList<String> resultList = new ArrayList(); //A Type-Safety (String) ArrayList
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(","); //row is String Array Object
for(String eachWord : row) //Iterate each String from the array
resultList.add(eachWord); // add String to the Type-Safe ArrayList.
}
}catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
update Your another code with this
if(arr != null){
for (int i = 1; i < arr.size(); i++) {
ArrayList<String> oneRow = new ArrayList();
oneRow.add(arr.get(i));
for (int j = 0; j < oneRow.size(); j++) {
strBuild.append(oneRow.get(j));
}
}
System.out.println(strBuild.toString());
}
This Code is perfectly Working. You may try it by your own. If any issue you may put a comment .
Why are you double convert to String this:
strBuild.append(String.valueOf(oneRow.get(j).toString()));
I think,this is helps you:
Help link
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.
}
How to read an entire record from a txt file, get each field separately and convert each field into a separate character stream. Then write the character streams of individual characters (in a loop) to a plain ASCII output text file.
I have my class definition, I just cannot seem to write the output file properly which has to be one individual plain ascii text character at a time. I just need a little help. Here is what I have so far:
----- This is my first question guys. Sorry if it isn't formatted well :( I'm trying to covert a file of objects to a plain ASCII character text file which i called "yankees.txt" I read it in with the ObjectInputStream then I'm supposed to get each field separately and convert each field into a seperate character stream, and write the characters one character at a time from each field to my "yankees.txt"
public class yankeesfilemain {
public static void main(String[] args) throws EOFException {
ObjectInputStream is;
OutputStream os;
yankees y;
int i, j, k;
String name, pos;
int number;
File fout;
try {
is = new ObjectInputStream(new
FileInputStream("yankees.yanks"));
y = (yankees)is.readObject();
fout = new File("yankees.txt");
os = new FileOutputStream(fout);
while (y != null) {
name = y.getname();
pos = y.getpos();
number = y.getnum();
for (i = 0; i < .length(); i++) {}
for (j = 0; j < .length(); j++) {
pos = y.getpos();
}
for (k = 0; k < .length(); k++) {
number = y.getnum();
}
break;
}
os.close();
is.close();
} catch(EOFException eof) {
eof.printStackTrace();
System.exit(0);
} catch(NullPointerException npe) {
npe.printStackTrace();
System.exit(0);
} catch(NumberFormatException nfe) {
nfe.printStackTrace();
System.exit(0);
} catch(IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
Please refer to the following code
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream("C:\\11.txt");
OutputStream out = new FileOutputStream("C:\\12.txt", true);
try {
byte[] buffer = new byte[1024];
while (true) {
int byteRead = in.read(buffer);
if (byteRead == -1)
break;
out.write(buffer, 0, byteRead);
}
}
catch (MalformedURLException ex) {
System.err.println(args[0] + " is not a URL Java understands.");
} finally {
if (in != null)
in.close();
if (out != null) {
out.close();
}
}
}
I have the following method to write an array to a text file. If a existing text file is given then it works fine but if a file that doesn't exist is given neither try-catch will run the code to restart the method. I'm not given any error or anything but the catch block won't run. I didn't think i would need to catch for an IOException but the code won't even run if i don't do that. So yea, anyone know how i can get this to work?
Edit: Forgot to mention the getInput method prompts the user for input.
private static void openFileWriter(String prompt, boolean append, int wordsperline, String[] story) {
try {
try {
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length-1; x++) {
if (story[x] == null) {
} else {
if (wordsperline == 21) {
save.println(story[x]);
wordsperline = 0;
} else {
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
} catch (FileNotFoundException e1) {
openFileWriter("File not found", append,wordsperline,story);
}
} catch (IOException e) {
// TODO Auto-generated catch block
openFileWriter("File not found", append,wordsperline,story);
}
}
If the File does not exist you cannot write to it, in your catch block you are trying to write the error to the File that doesn't exist. Also, I think you only need 1 catch block here, and note that one of the if statement blocks is empty.
try this:
try
{
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for(int x = 0; x <= story.length-1; x++)
{
if (story[x] == null)
{
}
else
{
if (wordsperline == 21)
{
save.println(story[x]);
wordsperline = 0;
}
else
{
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
}
catch (FileNotFoundException e1)
{
System.err.println(e1.getMessage());
}
catch (IOException e)
{
System.err.println(e.getMessage());
}
See FileWriter javadoc.
Quoting from the constructor doc:
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
If you pass it a filename that doesn't exist, but is a legal filename in a location where you have permission to write, it simply creates the file.
Your code in fact does reach the catch blocks if you pass it a directory (somewhat oddly, it catches a FileNotFoundException in this situation for me rather than the documented IOException).
To check if a file exists, see File javadoc
Try this version and send the stack trace when you get the exception:
public static List<String> splitByLength(String filename, int length) {
List<String> splitWords = new ArrayList<String>();
for (int i = 0; i < str.length(); i += length) {
splitWords
.add(str.substring(i, Math.min(str.length(), i + length)));
}
return splitWords;
}
private static void openFileWriter(String prompt, boolean append,
int wordsperline, String[] story) {
PrintWriter save = null;
try {
save = new PrintWriter(new FileWriter("c:\\test.txt", append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length - 1; x++) {
if (story[x] != null) {
List<String> splitWords = splitByLength(story[x], 21);
for (String line : splitWords) {
save.println(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (save != null) {
save.close();
}
}
}