Program terminates without printing anything - java

I am trying to print a line from the listed file, which contains a word stated. But the program does nothing. Can someone help me with the code? Thanks
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class SearchingArrayLists {
public static void main(String[] args) throws Exception {
ArrayList names = new ArrayList();
Scanner scan = new Scanner(new File("random.txt"));
while (scan.hasNext()){
names.add(scan.next());
}
if (names.contains("legal")){
System.out.println(scan.next());
}
scan.close();
}
}
UPDATE:
Sorry, removed the loop. the file contains random text where the word "legal" is in there. the file was read by the scanner beforehand.

System.out.println(scan.next()); will throw an exception, since you are calling it after you consumed all the input in the while (scan.hasNext()) loop.
But it may not even reach that exception if your names list doesn't contain an exact match to the String "legal".

Scanner scan = new Scanner(new File("random.txt"));
String name = "" ;
while (scan.hasNextLine()){
name = scan.nextLine();
if (name.contains("legal")){
System.out.println(name);
}
}
scan.close();
Try above code , you even don't need list. I have not compiled it , so remove if any syntax error you got.

Related

Java Using Scanner to Read File and Then Read Line

I'm trying to make a scanner that reads a file and deletes the spaces between each word. I can get this much but I can't get it to where they stay on the same line. I can't get the program to read a line, delete the spaces, and then go to the next line. This is the text from my practice project:
four score and
seven years ago our
fathers brought forth
on this continent
a new
nation
I'm currently only getting the first line
and this is my code:
import java.util.*;
import java.io.*;
public class CollapseSpace {
public static void main (String[] args) throws FileNotFoundException{
Scanner fileInput = new Scanner(new File ("textwithspaces.txt"));
String nextLine = fileInput.nextLine();
Scanner lineInput = new Scanner(nextLine);
while(fileInput.hasNext()){
nextLine = fileInput.nextLine();
while(lineInput.hasNext()){
System.out.print(lineInput.next() + " "); // I tried to add a fileInput.NextLine() to consume the line but it isn't working properly
}
System.out.println();
}
}
}
If you only need to iterate line by line and remove spaces between words then you only need one loop, sample code below should do the trick
public static void main (String[] args) throws FileNotFoundException{
final Scanner fileInput = new Scanner(new File ("src/main/resources/textwithspaces.txt"));
while(fileInput.hasNext()){
final String nextLine = fileInput.nextLine();
// remove all spaces
final String lineWithOutSpaces = nextLine.replaceAll("\\s+","");
System.out.println(lineWithOutSpaces);
}
}
First of all, you shouldn't be using * to import classes. It is generally thought of as "bad practice" since it can interfere with your own classes, also it is not very explicit.
You need to loop the nextLine method inside your own loop. And also using a replaceAll method of the string would be good.
I have shown an example below:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class Main {
public static void main(String[] args) throws FileNotFoundException {
// Create an object to represent a text file
File file = new File("textwithspaces.txt");
// Create a scanner with the text file as argument
Scanner scannerWithFile = new Scanner(file);
// Continue as long as it has a next line
do {
// Replace strings
String thisLine = scannerWithFile.nextLine();
// Only print the line out if not empty
if (!thisLine.isEmpty()) {
// Replace all spaces
thisLine = thisLine.replaceAll(" ", "");
// Print
System.out.println(thisLine);
}
} while (scannerWithFile.hasNext());
}
}
I also switched your while loop to a do while loop, this is so you can just instantly go into the loop without having to check for a condition first, it is done before next iteration.
Your biggest problem is that you declared nextLine = fileInput.nextLine(); outside of the loop, and then used that in Scanner lineInput = new Scanner(nextLine); so it becomes the first line of the text, but then never changes.
I also agree with the other comment that says you shouldn't be using *, it's considered bad practice to import broadly like that, as you're importing a whole lot of stuff you won't be using.
I reconstructed your code to make it work.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main (String[] args) throws FileNotFoundException{
Scanner fileInput = new Scanner(new File ("textwithspaces.txt"));
while(fileInput.hasNext()){
String nextLine = fileInput.nextLine();
Scanner lineInput = new Scanner(nextLine);
while(lineInput.hasNext()){
System.out.print(lineInput.next() + " ");
}
System.out.println();
}
}
}

my program reads from the file but cant find the words

So my program knows where the file is and it can read how many words it has, however, I am trying to compare words to count the occurrences of a word that i will use with a scanner.
The program says i can't convert string to a boolean which i understand but how would i be able to make it happen?
can I get an answer why it runs but doesn't allow me to find the word to look for
thanks
import java.util.*;
import java.io.*;
public class wordOccurence {
public static void main(String[] args) throws IOException {
{
int wordCount=0;
int word =0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter file name");
System.out.println("Enter the word you want to scan");
String fileName=scan.next().trim();
Scanner scr = new Scanner(new File(fileName));
// your code goes here ...
while(scr.nextLine()){
String word1 = scr.next();
if (word1.equals(scr)){
word++;
}
}
System.out.println("Total words = " + word);
}
}
}
At present you are only checking if there is a next line available:
while(scr.hasNextLine()){
but you are not fetching it. Its like you are staying at the same position in the file forever.
To fetch the next line, you can make use of
scanner.nextLine()

Java end of file [closed]

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 7 years ago.
Improve this question
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner line = new Scanner(System.in);
int counter = 1;
while (line.hasNextLine()) {
String line = line.nextLine();
System.out.println(counter + " " + line);
counter++;
}
}
}
Task: Each line will contain a non-empty string. Read until EOF.
For each line, print the line number followed by a single space and the line content.
Sample Input:
Hello world
I am a file
Read me until end-of-file.
Sample Output:
1 Hello world
2 I am a file
3 Read me until end-of-file.
If you'd like to scan from a file, you can use the below code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("input.txt"));
int counter = 1;
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(counter + " " + line);
counter++;
}
}
}
Scanner line = new Scanner(); // <-- YOUR ERROR - there is no constructor for the Scanner object that takes 0 arguments.
// You need to specify the environment in which you wish to 'scan'. Is it the IDE? A file? You need to specify that.
Since you said EOF, I'm assuming there is a File associated with this task.
Create a File object, toss that into the Scanner constructor.
File readFile = new File(PATH_TO_FILE); // where PATH_TO_FILE is the String path to the location of the file
// Set Scanner to readFile
Scanner scanner = new Scanner(readFile);
You also have a duplicate local variable named: line
I suggest you do more reading to get a grasp of how variables and objects work rather than guess or be spoonfed code you don't understand. That's how you become a strong programmer.
Documentation states that you need to pass Source to Scanner, so that it can scan from it.
To get user input then you need to use Scanner(InputStream source) constructor.
Scanner line = new Scanner(System.in);
public static void main(String[] args) {
Scanner line = new Scanner(System.in); // Added source parameter in constructor.
int counter = 1; // Initialization of counter is done outside while loop, otherwise it will always get initialized by 1 in while loop
while (line.hasNextLine()) {
String lineStr = line.nextLine(); // changed variable name to lineStr, because 2 variable can't be declared with the same name in a method.
System.out.println(counter + " " + lineStr);
counter++;
}
}
Note: Make sure you break your while loop, otherwise it will go into infinite loop.
You can't have multiple variable without the same name. You must rename one of your line variables.
When creating a scanner, you need to send in the input stream you want it to read from. System.in can server as this stream and it will read from your console. Your question though seems to indicate that you want to read from a file. If you indeed want to read from a file, you need to create the file you want to read from and send that file into the scanner to allow the scanner to read from that file.
Try:
public class Solution {
public static void main(String[] args) {
//create the File
File file = new File(filename);
//send the file into Scanner so it can read from the file
Scanner scanner = new Scanner(file);
//initialize the counter variable
int counter = 1;
//read in the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(counter +" "+ line);
counter++;
}
}
}
To read user input, you need to use System.in in your declaration of the line object in your code:
Scanner line = new Scanner(System.in);
int counter = 0; // Initialized out of loop.
while (line.hasNextLine()) {
String ln = line.nextLine();
System.out.println(counter +" "+ln);
counter++;
}

Error Parsing a Csv File with Java

I have a csv file with values like these:
1/1/1983;1,7;-3;8;-0,7;84;4;2;11;0;1030;0;0
2/1/1983;2,7;-2;8,4;1,9;94;2;2;15;0;1027;0;0
3/1/1983;4,1;-0,4;11,3;3,1;93;3;3;13;0;1030;0;0
4/1/1983;7,6;1,3;15;5,1;84;9;8;28;0;1027;0;0
5/1/1983;5,6;1,4;10;5,1;97;2;2;11;0;1023;0;0
6/1/1983;7;5,5;7,5;7;100;1;3;9;0;1028;0;0
7/1/1983;7,7;5;13,4;7,1;96;1;4;20;0;1029;0;0
8/1/1983;7,9;7;15,5;7,4;97;2;7;24;0;1029;0;1
9/1/1983;6,7;1;10,3;4,1;83;8;15;44;0;1033;0;0,3
10/1/1983;2,2;-1,9;8;0,4;88;8;4;13;0;1036;0;0
11/1/1983;0,7;-3,4;6,4;-1,2;87;3;1;13;0;1038;0;0
12/1/1983;0,2;-4,7;8;-1,7;87;6;4;9;0;1037;0;0
13/1/1983;1,7;-5,2;11,1;-0,1;88;4;3;15;0;1032;0;
So i have found on a website a Csv Parser implementation:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerExample
{
public static void main(String[] args) throws FileNotFoundException
{
//Array
ArrayList<String> weather = new ArrayList<String>();
//Get scanner instance
Scanner scanner = new Scanner(new File("C:/csv/meteo2.csv"));
//Set the delimiter used in file
scanner.useDelimiter(";");
//Get all tokens and store them in some data structure
//I am just printing them
while (scanner.hasNext())
{
weather.add(scanner.next());
}
System.out.println(weather.get(12));
//Do not forget to close the scanner
scanner.close();
}
}
But I Have a problem with the last element of one line and the first element of the successive line :
Infact when in the code i try to print the twelfth element (that must be 0). It prints
0
2/1/1983
But it's considered as only one element.
There is a solution to that?
If you want the semicolon and the linebreak as a delimiter, you should use
scanner.useDelimiter("[;\n]");
as Scanner#useDelimiter(String pattern) expects a regular expression as the parameter.

Storing file content into an array

I'm having a problem with my hangman program. I really think what I need to do is beyond what I understand about java. Here's my code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Random;
public class HangmanProject
{
public static void main(String[] args) throws FileNotFoundException
{
String scoreKeeper; // to keep track of score
int guessesLeft; // to keep track of guesses remaining
String[] wordList = new String[25];
final Random generator = new Random();
Scanner keyboard = new Scanner(System.in); // to read user's input
System.out.println("Welcome to Nick Carfagno's Hangman Project!");
// Create a scanner to read the secret words file
Scanner wordScan = null;
try
{
wordScan = new Scanner(new BufferedReader(new FileReader("words.txt")));
while (wordScan.hasNext())
{
}
}
finally
{
if (wordScan != null)
{
wordScan.close();
}
}
// get random word from array
class pickRand
{
public String get(String[] wordList)
{
int rnd = generator.nextInt(wordList.length);
return wordList[rnd];
}
}
System.out.println(wordList);
}
}
I was able to get the program to read a file and then print to screen, but I can't figure out how to store the words from file into an array. I not advanced at all, so please try and be as thorough as possible.
1) What you've got so far looks pretty good :)
2) Since you don't know exactly how many or few words you'll have, you don't want an "array". You're probably better off with an "ArrayList". Arrays are "fixed". Lists are "variable".
3) For each "word" you read, just ".add()" it to your arraylist
Voila! Done.
Here's a complete example:
http://www.daniweb.com/software-development/java/threads/311569/readingwriting-arraylist-fromto-file#
You need to save the read line in a String object and assign it to a certain field of the array. For example:
wordList[0] = myString;
This would assign the value of myString to the first field of your array.

Categories