hasNextLine() always returns false - java

I'm trying to make a spell checker and going to open the words in .txt file in a linked list but hasNextLine() always returns false.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.Scanner;
public class backEnd {
String string;
String[] splitted;
public backEnd(String s){
string=s;
}
public void splitter(){
splitted =string.split(" ");
for (int x=0; x<splitted.length; x++){
System.out.println(splitted[x]);
}
}
public void spellChecker(){
Serializable data = new String[100];
LinkedList<String> l=new LinkedList<String>();
File f= new File("WordDict.txt");
if(!f.exists())
try {
f.createNewFile();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream Fis=new FileInputStream(f);
Scanner sc = new Scanner(Fis);
System.out.println("Check outside nextline");
this is the point where it should take words line by line from .txt file but it always breaks the loop.
while (sc.hasNextLine()){
System.out.println("Check in nextline");
data = sc.nextLine();
l.add( (String) data);
}
sc.close();
}
catch(FileNotFoundException fnf){
fnf.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y)==splitted[x]){
System.out.println("Matched.");
y++;
}`enter code here`
}
System.out.println("Wrong spelling of: "+splitted[x]);
x++;
}
}
}

The obvious reason seems to be that the file WordDict.txt doesn't exist,
so your code creates it, but it's empty, so it has no next line.
In this code, put a breakpoint on f.createNewFile():
File f= new File("WordDict.txt");
if(!f.exists())
try {
f.createNewFile();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream Fis=new FileInputStream(f);
Scanner sc = new Scanner(Fis);
System.out.println("Check outside nextline");
Another obvious reason can be that the file exists but it's empty.
Most probably your problem is the first one, and your confusion comes from your assumption of the execution directory. That is, the program is probably not executed where you think. To verify what, change WordDict.txt to absolute path.

sc.hasNextLine() returns true just because is a Empty file!!! Try to write something on it.
In addition your while loop is infinite and a not correct compair (string == string is wrong):
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y)==splitted[x]){
System.out.println("Matched.");
y++;
}`enter code here`
}
System.out.println("Wrong spelling of: "+splitted[x]);
x++;
}
This loop maybe should be something like this:
int x=0;
int y=0;
while(x<splitted.length){
while(y<l.size()){
if(l.get(y).equals(splitted[x])){
System.out.println("l.get("+ y +") is "+ l.get(y) +", splitted["+x+"] is "+ splitted[x]);
System.out.println("Matched.");
y++;
x++;
}else{
System.out.println("Wrong spelling of: "+splitted[x]);
y++;
}
}
}

Related

How to use BufferedReader in a try catch?

I've been trying to use bufferedreader several times but every time I get some form error. This is time it is "not a statement" and "; expected" also "catch without try". I keep getting errors at the line with the try(bufferedreader) line. Am I using this correct? I am just trying it out and not quite sure how it works. from the online resource I've been looking at my code looks fine. But when I run my own it gives me errors.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Problem2 {
public static void main(String [] args) {
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(New FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
}
br.close();
}
catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}
}
}
1) The errors are simple, firstly you're supposed to use new FileReader (with lowercase n) rather than New FileReader (with uppercase N).
2) you're closing the else block before attaching the catch handlers to the try block.
I have now corrected both issues and the code below should compile.
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
br.close();
}catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}

PrintWriter issue with even numbers

I'm having an issue here: I had this program printing all even numbers 0 through 1000 but after a friend made some changes it only prints "0" now. I've worked with it for a while and can't figure out if it's a loop issue or a printwriter issue. I took the loop out of the printWriter method and still nothing. What exactly am I doing wrong?
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
public class NumberWriter {
public static void main(String[] args) {
String fileName = "numbers.txt";
try {
PrintWriter outputStream = new PrintWriter(fileName);
for(int i = 0; i <= 1000; i++){
if (i%2==0){
outputStream.println(i + "");
outputStream.close();
}
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Don't close your PrintWriter (outputStream) or you won't get any more output. And your code can be optimized to increment by 2 and bypass the even test (this works because every even number is a multiple of two). And Java now has The try-with-resources Statement so you don't have to remember to close your PrintWriter,
try (PrintWriter outputStream = new PrintWriter(fileName)) {
for(int i = 0; i <= 1000; i += 2){
outputStream.println(Integer.toString(i));
}
} catch (FileNotFoundException e) {
e.printStackTrace():
}

Program looping infinitly

I wrote program that take command from user and perform particular functionality. However, there is something wrong with the functionality read and write input to file which cause the loop to run indefinitely.
import java.util.HashMap;
import java.util.Scanner;
public class cShell{
static String Currentpath="C:\\";
public String Current = Currentpath;
static HashMap<String, ICommand> myhashData=new HashMap<String, ICommand>();
public static void main(String[] args)
{
myhashData.put("ltf", new cITF());
myhashData.put("nbc", new cNBC());
myhashData.put("gdb", new cGDB());
myhashData.put("Tedit", new cTedit());
do
{
System.out.print(Currentpath+"> ");
String Input = null;
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
Input = scan.nextLine().trim();
}
//if(Input.equals("exit")){
// System.exit(0);
//}
if(myhashData.containsKey(Input))
{
ICommand myCommand=myhashData.get(Input);
myCommand.Execute();
}
else
{
System.out.println("Invalid Command");
}
}while(!"Input".equals("exit"));
}
}
And here is the class which provide the functionality for read and write.
import java.util.*;
import java.io.*;
//import java.lang.System.*;
public class cTedit implements ICommand{
#Override
public void Execute() {
// TODO Auto-generated method stub
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
String filename = scan.nextLine();
InputStreamReader cin = null;
FileWriter out = null;
try{
cin = new InputStreamReader(System.in);
out = new FileWriter(cShell.Currentpath+"\\"+filename);
System.out.println("Enter character, 'q' to quit");
char c;
do{
c = (char) cin.read();
out.write(c);
}while(c!= 'q');
}
catch(Exception e){
System.out.println("Error");
}
finally{
try{
cin.close();
out.close();
}
catch(IOException e)
{
System.out.println("File did not close");
}
}
}
}
The problem is that after the reading and writing, the program output the message "Invalid Command" which is defined inside the class cShell. Can anyone point to me where this the cause..??
The do-while loop will run forever becauses its termination condition is:
!"Input".equals("exit")
The string "Input" will never be equal to the string "exit". You may want to use the variable Input instead:
!input.equals("exit")
Note:
Try to follow Java naming conventions. Use 'mixedCase' for methods/variables and use 'CamelCase' for classes/interfaces. In other words, the variable name should be input, not Input.
Change
while(!"Input".equals("exit"));
to
while(!Input.equals("exit"));
As "Input" can never be equal to "exit" condition is always true and hence it loops infinitely.
For NPE you can add null checks
finally{
try{
if(cin != null)
cin.close();
if(out != null)
out.close();
}
catch(IOException e)
{
System.out.println("File did not close");
}
}

Storing a text file of numbers into an array in java

Hi guys i have a text file in the following path C:/Users/Marc/Downloads/vector25 which contains comma-separated values in the following format
-6.08,70.93,-9.35,-86.09,-28.41,27.94,75.15,91.03,-84.21,97.84,
-51.53,77.95,88.37,26.14,-23.58,-18.4,-4.62,46.52,-19.47,17.54,
85.33,52.53,27.97,10.73,-5.82,
How would i read this text file and store those doubles in an array ?
I'm currently thinking of trying a buffered reader but so far the answer eludes me can anyone point me in the right direction ?
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class subvector {
public static void main(String[] args){
FileReader file = null;
try {
file = new FileReader("C:/Users/Marc/Downloads/vector25");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Double> list = new ArrayList<Double>();
int i=0;
try {
Scanner input = new Scanner(file);
while(input.hasNext())
{
list.add(input.nextDouble());
i++;
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
for(double k:list){
System.out.println(k);
}
}
You should use a delimeter
Scanner input = new Scanner(file);
input.useDelimeter(",");
Scanner.nextDouble() uses whitespace as the delimiter by default. Your input has commas as delimiter. You should use input.useDelimiter(",") to set commas as the delimiter before calling input.hasNext(). Then it should work as expected.
I think your code snippet will not for the specified data i.e. -6.08,70.93,-9.35,-86.09,-28.41,27.94,75.15,91.03,-84.21,97.84, -51.53,77.95,88.37,26.14,-23.58,-18.4,-4.62,46.52,-19.47,17.54, 85.33,52.53,27.97,10.73,-5.82,
But your program will work fine these type of data :
19.60
63.0
635.00
896.63
47.25
I have modified your program and tested with your data also. It's working as expected.
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("D:\\log4j\\vector25.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Double> list = new ArrayList<Double>();
int i=0;
Double d= null;
try {
BufferedReader input = new BufferedReader(file);
String s=null;
while((s=input.readLine())!=null) {
StringTokenizer st = new StringTokenizer(s,",");
while(st.hasMoreTokens()) {
try {
d = Double.parseDouble(st.nextToken());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list.add(i, d);
}
}
input.close();
} catch(Exception e) {
e.printStackTrace();
}
for(double k:list) {
System.out.println(k);
}
}
Please review it and let me know if you update anything.
This is my first POST on stackoverflow.
Thanks, Prasad

Reading a text file in Java and printing backwards with recursion

Write a Java program that recursively reads ten names from a file, and then outputs the total number of characters in the names, the list of names, and the list of names in reverse order. All looping must be performed recursively.
Jay Walker
Erol Flintstone
C. Erol Madre
Billy Pilgrim
Mickey Angels
José Francisco de San Martín
Squarebob Sponge Pants
Mischa Ternoff
Chester Peak
Al Italia
Ben Dover
Pat Pending
I am 100% lost. I would like advice on where would be the first place to start. Thinking about the program, I wanted to build a main that would call a scanner that would read the file first. When reading the file, it would count the characters in the text (quick question, would a scanner count the spaces between the characters?).
Next I was thinking of just a simple print function that would display the entire names.txt file.
Finally, the part the I'm 110% lost...how the heck would I go about listing the names in reverse order? What would I use? How does recursion fit in all this?
Something like this:
Reader(Stream strm)
{
string line;
if(!strm.eof())
{
line = strm.ReadLine();
Reader(strm);
}
// Info - char counte etc
string parseResult = Parse(line);
Print(parseResult);
}
Recursion will stop at the end of file and will start to unroll. The last message will be printed first.
Pseudocode for the recursion part:
function printLines(lines):
if lines not empty:
print first line from lines // this prints lines in order
call printLines(remaining lines)
print first line again // this prints lines in reverse order
Example output for lines ["line1", "line2", "line3"]
line1 // 1st output for printLines(["line1", "line2", "line3"])
line2 // 1st output for printLines(["line2", "line3"])
line3 // 1st output for printLines(["line3"])
// no output for printLines([])
line3 // 2nd output for printLines(["line3"])
line2 // 2nd output for printLines(["line2", "line3"])
line1 // 2nd output for printines(["line1", "line2", "line3"])
You can read file with scanner.nextLine(). It would read an entire line includiing spaces.
For how to print a string backwards using recursion, imagine that as a way containing houses on sides. You want to visit houses backwards (although you entered the way forwards). So you decided to go ahead until the way's end, and then back step by step and print neighbour house names.
function print( i )
if i == wayEnd
return
print(i + 1) // go ahead
// after you return, print:
output house at i
ADD
The code of method should be then:
private static Scanner scanner;
private static void readFile() {
if (!scanner.hasNext()) return;
String line = scanner.nextLine();
readFile();
System.out.println(line);
}
Just you have to call readFile() from main:
public static void main(String[] args) {
scanner = new Scanner(new File("myText.txt"));
readFile();
}
Am not good at scanning but using Desolator's scanner you can do the rest of the part as follows,
private Scanner scanner;
static Map<String, Integer> counts = new HashMap<String, Integer>();
public static void main(String[] args) {
scanner = new Scanner(new File("myText.txt"));
readFile();
System.out.println(counts);
}
private void readFile() {
if (!scanner.hasNext()) return;
String line = scanner.nextLine();
String[] names = line.split("([\\W\\s]+)");
for(int i=0;i<names.length;i++) {
populateMap(names[i]);
}
readFile();
}
static void populateMap(String str) {
counts.put(reverse(str), str.length());
}
static String reverse(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverse(s.substring(0,s.length()-1));
}
To train my Java skills I wrote you the following code:
import java.util.*;
import java.io.*;
public class RecursiveReadNames{
public static final int MAXLINES = 10;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("listOfNames.txt"));
String[] names = new String[MAXLINES];
readNames(names, scan, 0);
printNames(names,0);
System.out.println();
printNamesReverse(names,0);
System.out.println(totalNumberOfCharsInNames(names, 0,0));
}
static String[] readNames(String[] names, Scanner scan, int curLine) {
if(curLine >= MAXLINES)
return names;
names[curLine] = scan.nextLine();
return readNames(names, scan, curLine+1);
}
static void printNames(String[] names, int cur) {
if(cur >= names.length)
return;
System.out.println(names[cur]);
printNames(names, cur+1);
}
static void printNamesReverse(String[] names, int cur) {
if(cur >= names.length)
return;
printNamesReverse(names, cur+1);
System.out.println(names[cur]);
}
static int totalNumberOfCharsInNames(String[] names, int cur, int sum) {
if(cur >= names.length)
return sum;
return totalNumberOfCharsInNames(names, cur+1, sum+names[cur].length());
}
}
do something like this
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Test {
public static void printname(String name,BufferedReader br)
{
if(name!=null && br!=null)
{
try {
Test.printname(br.readLine(), br);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name);
}
}
static Scanner scanner1 = new Scanner(System.in);
public static void main(String[] args)
{
//print the names and total character in each name
try {
FileInputStream fin=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fin));
String n;
while((n=br.readLine())!=null)
{
System.out.println(n+" length:"+n.length());
}
fin.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//print names in reverse order
try {
FileInputStream f=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(f));
try {
Test.printname(br.readLine(),br);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
f.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
notice that I'm passing br object
import java.util.Scanner;
import java.io.*;
class Listnames{
public static void recursiveRead(Scanner scanner) {
String name;
if(scanner.hasNext())
{name=scanner.next();
recursiveRead(scanner);
System.out.println(name.length() +" "+ name);
}
}
public static void main(String[] args)
{
try{
Scanner scanner=new Scanner(new File("name.txt"));
scanner.useDelimiter(System.getProperty("line.separator"));
recursiveRead(scanner);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Categories

Resources