Why can't I read Strings from a file? - java

The code is supposed to read an array of strings from a file then print it out. I'm not sure what is wrong with the code.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class program2 {
public static void main(String[] args) throws IOException {
//PriorityQueue<String> q = new PriorityQueue<String>();
//file that contains strings
File file = new File("infix.txt");
Scanner scnf = new Scanner(file);
// array count
int arycnt = 0;
// gets the count of the array in the file
while(scnf.hasNextLine()){
arycnt++;
scnf.next();
}
// creates array
String[] letter = new String[arycnt];
//reads in array from file
Scanner scnf2 = new Scanner(file);
for(int i = 0; i<arycnt ;i++){
letter[i] = scnf2.next();
}
// suppose to print all of the array
for (int i = 0;i < letter.length;i++){
System.out.println(letter[i]);
}
}
}

You are mixing up between nextLine and next. Replace your hasNextLine() with hasNext() and you should be OK.

Related

How would I separate one value of an array (for the entire array) into alphabetic and numeric characters, and then into separate arrays? (Java)

I've been struggling to find an answer to my specific problem here. I understand that I can use regex to separate array values, but they both don't seem to work and I can't figure out how to get the two values separately. Thanks!
Here's my code without any separation of arr:
package boomaa;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.lang.*;
public class Solution{
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("A.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
System.out.println(Arrays.toString(arr));
for (int i = 1;i<arr.length;i++) {
System.out.println(arr[i]);
}
}
}
My input is formatted like this:
3
1 CS
2 CS
1 SS
If the numbers and characters are separated by a space, simply iterate over the array and use the String method split to split at the space.
Scanner sc = new Scanner(new File("A.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] numbers = new String[lines.size()];
String[] characters = new String[lines.size()];
for (int i = 0; i < lines.size(); i++) {
String[] components = lines.get(i).split(" ");
numbers[i] = components[0];
characters[i] = components[1];
}

what wrong with my code always print answer : null+word,what is null?

We have file with a few words, try safe word with word have 2,4,6 or 8 letters in array but then save in screen write null and null+good word.
What did I write wrong, and why does it show null?
public static void lyginis () throws IOException {
Path path = Paths.get("words.txt");
Scanner scanner = new Scanner(path);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner1 = new Scanner(path);
String[] atrinkti = new String[kiek];
String scan = "";
for (int i = 0; i < kiek; i++) {
scan = scanner1.next();
if (scan.length() % 2 == 0) {
atrinkti[i] += scan ;
}
System.out.println(atrinkti[i]);
}
}
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) throws IOException {
File file = new File("words.txt");
Scanner scanner = new Scanner(file);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner2 = new Scanner(file);
String[] atrinkti = new String[kiek];
String word = "";
for (int i = 0; i < kiek; i++) {
word = scanner2.next();
if (word.length() % 2 == 0) {
atrinkti[i] = word;
System.out.println(atrinkti[i]);
}
}
}
}
Output
$ cat words.txt
hi
hello
whats up
chicken
duck
goose
$ javac Hello.java; java Hello
hi
up
duck
The issues were:
Path was used instead of File
The += was used within the if statement instead of just =
The System.out.println() function was called outside of the if statement so when the word's length was not divisible by 2, the current array element would print the default initialized value of the array of null

Inputting a sorted file, unsorting it, then outputting the unsorted file (Java)

This project is supposed to have 3 separate main classes.
It inputs a file of a list of countries that is sorted alphabetically, it outputs an unsorted file with lines rearranged randomly.
My first main class looks like this:
package assignment3;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
public class Assignment3 {`
public static void main(String[] args) throws Exception{
Scanner stdIn = new Scanner(new File("C:/Users/Vicki/Desktop/CountrySortedFormat.txt"));
PrintWriter out = new PrintWriter("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt");
String[] line = new String[238];
while (stdIn.hasNextLine()){
for (int k = 0; k <= line.length-1; k++){
line[k]=stdIn.nextLine();
out.println(line[k]);
out.close();
}
}
}
}
My code doesn't have any visible problems but I tried printing out the array and got an array of "null". Am I doing something wrong?
EDIT: changed PrintWriter file name to CountryUnsortedFormat
That line:
PrintWriter out = new PrintWriter("C:/Users/Vicki/Desktop/CountrySortedFormat.txt");
recreates the file. After this line your input file will be empty.
Beside what #Jens says you have this problems too :
There multiple problem with your code. first of all, you have this line:
while (stdIn.hasNextLine())
so why there is this line?
for (int k = 0; k <= line.length-1; k++)
you have a loop already, and you dont need the second loop.
Also you close the output in every loop! What is that?
out.close();
you just need to close it in the end of the function!
your loop should be something like this :
int k = 0;
while (stdIn.hasNextLine()) {
// for (int k = 0; k <= line.length - 1; k++) {
line[k] = stdIn.nextLine();
out.println(line[k]);
k++;
// }
}
out.close();
Also after something like this your output is sorted, you didnt do any thing to make output unsorted.
while (stdIn.hasNextLine()) {
// for (int k = 0; k <= line.length - 1; k++) {
String str = stdIn.nextLine();
out.println(str);
// out.close(); --> here you are closing the out put writer so after first line it will be closed.
// }
}
Close scanner and printwriter outside the loop. otherwise after first line it will the writer will be closed and only first line will be printed.
As pointed out by #Ali there are multiple flaws in your code. Also there is no logic for unsorting the input.
Your unsorting will become easier with use of ArrayList instead of normal array.
Here is a sample code which might serve your purpose.
import java.io.PrintWriter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) throws Exception{
Scanner stdIn = new Scanner(new File("sortedInput.txt"));
PrintWriter out = new PrintWriter("unsortedOutput.txt");
ArrayList<String> line = new ArrayList<String>();
System.out.println(stdIn.hasNextLine());
while (stdIn.hasNextLine()){
line.add(stdIn.nextLine());
}
//here is your unsorting
Collections.shuffle(line);
for(int i=0; i < line.size() ; i++)
out.println(line.get(i));
//Close printwriter once you are done writing everything
out.close();
}
}

read csv file into 2d array

CSV File:
515.30,516.81
516.81,514.27
516.74,517.68
517.54,516.72
517.61,517.64
517.22,516.99
517.21,517.33
516.99,516.92
516.96,517.5
517.38,516.91
No blank lines in between.
My program so far:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class CSVRead
{
public static void main(String arg[]) throws Exception
{
double[][] test = new double[9][2];
String[] testStr = new String[19];
String delimiter = ",";
Scanner sc = new Scanner("kort.csv");
while (sc.hasNextLine())
{
String line = sc.nextLine();
testStr = line.split(delimiter);
}
for (int i=0; i<10; i++)
{
for (int j=0; j<2; j++)
{
test[i][j] = Double.parseDouble(testStr[2*i+j]);
}
}
for (int y=0; y<10; y++)
{
for (int x=0; x<2; x++)
{
System.out.print(test[y][x] +" ");
}
}
} //main()
} // CSVRead
Exception in thread "main" java.lang.NumberFormatException: For input string: "AEX2008kort.csv"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at CSVRead.main(CSVRead.java:26)
Java Result: 1
Change to
Scanner sc = new Scanner(new File("kort.csv"));
You want to parse the content of the file, not the String "kort.csv"
After you have done what Alex mentioned, you need to change the way testStr is being used. In your current code, testStr will always have the last line elements (517.38 and 516.91). What you probably want to do is to store the Double numbers in a List perhaps,
List<Double> mynumbers = new ArrayList<Double> ();
and use it later on to populate your 2D array. Once you have split the line into testStr, you should add these numbers to the list,
mynumbers.add(testStr[0]);
mynumbers.add(testStr[1]);
Finally, in the parseDouble method, instead of passing testStr you should pass your list:
mynumbers.get(index_you_want);

Cannot find number of lines in a file using Scanner

I am trying to calculate the number of lines in a file using a Scanner in the below code but for some reason I am stuck in an infinite loop.
import java.util.*;
import java.io.*;
public class FileCount{
File fileCount;
public FileCount(String name_of_file){
fileCount = new File(name_of_file);
}
public static void main(String args[]) throws FileNotFoundException{
FileCount f = new FileCount("test.txt");
System.out.println(f.num_of_records());
}
public int num_of_records() throws FileNotFoundException{
Scanner handler = new Scanner(this.fileCount);
int num_of_lines = 0;
for(int i=0; handler.hasNextLine(); i++){
num_of_lines = i;
}
handler.close();
return num_of_lines;
}
}
You check that it has a next line, but then you never tell it to do anything with that line. Something like this should work.
for(int i=0; handler.hasNextLine(); i++){
handler.nextLine();
num_of_lines = i;
}
As an alternative to Scanner, you may consider using BufferedReader instead:
BufferedReader reader = new BufferedReader(new FileReader("your_file_name"));
int num_of_lines;
for (num_of_lines=0; reader.readLine()!=null; num_of_lines++) {}
You don't need a Scanner or a BufferedReader either. You can do it in about three lines with a LineNumberReader. First seek to the file size, then get the current line number.

Categories

Resources