cat a textfile into standard input resulting null in array? - java

I'm cating a file using the cat text-file | Java my-program on my terminal
the result when I print the lines after i store it into a array results in null
can someone explain why?
Scanner scan2 = new Scanner(System.in);
Scanner scan = new Scanner(System.in);//create new scanner object
int index = 0;//create index to increment through array
while(scan.hasNextLine()){//while looop to execute if file has length
String line = scan.nextLine();//store line into string input
count++;
}
if(count < BUFSIZE){
stringArray = new String[count];
}
else{
stringArray = new String[BUFSIZE];
}
while(scan2.hasNextLine()){
String line2 = scan2.nextLine();
if(index > stringArray.length-1)
{
stringArray = expandArray(stringArray,BUFSIZE);//call method to increase array length
}
stringArray[index] = line2;//store line into array at given index
index++;//increment index
}
/*while(sorted){
sorted = false;
for(int i = 0; i < stringArray.length-1; i++){
if(stringArray[i].compareTo(stringArray[i+1]) > 0){
temp = stringArray[i];
stringArray[i] = stringArray[i+1];
stringArray[i+1] = temp;
sorted = true;
}
}
}*/
for(int i = 0; i < stringArray.length; i++){
System.out.println(stringArray[i]);
}
}
}
private static String [] expandArray(String [] array, int extend){
String newArray [] = new String[array.length+extend];//create new array with given array and int as length to extend
//for loop to copy data from old array into new created array
for( int i = 0; i < array.length; i++){
newArray[i] = array[i];
}
return newArray;//return newly created array
}
}
the program bubble sorts the array of strings. If I read in the file through Scanner file its fine, but why I cat it doesn't. The expand array method is to dynamically expand the array every-time it reaches max capacity. Thank you

The following is wrong:
Scanner scan2 = new Scanner(System.in);
Scanner scan = new Scanner(System.in);//create new scanner object
Basically, each scanner grabs the System.in stream, but streams can only be read once. You should change your code to use only one scanner, and then only use it once.
When you wrote the program to use a file, the Scanner would actually open two streams to the file so that it can be read twice, but this won't work when all you have is one stream.
EDIT:
Here is a version where you use only one Scanner (and thus one stream) :
Scanner scan = new Scanner(System.in);//create new scanner object
int count = 0;
stringArray = new String[BUFSIZE];
while (scan.hasNextLine()){//while looop to execute if file has length
String line = scan.nextLine();//store line into string input
if (count >= stringArray.length) {
//call method to double array length
stringArray = expandArray(stringArray, stringArray.length);
}
stringArray[count] = line;
count++;
}
// Shrink array to required size
String[] temp = stringArray;
stringArray = new String[count];
System.arraycopy(temp, 0, stringArray, 0, count);
Please note I didn't test it, but this is conceptually how you could do it.
The other alternative is to use an ArrayList<String> which will automatically expand and shrink.

Scanner scan = new Scanner(System.in);
List<String> list = new LinkedList<>();
while(scan.hasNext()) list.add(scan.next());
scan.close();
Collections.sort(list);
for(String line : list) System.out.println(line);
lol
UPDATE #JBert:
System.out.println(StringUtils.join(Ordering.<String>natural().sortedCopy(IOUtils.readLines(System.in)), "\r\n"));
looool

In this code
while(scan2.hasNextLine()){
String line2 = scan2.nextLine();
if(index > stringArray.length-1)
you are doing something if index is greater than the length of the array, but no doing anything otherwise.

Related

Java compiles with no errors, runs first line, then doesn't continue or end

I am working on a project for my intro to java class and I can't get it to continue. The first part of the project is supposed to use a method to read a file and turn it into an array, then retrieve that array in the main method. It compiled with no errors, but when I run it, it prompts the user for the file name and when you type it and press enter it just sits there. It does not end the program but it also doesn't continue. Am I doing something wrong?
Here is the method that reads the file and creates the array:
public static int[] inputData() throws IOException
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter input filename: ");
String fileName = kb.nextLine();
File file = new File(fileName);
if(!file.exists())
{
System.out.println("File not found.");
System.exit(0);
}
Scanner inFile = new Scanner(file);
int size = 0;
while(inFile.hasNext())
{
size++;
}
int[] array = new int[size];
while(inFile.hasNext())
{
for(int i = 0; i < size; i++)
{
array[i] = inFile.nextInt();
}
}
inFile.close();
return array;
}
and here is the main method:
public static void main(String[] args) throws IOException
{
int[] array = inputData();
int length = array.length;
System.out.println("Original array: ");
printArray(array, length);
System.out.println();
System.out.print("The first element out of order is at index "
+ outOfOrder(array));
System.out.println(".");
System.out.println("Reversed array: ");
reverseArray(array);
System.out.println("Sorted array in descending order: ");
selectionSort(array);
System.out.println("Delete repeats: ");
deleteRepeats(array);
}
I am very new to java so I apologize if this is an obvious error. Please help, thank you!
Loop in your code will never complete as you are not using inFile.next() inside the loop.
while(inFile.hasNext()){
size++;
}
Remove the two while cycles and add this:
int[] array = new int[1];
int index= 0;
while (inFile.hasNext()) {
array[index] = inFile.nextInt();
if(inFile.hasNext()) {
index++;
int[] array2 = new int[array.length + 1];
for (int i = 0; i<array.length;i++) {
array2[i] = array[i];
}
array = array2;
}
}
This code will increase the size of array[] for each next element.

Making an array out of doubles from a text file

I need to read a file of grades and input them into an array. I cant seem to figure it out though. Any suggestions. Thanks for your help :)
The grades.txt file looks like this:
90.0
71.5
87.9
95.0
98.1
Code:
File file1 = new File("grades.txt");
Scanner gradesFile = new Scanner(file1);
String line = gradesFile.nextLine();
//create array
double[] array = new double[12];
//variable to increment
int u = 0;
//loop to put data into array
while(gradesFile.hasNextDouble())
array[u] = gradesFile.nextDouble();
u += 1;
gradesFile.close();
A. As #hnefatl said you need to group statements in the loop,
while(<condition>) {
statement1;
...
statementN;
}
otherwise only next one executes.
while(<condition>) statement1;
...
B. When you did String line = gradesFile.nextLine();
you got full first line from file and Scanner position is at next line if there is any.
So by doing gradesFile.hasNextDouble() after that, Scaner looks for double in next line.
If you'd like to use nextLine() and your doubles are "one-per-line" you need to work with them in a loop as:
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextLine()) {
String line = gradesFile.nextLine();
array[u] = Double.parseDouble(line);
u += 1;
}
gradesFile.close();
or if you'd like to use nextDouble() you do not mix it with nextLine()
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextDouble()) {
array[u] = gradesFile.nextDouble();
u++;
}
gradesFile.close();
You can simply scan the double value in your file and store in the array as below
Scanner scan;
//Data file
File file = new File(grades.txt");
//Array to store the double read from file
double[] array = new double[10];
int i =0;
try {
scan = new Scanner(file);
//Scan while the file has next double value
while(scan.hasNextDouble())
{
//Save the double value read from text file and store to array
array[i] = scan.nextDouble();
i++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
To print what you have stored in your array
for(int y = 0; y < array.length;y++)
{
System.out.println(array[y]);
}

Filling a 2d character array from a file in java

I'm a beginner in java and I am trying to fill a 2d character array from an input file. To do this I constructed a method which takes in a 2d character array as a parameter variable, then reads the file and stores it as a character array. So far I have done everything except fill the array, as when I run the code the program throws a NoSuchElement exception. If anyone could help me with this I would greatly appreciate it.
public static char [][] MakeWordArray (char [][] givenArray)
{
try
{
File wordFile= new File ("words.txt");
Scanner in= new Scanner (wordFile);
int rows =0;
int col=0;
while (in.hasNextLine())
{
rows = rows + 1;
col = col + 1;
in.next();
}
char [][] words = new char [rows][col];
File wordFile2= new File ("words.txt");
Scanner in2= new Scanner(wordFile2);
for ( int i = 0; i < rows; i++)
{
for (int j = 0; j < col; j++)
{
String wordly = in2.nextLine();
words [i][j] = wordly.charAt(i);
}
}
return words;
}
catch (FileNotFoundException e)
{
System.out.println("File Does Not Exist");
}
return null;
}
I think your counting methods have some problems.
If you want to count how many lines your .txt have:
int counter = 0;
while (in.hasNextLine())
{
counter++;
in.nextLine();
}
If you want to count how many char your .txt have:
int counterWithoutSpace = 0, counterWithSpace = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
while (inLine.hasNext())
{
String nextWord = inLine.next();
counterWithoutSpace += nextWord.length();
counterWithSpace += nextWord.length() + 1;
}
counterWithSpace--;
}
If you want to count how many char you have on each line, I recommend ArrayList. Because the size of your array is dynamic.
Note that you can also you can use the char counter logic above with List too.See as follows:
List<Integer> arr = new ArrayList<Integer>();
while (in.hasNextLine())
{
arr.add(in.nextLine().length());
}
And if you realy needs the static array, you can use:
Integer[] intArr = arr.toArray(new Integer[0]);
You can transform its entire function as below to get a list of every Character of the .txt:
List<Character> arr = new ArrayList<Character>();
while (in.hasNextLine())
{
String line = in.nextLine();
for (char c : line.toCharArray())
{
arr.add(c);
}
}
Try using a do while loop instead of the while
do
{
rows=rows+1;
col=lol+1;
in.next();
}
while(in.hasNext());
There are multiple questions here.
1) Why did you provide a char[][] parameter when you are not even using it?
2) Why are you using two files when all you need to do is read from a file and convert it in 2d Array?
3) The method name should follow camel casing convention.
From what i understood from your question, This is a code i've tried.
NOTE- because the requirement is of an Array and not dynamic datatypes like List ArrayList etc., the data entered into char array might be lost
Saying that here is what works.
public class StackOverflow{
public static char [][] makeWordArray ()
{
try{
File f = new File("C:\\docs\\mytextfile.txt");
Scanner scan = new Scanner(f);
int row = 0, col = 0;
String readData = "";
while(scan.hasNextLine()){
readData += scan.nextLine();
row++;
}
double range = (readData.length()/row);
col = (int)Math.ceil(range);
char[][] arr = new char[row][col];
int count = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
arr[i][j] = readData.charAt(count++);
System.out.println("Pos: ["+ i +"][" + j + "]" + arr[i][j]);
}
}
return arr;
}
catch(FileNotFoundException fe){
System.err.println(fe.getMessage());
return null;
}
}
public static void main(String[] arg){
char[][] myarr = StackOverflow.makeWordArray();
//print your array
}
}

Using String Array and Printfile Output getting NullPointerException?

So, I'm writing a program in which I need to have a loop that "reads and writes the first character of the strings stored in each element of the array to the output file".
I keep getting a NullPointerException at: a = planets[i].charAt(0);
String[] planets = new String[8];
char a = 'a';
String pl = "planets.txt";
File file = new File(pl);
Scanner inputFile = new Scanner(file);
for(int i = 0; i < planets.length; i++){
while(inputFile.hasNext()){
planets[i] = inputFile.nextLine();
}
}
inputFile.close();
System.out.println("closed.");
String b = "planetfirst.txt";
PrintWriter outputFile = new PrintWriter(b);
for (int i = 0; i< planets.length; i++){
a = planets[i].charAt(0);
outputFile.println(a);
}
outputFile.close();
System.out.println("Data written to the file.");
Thanks in advance!
edit:
I added the rest of my program for some context :)
Your while loop is inside your for loop, so all the text will be inside planets[0], and the rest of the indices will be empty (i.e null). When you later iterate through the array with
for(int i = 0; i < planets.length; i++) {
a = planets[i].charAt(0);
}
you will get a NullPointerException when i is larger than 0.
If your textfile has 8 lines, then there is no need for the while-loop, because you have a for loop that iterates 8 times, and an array of length 8.
If the number of lines in your textfile varies, however, you shouldn't use an array, and instead use an arraylist, and instead of a for loop, only have your while loop.
Something like
List<String> planets = new ArrayList<String>();
while(inputFile.hasNext()){
planets.add(inputFile.nextLine());
}

Create a string array with length determined by user input

I am trying to create an array that reads string tokens from standard input, and places them in an array, and then prints the words out, until it reaches a specific word. For example, let's say I wanted my array to read a series of words until it reached the word "okay" from std in, print out each word, and then terminate before printing out "okay". The length of this array will be unknown, so I am confused on how to do this.
String s = sc.next();
String[] copy = new String[???];
for( int i = 0; i < copy.length; i++ ){
copy[i] = sc.next();
}
Something like:
String s = sc.next();
ArrayList<String> copy = new ArrayList<String>();
while(!s.equals("okay")){
copy.add(s);
s = sc.next();
}
for (String n : copy){
System.out.println(n);
}
If you don't want to use any list at all, then this becomes impossible. This is simply because array size needs to be defined at the time the array object is created.
So with this constraint you can have a large integer and declare an array of that size.
Final int MY_LARGE_CONST = 3000;
...
String[] tokens = new String[MY_LARGE_CONST]...
This is wasteful since it takes more memory and will fail if you have more tokens than the constant.
Alternaely if you are ok with lists and not ok with iterating over that for actual processing, then u can put the tokens in an ArrayList and once they are all collected, call the toArray method on the ArrayList object.
It's my code Without using ArrayList.
import java.util.Scanner;
import java.util.StringTokenizer;
public class Sample {
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
String line = sc.nextLine();
StringTokenizer st = new StringTokenizer(line);
int len = st.countTokens();
String[] array = new String[len];
for (int idx = 0; idx < len; idx++) {
array[idx] = st.nextToken();
}
for (String str: array) {
System.out.println(str);
}
}
}

Categories

Resources