Scanner returning NoSuch Element Exception error. Could you explain why is this happening.
The Scanner now passes and runs fine but it didn't take the nextLine input from the second Scanner call. This may be a little tweak but could someone point out what the mistake is.
public class JavaHW1_1 {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) throws IOException {
String pattern ;
String fileName = null;
// Method to manage user inputs
fileName = userInputFileName(userInput);
pattern = userInputPattern(userInput);
// To find the pattern in the file
// findPattern();
}
private static String userInputPattern(Scanner userInput) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
while(userInput.hasNextLine()){
pattern = userInput.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
}
userInput.close();
return pattern;
}
private static String userInputFileName(Scanner userInput) throws IOException {
String path = "./src";
String files, fileName;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
System.out.println("Please input the desired file name:\n");
System.out.println("Some suggestions:\n");
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".txt"))
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
int userAttempt = 0;
do{
fileName = userInput.nextLine();
if(fileName.toLowerCase().endsWith(".txt")){
System.out.println("The file name entered is in correct format");
File file = new File("./src",fileName);
try {
file.createNewFile();
System.out.println("File is created. Please enter text to be written in the file. End the content with \"eof\"");
InputOutput(file.getName());
} catch (IOException e) {
e.printStackTrace();
}
userAttempt = 10;
}
else
{System.out.println("Please enter correct format file with .txt extension");
userAttempt++;}
}while (userAttempt <10);
return fileName;
}
private static void InputOutput(String fName) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("./src/" + fName));
String inputLine = null;
do {
inputLine=in.readLine();
out.write(inputLine);
out.newLine();
} while (!inputLine.equalsIgnoreCase("aaa"));
System.out.print("Write Successful");
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
private static void findPattern() {
// TODO Auto-generated method stub
}
}
Based in this SO, you might be closing the Scanner and creating a new one to read from the System.in and it makes sense by looking at your code.
So my suggestion for you code is to receive the Scanner by parameter, something like this:
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
String pattern = userInputPattern(scan);
String test = readSomethingElse(scan);
}
private static String readSomethingElse(Scanner scan) {
System.out.println(". Read something else");
return scan.nextLine();
}
private static String userInputPattern(Scanner scan) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
pattern = scan.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
return pattern;
}
It could happen if you pass EOF straight into the standard input. For example (in windows):
java com.myprog.MainClass
^Z
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
....
The ^Z above represents a Ctrl-Z on windows command prompt which is an EOF signal
You need to consider your requirement and process / display error if user is provided a EOF without any prior data
Related
I am working on creating a tester.
When I tried
javac WordListsTester.java
java WordListsTester a.txt
I think it should show an error message as the file has to be "dictionary.txt" but, it does not.
What should I fix?
public class WordListsTester {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
WordLists scrabble = new WordLists("dictionary.txt");
String[] containLetter = scrabble.containsLetter(3, 'a');
output(containLetter, "containsLetter.txt");
String[] wordsStarts = scrabble.startsWith(3, 'a');
output(wordsStarts, "startsWith.txt");
String[] wordLength = scrabble.lengthN(3);
output(wordLength, "lengthN.txt");
String[] multiLetter = scrabble.multiLetter(2, 'h');
output(multiLetter, "multiLetter.txt");
String[] vowelHeavy = scrabble.vowelHeavy(5, 2);
output(vowelHeavy, "vowelHeavy.txt");
input.close();
}
public static void output(String[] words, String fileName) {
try {
PrintWriter out = new PrintWriter(fileName);
if (words.length == 0) {
System.out.println("NO matched Words exist");
}
for (int i = 0; i < words.length; i++) {
out.println(words[i]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Invalid file name.");
}
}
}
WordLists scrabble = new WordLists(args[0]);
Not sure what this program does exactly.
Not sure if file name is being checked inside the WordLists class.
But if you want to check USER INPUT, you need to check args[0].
What I'm trying to do is to make my program read input test-cases from a file instead of standard console input and write back the output to another file.
Here comes the problem into play, if I'm trying to give input using file it is showing java.lang.NullPointerException, but on other hand giving correct output if I'm trying to give custom standard input(using cmd) and printing output to a file.
Here is my sample program:
public class Roman
{
static private final String INPUT = "Q4.in";
static private final String OUTPUT = "Q4.out";
// open I/O files
public static void main(String[] args)
{
FileInputStream instream = null;
PrintStream outstream = null;
try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}
int i;
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
Num2Rom[] tc=new Num2Rom[T];
for(i=0;i<T;i++)
{ tc[i]=new Num2Rom(); }
System.out.println(T+"\n");
for(i=0;i<T;i++)
{ tc[i].display(i+1); }
}
}
and
ArrayList<String> wordList;
Num2Rom()
{
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String numeral = sc.nextLine();
System.out.println("print"+numeral);
numeral = numeral.toUpperCase();
String[] words = numeral.split(" ");
wordList = new ArrayList<>(Arrays.asList(words)); }
}
The input is formatted as:
2
Eight
Twenty
You can use java command line arguements to give input to the program.
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
do convert the arguments to the desired type,as arguments are received in the string format.
such as if you want an integere you can convert using
int value=Integer.parseInt($args[0]);
I'm trying to read a text file to get a version number but for some reason no matter what I put in the text file it always returns 0 (zero).
The text file is called version.txt and it contains no spaces or letters, just 1 character that is a number. I need it to return that number. Any ideas on why this doesn't work?
static int i;
public static void main(String[] args) {
String strFilePath = "/version.txt";
try
{
FileInputStream fin = new FileInputStream(strFilePath);
DataInputStream din = new DataInputStream(fin);
i = din.readInt();
System.out.println("int : " + i);
din.close();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
private final int VERSION = i;
Here is the default solution that i use whenever i require to read a text file.
public static ArrayList<String> readData(String fileName) throws Exception
{
ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String temp = in.readLine();
while (temp != null)
{
data.add(temp);
temp = in.readLine();
}
in.close();
return data;
}
Pass the file name to readData method. You can then use for loop to read the only line in the arraylist, and can use the same loop to read multiple lines from different file...I mean do whatever you like with the arraylist.
Please don't use a DataInputStream
Per the linked Javadoc, it lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
You want to read a File (not data from a data output stream).
Please do use try-with-resources
And since you seem to want an ascii integer, I'd suggest you use a Scanner.
public static void main(String[] args) {
String strFilePath = "/version.txt";
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
int i = scanner.nextInt();
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}
Use an initializing block
An initializing block will be copied into the class constructor, in your example remove public static void main(String[] args), something like
private int VERSION = -1; // <-- no more zero!
{
String strFilePath = "/version.txt";
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
VERSION = scanner.nextInt(); // <-- hope it's a value
System.out.println("Version = " + VERSION);
} catch (Exception e) {
e.printStackTrace();
}
}
Extract it to a method
private final int VERSION = getVersion("/version.txt");
private static final int getVersion(String strFilePath) {
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
VERSION = scanner.nextInt(); // <-- hope it's a value
System.out.println("Version = " + VERSION);
return VERSION;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
or even
private final int VERSION = getVersion("/version.txt");
private static final int getVersion(String strFilePath) {
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
if (scanner.hasNextInt()) {
return scanner.nextInt();
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
I am have a project that need to modify some text in the text file.
Like BB,BO,BR,BZ,CL,VE-BR
I need make it become BB,BO,BZ,CL,VE.
and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR.
I have tried to type some code, however the code fail to loop and also,in this case.
IN/CI, GH, KE, NA, NG, SH, ZW /EE, HU, LT, LV, UA,/AR, BB
"AR, BB,BO,BR,BZ,CL, CO, CR, CW, DM, DO,VE-AR-BR-MX"
I want to delete the AR in second row, but it just delete the AR in first row.
I got no idea and seeking for helps.
Please
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class tomy {
static StringBuffer stringBufferOfData = new StringBuffer();
static StringBuffer stringBufferOfData1 = stringBufferOfData;
static String filename = null;
static String input = null;
static String s = "-";
static Scanner sc = new Scanner(s);
public static void main(String[] args) {
boolean fileRead = readFile();
if (fileRead) {
replacement();
writeToFile();
}
System.exit(0);
}
private static boolean readFile() {
System.out.println("Please enter your files name and path i.e C:\\test.txt: ");
filename = "C:\\test.txt";
Scanner fileToRead = null;
try {
fileToRead = new Scanner(new File(filename));
for (String line; fileToRead.hasNextLine()
&& (line = fileToRead.nextLine()) != null;) {
System.out.println(line);
stringBufferOfData.append(line).append("\r\n");
}
fileToRead.close();
return true;
} catch (FileNotFoundException ex) {
System.out.println("The file " + filename + " could not be found! "+ ex.getMessage());
return false;
} finally {
fileToRead.close();
return true;
}
}
private static void writeToFile() {
try {
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(
filename));
bufwriter.write(stringBufferOfData.toString());
bufwriter.close();
} catch (Exception e) {// if an exception occurs
System.out.println("Error occured while attempting to write to file: "+ e.getMessage());
}
}
private static void replacement() {
System.out.println("Please enter the contents of a line you would like to edit: ");
String lineToEdit = sc.nextLine();
int startIndex = stringBufferOfData.indexOf(lineToEdit);
int endIndex = startIndex + lineToEdit.length() + 2;
String getdata = stringBufferOfData.substring(startIndex + 1, endIndex);
String data = " ";
Scanner sc1 = new Scanner(getdata);
Scanner sc2 = new Scanner(data);
String lineToEdit1 = sc1.nextLine();
String replacementText1 = sc2.nextLine();
int startIndex1 = stringBufferOfData.indexOf(lineToEdit1);
int endIndex1 = startIndex1 + lineToEdit1.length() + 3;
boolean test = lineToEdit.contains(getdata);
boolean testh = lineToEdit.contains("-");
System.out.println(startIndex);
if (testh = true) {
stringBufferOfData.replace(startIndex, endIndex, replacementText1);
stringBufferOfData.replace(startIndex1, endIndex1 - 2,
replacementText1);
System.out.println("Here is the new edited text:\n"
+ stringBufferOfData);
} else {
System.out.println("nth" + stringBufferOfData);
System.out.println(getdata);
}
}
}
I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash.
The method reads the file and writes it straight out to a file after editing for the token. This would allow you to process a huge file without worrying about about memory constraints.
You can simply rename the output file after a successful edit. I'll leave it up to you to work that out.
If you feel you really must use string buffers to do in memory management, then grab the logic for the line editing from my method and modify it to work with string buffers.
static void onePassReadEditWrite(final String inputFilePath, final String outputPath)
{
// the input file
Scanner inputScanner = null;
// output file
FileWriter outputWriter = null;
try
{
// open the input file
inputScanner = new Scanner(new File(inputFilePath));
// open output file
File outputFile = new File(outputPath);
outputFile.createNewFile();
outputWriter = new FileWriter(outputFile);
try
{
for (
String lineToEdit = inputScanner.nextLine();
/*
* NOTE: when this loop attempts to read beyond EOF it will throw the
* java.util.NoSuchElementException exception which is caught in the
* containing try/catch block.
*
* As such there is NO predicate required for this loop.
*/;
lineToEdit = inputScanner.nextLine()
)
// scan all lines from input file
{
System.out.println("START LINE [" + lineToEdit + "]");
// get position of dash in line
int dashInLinePosition = lineToEdit.indexOf('-');
while (dashInLinePosition != -1)
// this line has needs editing
{
// split line on dash
String halfLeft = lineToEdit.substring(0, dashInLinePosition);
String halfRight = lineToEdit.substring(dashInLinePosition + 1);
// get token after dash that is to be removed from whole line
String tokenToRemove = halfRight.substring(0, 2);
// reconstruct line from the 2 halves without the dash
StringBuilder sb = new StringBuilder(halfLeft);
sb.append(halfRight.substring(0));
lineToEdit = sb.toString();
// get position of first token in line
int tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
while (tokenInLinePosition != -1)
// do for all tokens in line
{
// split line around token to be removed
String partLeft = lineToEdit.substring(0, tokenInLinePosition);
String partRight = lineToEdit.substring(tokenInLinePosition + tokenToRemove.length());
if ((!partRight.isEmpty()) && (partRight.charAt(0) == ','))
// remove prefix comma from right part
{
partRight = partRight.substring(1);
}
// reconstruct line from the left and right parts
sb.setLength(0);
sb = new StringBuilder(partLeft);
sb.append(partRight);
lineToEdit = sb.toString();
// find next token to be removed from line
tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
}
// handle additional dashes in line
dashInLinePosition = lineToEdit.indexOf('-');
}
System.out.println("FINAL LINE [" + lineToEdit + "]");
// write line to output file
outputWriter.write(lineToEdit);
outputWriter.write("\r\n");
}
}
catch (java.util.NoSuchElementException e)
// end of scan
{
}
finally
// housekeeping
{
outputWriter.close();
inputScanner.close();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
inputScanner.close();
e.printStackTrace();
}
}
So the following program should take in an input and output file as command line arguments.
class FileCopy
{
public static void main(String[] args) throws IOException
{
String infile = null;
String outfile = null;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
if (args.length >= 2) //both files given via command line
{
infile = args[0];
if (fileExists(infile) == false)
{
infile = getInputFile();
}
outfile = args[1];
}
else if (args.length == 1) //input file given via command line
{
infile = args[0];
outfile = getOutputFile(infile);
}
else //no files given on command line
{
infile = getInputFile();
outfile = getOutputFile(infile);
}
//create file objects to use
File in = new File(infile);
File out = new File(outfile);
/*
*rest of code
*/
}
//get the input file from the user if given file does not exist
public static String getInputFile() //throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
boolean haveFile = false;
while(haveFile == false)
{
System.out.println("Enter a valid filename for input:");
System.out.print(">> ");
try
{
fileName = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
haveFile = fileExists(fileName);
}
return fileName;
}
//get the output file and test things
public static String getOutputFile(String infile)
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
File input = new File(infile);
String filename = null;
boolean more = true;
while(more)
{
System.out.println("Enter a valid filename for output:");
System.out.print(">> ");
try
{
filename = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
File output = new File(filename);
if (output.exists())
{
more = false;
}
if (filename == infile)
{
int selection;
String inputString = null;
System.out.println("The output file given matches the input file. Please choose an option:");
System.out.println("1) Enter new filename");
System.out.println("2) Overwrite existing file");
System.out.println("3) Backup existing file");
System.out.print(">> ");
try
{
inputString = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
selection = Integer.valueOf(inputString);
switch (selection)
{
case 1: //new filename
case 2: //overwrite
case 3: //backup
default: System.exit(0);
}
}
}
return null;
}
//check the given file to see if it exists in the current working directory
public static boolean fileExists(String n)
{
return (new File(n)).exists();
}
}
One detail that I believe you have missed:
When your program has only one argument (args.length == 1), i.e. when only the input file is defined, fileExists() is not called at all; infile is set to args[0] with no validation at all. You should probably add a specific check as you have done for the two-argument case.
I've ran into a similar problem too. I was working under eclipse, and had to specify "src/file.txt" with my current directory having a file named "file" in the src directory.
Note: It was not named "file.txt" (this causes the string to be interpreted as "file.txt.txt"!).
Try testing against this program here assuming you have a file named "file" in your "src" directory:
import java.io.File;
public class FileChecker {
public static boolean Exists( String file )
{
System.out.println("File being checked: " + file);
return( (file.length()) > 0 && (new File(file).exists()) );
}
public static void main( String[] args )
{
File dir = new File("src");
System.out.println("List of files in source directory: ");
if( dir.isDirectory()){
File[] filenames = dir.listFiles();
for( Object file : filenames ) {
System.out.println(file.toString());
}
}
else
System.out.println("Directory does not exist.");
if(FileChecker.Exists("src/file.txt"))
System.out.println("File exists");
else
System.out.println("File does not exist");
}
}
It will print out the current files in source directory so you can see whether the file is really there or not, then you can test if it actually exists. Works on my end.