The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation
Related
I'm using Scanner to read 3 lines of input, the first two are strings and the last one is int.
I'm having an issue when the first line is empty and I don't know how to get around it. I have to do this:
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
encrypt(operation,line,index);
But when the first line is empty I get an error message.
I tried the following to force a loop until I get a non empty next line but it does not work either:
while(sc.nextLine().isEmpty){
operation = sc.nextLine();}
Anybody has a hint please ?
A loop should work, though you must actually call the isEmpty method and scan only once per iteration
String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());
You could also use sc.hasNextLine() to check if anything is there
Try this:
Scanner scanner = new Scanner(reader);
String firstNotEmptyLine = "";
while (scanner.hasNext() && firstNotEmptyLine.equals("")) {
firstNotEmptyLine = scanner.nextLine();
}
if (!scanner.hasNext()) {
System.err.println("This whole file is filled with empty lines! (or the file is just empty)");
return;
}
System.out.println(firstNotEmptyLine);
Then you can read the other two lines after this firstNotEmptyLine.
Please try this.
Scanner sc = new Scanner(System.in);
String operation = null;
String line = null;
int index = 0;
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
operation = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
line = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
index = Integer.parseInt(nextLine);
break;
}
}
System.out.println(operation + " " + line + " " + index);
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
test(operation,line,index);
}
public static void encrypt(String a,String b,int c){
System.out.println("first :"+a+" Second :"+b+" Third :"+c);
}
I don't see any error here. It compiles well.
I am attempting to create and write to a .txt file so that another program can open and read it. The problem is that the entered data is not being written to the file created. It is a blank .txt document.
import java.util.Scanner;
import java. io.*; //import class for file input.
public class inventoryStock
{
public static void main(String args[]) throws Exception
{
//Declarations
String[] itemName = new String [10];
double[] itemCost = new double [10];
double[] inStockNumber = new double [10];
int counter = 0;
//End declarations
Scanner input = new Scanner (System.in);
//Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw);
do
{
System.out.print("Enter item name");
pw.println();
itemName[counter] = input.next();
System.out.print("Enter item cost");
pw.println();
itemCost[counter] = input.nextDouble();
System.out.print("Enter Number in stock");
pw.println();
inStockNumber[counter] = input.nextDouble();
counter += 1;
}while(counter<10);
pw.flush();
pw.close();
System.exit(0);
} //End of main method
} //End of InventoryStock class.
It seems that you didn't really write what you want to file. You can try the code below.
pw.println(itemName[counter] + ", " + itemCost[counter] + ", " + inStockNumber[counter]);
Two recommendations to you.
Since the size 10 is everywhere in your code. You'd better extract it to a single variable for better maintainability.
Please follow the naming convention of java. For your case, the first letter of class name should be capitalized. Use InventoryStock instead of inventoryStock.
The entire code is like below, hope it will help. Thx.
import java.util.Scanner;
import java.io.*; //import class for file input.
public class InventoryStock {
public static void main(String args[]) throws Exception {
int size = 10;
// Declarations
String[] itemName = new String[size];
double[] itemCost = new double[size];
double[] inStockNumber = new double[size];
int counter = 0;
// End declarations
Scanner input = new Scanner(System.in);
// Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw);
{
do {
System.out.print("Enter item name");
itemName[counter] = input.next();
System.out.print("Enter item cost");
itemCost[counter] = input.nextDouble();
System.out.print("Enter Number in stock");
inStockNumber[counter] = input.nextDouble();
pw.println(itemName[counter] + ", " + itemCost[counter] + ", " + inStockNumber[counter]);
counter += 1;
} while (counter < size);
fw.flush();
}
fw.close();
System.exit(0);
} // End of main method
} // End of InventoryStock class.
You'll have to actually tell PrintWriter to write to file or else it won't do anything even though you grab the user's input with input.next(). Try something like this:
Scanner input = new Scanner (System.in);
//Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw, true);
do
{
System.out.print("Enter item name");
itemName[counter] = input.next();
pw.write(itemName[counter]);
pw.println();
System.out.print("Enter item cost");
itemCost[counter] = input.nextDouble();
pw.write(String.valueOf(itemCost[counter]));
pw.println();
System.out.print("Enter Number in stock");
inStockNumber[counter] = input.nextDouble();
pw.write(String.valueOf(inStockNumber[counter]));
pw.println();
counter += 1;
}while(counter<10);
pw.flush();
pw.close();
System.exit(0);
I'm trying to write a part of a program that reads a text file and then retrieves an integer from each line in the file and adds them together. I've managed to retrieve the integer, however each line contains more than one integer, leading me to inadvertently pick up other integers that I don't need. Is it possible to skip certain integers?
The format of the text file can be seen in the link underneath.
Text file
The integers that i'm trying to collect are the variables that are 3rd from the left in the text file above, (3, 6 and 4) however i'm also picking up 60, 40 and 40 as they're integers too.
Here's the code that i've got so far.
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
}
}
return itemAmount;
}
Just add input.nextLine():
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
}
From the documentation: nextLine advances the scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Another approach would be parsing each line and taking the third column.
BufferedReader r = new BufferedReader(new FileReader(filename));
while (true) {
String line = r.readLine();
if (line==null) break;
String cols[] line.split("\\s+");
itemAmount += Integer.parseInt(cols[2]);
}
r.close();
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
String []var = input.nextLine().split("\\s+");
itemAmount += var[2];
}
return itemAmount;
}
How do you "delete" a character from a file. Also, how do you print the stuff in the file out?
Write a program that reads in a file of text, perhaps the text of a novel. The program copies the same text to an output file, except that all the useless words such as "the", "a", and "an" are removed. (Decide on what other words you with to remove. The list of words removed is called a stop list.) Do this by reading the text file token by token using hasNext() and next(), but only writing out tokens not on the stop list.
Prompt the user for the names of the input and output files. Preserve the line structure of the input file. Do this by reading each line using nextLine() and then creating a new Scanner for that line. (Look at the on-line documentation for Scanner.) With each line's Scanner, use hasNext() and next() to scan through its tokens.
public static void main(String[] args) throws IOException {
String fileName;
Scanner user = new Scanner(System.in);
System.out.print("File name: ");
fileName = user.nextLine().trim();
File file = new File(fileName);
PrintStream printfile = new PrintStream(file);
System.out.println("Input data into file: ");
String datainfile = user.nextLine();
Scanner scan = new Scanner(file);
printfile.println(datainfile);
while (scan.hasNextLine()) {
while (scan.hasNext()) {
String character = scan.next();
if (character.equals("a")) {
}
}
}
}
EDIT
thanks to peeskillet I tried attempting again. However, there seems to be an error somewhere in my program and I get:
AAApotatopotatopotatojava.util.Scanner[delimiters=\p{javaWhitespace}+][position=0] [match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
Can you inspect my program?
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Input File name: ");
String filename1 = keyboard.nextLine().trim();
System.out.print("Output File name: ");
String filename2 = keyboard.nextLine().trim();
File inputFile = new File(filename1);
File outputFile = new File(filename2);
PrintStream printfile = new PrintStream(inputFile);
System.out.println("Input data into file: ");
String datainfile = keyboard.nextLine();
printfile.println(datainfile);
Scanner inFile = new Scanner(inputFile);
PrintWriter writeFile = new PrintWriter(outputFile);
Scanner lineScanner;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String word = lineScanner.next();
if(!(word.equals("a"))) {
writeFile.print(word + " ");
System.out.print(word);
}
if(!(word.equals("an"))) {
writeFile.print(word + " ");
System.out.print(word);
}
if(!(word.equals("the"))) {
writeFile.print(word + " ");
System.out.print(word);
}
else {
writeFile.print(" ");
}
}
writeFile.println();
}
writeFile.close();
Scanner readOutput = new Scanner(outputFile);
System.out.println(readOutput);
}
}
First of all you need two File objects, one for input and one for output. You only have one.
You want to do something like this
Scanner keyboard = new Scanner(System.in);
System.out.print("Input File name: ");
String filename1 = keyboard.nextLine();
System.out.print("Output File name: ");
String filename2 = keyboard.nextLine();
File inputFile = new File(filename1);
File outputFile = new File(filename2);
Scanner infile = new Scanner(inputFile);
PrintWriter outputFile = new PrintWriter(outputFile);
Scanner lineScanner;
while(infile.hasNextLine()){ // here you read each line of a file
String line = inFile.nextLine(); // here is a line
lineScanner = new Scanner(line); // for the above line, create a scanner
// just to scan that line
while(lineScanner.hasNext()){ // loop through that line
// do something
}
}
outputFile.close();
Edit: I would just put all the conditions into one statement
while (lineScanner.hasNext()) {
String word = lineScanner.next();
if(!(word.equals("a")) && !(word.equals("an")) && !(word.equals("the"))) {
writeFile.print(word + " ");
System.out.print(word);
}
}
I'm suppose to write a program in which we ask the user for 2 files the first file is for reading and the second for writing
the first one we are suppose to read the file and then copy the info switch it all to uppercase and save it to the second file
I cant get it to write on the second part any help?
public class FileConverter
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the filename for the first file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner (file);
while(inputFile.hasNext())
{
String fileinfo = inputFile.nextLine();
String uppercaseinfo1 = fileinfo.toUpperCase();
}
System.out.print("Enter the filename "
+ "for the second file");
filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(file);
while(inputFile.hasNext())
{
outputFile.println();
}
}
}
You need to close() the PrintWriter
...
while(inputFile.hasNext())
{
outputFile.println();
}
ouputFile.close();
Also, You don't need two loops. Just do the transferring all in one loop. You need to make sure you have two different File objects. One for the input and one for the output. With different file names.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the filename for the first file");
String filename = keyboard.nextLine();
File file = new File(filename); // file 1
Scanner inputFile = new Scanner (file); // infile
System.out.print("Enter the filename "
+ "for the second file");
filename = keyboard.nextLine();
File file1 = new File(filename); // file 2
PrintWriter outputFile = new PrintWriter(file1); // outfile
while(inputFile.hasNext())
{
String fileinfo = inputFile.nextLine();
String uppercaseinfo1 = fileinfo.toUpperCase();
outputFile.println(uppercaeinfo1);
}
outputFile.close();
You need a FileWriter in there, and close it:
FileWriter outFile = new FileWriter(filePath);
PrintWriter out = new PrintWriter(outFile);
out.println("stuff");
out.close();
Use an instance of BufferedWriter to write into the file instead of PrintWriter.
e.g.
BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); // create the write buffer
// to-do: EITHER surround with try-catch in order catch the IO Exception OR add throws declaration
bw.write("some text"); // content for the new line
bw.newLine(); // a line break
bw.flush(); // flush the buffer and write into the file
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the filename for the first file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner (file);
System.out.print("Enter the filename "
+ "for the second file");
String filename2 = keyboard.nextLine();
File file2 = new File(filename2);
PrintWriter outputFile = new PrintWriter(file2);
while(inputFile.hasNext())
{
String fileinfo = inputFile.nextLine();
String uppercaseinfo1 = fileinfo.toUpperCase();
outputFile.println(uppercaseinfo1);
}
outputFile.close()
}
}
I do it smth like this
Not only close() method is absent. Solution has some mistakes.
// corrected statements are marked with "!"
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the filename for the first file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String uppercaseinfo1 = ""; // !
while(inputFile.hasNext())
{
String fileinfo = inputFile.nextLine();
uppercaseinfo1 += fileinfo.toUpperCase() + "\n"; // !
}
inputFile.close(); // !
System.out.print("Enter the filename "
+ "for the second file");
filename = keyboard.nextLine();
file = new File(filename); // !
PrintWriter outputFile = new PrintWriter(file);
outputFile.println(uppercaseinfo1); // !
outputFile.close(); // !
}
And, as rightly noted above, you must close input/output streams at the end, if you want changes to take effect.