Looking for help with the following code...
package pkgPeople;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class CreateWithoutSerialization {
public static void main(String[] args) throws Exception
{
BankAccount bankAccount = new BankAccount(0, 0);
Person person = new Person();
String nm;
int ht;
int wt;
long ba;
double bal;
File inFile = new File("G:/CS9.27/inperson.txt");
File outFile = new File("G:/CS9.27/outperson.txt");
PrintWriter writer = new PrintWriter(outFile);
Scanner reader = new Scanner(inFile);
nm = reader.nextLine();
ht = reader.nextInt();
wt = reader.nextInt();
ba = reader.nextLong();
bal = reader.nextDouble();
person.setName(nm);
person.setHeight(ht);
person.setWeight(wt);
bankAccount.setAcctID(ba);
bankAccount.setBalance(bal);
System.out.println(person.toString());
//Write the attributes in ASCII to a file
writer.printf("%s is the name of the person.\r\n",nm);
writer.printf("%d inches is the height of %s.\r\n",ht, nm);
writer.printf("%d pounds is the weight of %s\r\n",wt,nm);
writer.printf("%d dollars is the balance of %s\r\n", bal, nm);
writer.printf("%l is the ID of the bank account.\r\n", ba);
}
}
Upon running, i get this exception..
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at pkgPeople.CreateWithoutSerialization.main(CreateWithoutSerialization.java:23)
Is this a file error? Have tried multiple fixes but still stuck.
The exception is being thrown in the call to reader.nextLine() According to the javadoc, this means that nextLine() could not find a next line.
Based on a careful reading of the javadoc, I think that this means that your input file is empty. You could test this by calling hasNextLine() before the call to nextLine().
As a beginner in a programming language, you need to learn how to use the documentation and resources made readily available for that language.
If you look at the javadoc for the method you are using here you would soon realize that the problem is that there is not a new line character for the Scanner to read in a line. Check your input file and make sure it meets the specifications. If you are sure your input file is correct you can do some debugging by using the file API to make sure the input File exists before attempting to use it as input for the Scanner.
All of the information you need is readily available in the javadoc.
Hmmm... I there are two things which are missing here....
Now the NoSuchElementException comes when input is exhausted . It need not to be related to nextLine(). So check whether for the following number of reads
nm = reader.nextLine();
ht = reader.nextInt();
wt = reader.nextInt();
ba = reader.nextLong();
bal = reader.nextDouble();
You have equal number of lines in your inperson.txt
Also
When done writing ... do this also..
writer.flush();
writer.close();
Otherwise you won't see any output file... :)
good luck
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I have a rudimentary piece of code that's meant to update a properties file. However, it seems that of the two possible keywords to update, only the second is updated by the user's input, as opposed to one after the other.
Here is the full code:
import java.io.*;
import java.util.Properties;
import java.util.Scanner;
public class UpdateProperty{
private static int choice;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws Exception
{
FileInputStream in = new FileInputStream("Stats.properties");
Properties props = new Properties(); //creates a Properties object named prop
props.load(in); //loads in as value of prop
in.close(); //no idea
System.out.println("1- BlackBerryIzzie: " + props.getProperty("BlackBerryIzzie"));
System.out.println("2- GrapeFruitIzzie: " + props.getProperty("GrapeFruitIzzie"));
System.out.println("");
String blackAmount = props.getProperty("BlackBerryIzzie");
String grapeAmount = props.getProperty("GrapeFruitIzzie");
//System.out.println("Selling BlackBerry Izzie");
//blackAmount = itemSold(blackAmount);
System.out.println("Do you wish to update inventory? Type 2");
choice = sc.nextInt();
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
}
public static String itemSold(String s){
int i=Integer.parseInt(s);
i -= 1;
String ret=Integer.toString(i);
return ret;
}
}
The bit that seems to be malfunctioning:
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
This is meant to ask the user for blackberry amount, then update the BlackBerryIzzie keyword to that amount. Then, it is meant to do the same for grapefruit after blackberry is done. However, it skips blackberry and only asks for one scanner input and sets grapefruit to that.
Thanks for your time!
Don't mix nextLine and nextAnythingElse.
The solution is to set your scanner's delimiter to what you want. You want 'user presses enter' to be the delimiter, surely. So, tell scanner that. Run scanner.useDelimiter("\\R") immediately after making it. Then, to get 'an entire line', call .next(), if you want that line to be read as e.g. an int, call .nextInt(), etc. Don't call nextLine() for anything.
Explaining why mixing nextLine and nextAnythingElse is bad is a bit of a story - this SO answer explains part of it. Unfortunately the 1000-vote accepted answer is not the right solution (.useDelimiter("\\R") and then .next() to read a line is the right solution).
I am recently beginning programming and cannot get my program to find a file, then read input from it. Says the file does not exist. Here is my code.
import java.util.*;
import java.io.*;
public class assignment3 {
public static void main(String args[]) throws IOException {
PrintWriter pw = new PrintWriter("C:\\file\\Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n" +
"---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.next();
File f = new File(filename);
System.out.println(f);
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
At line Scanner inputfile = new Scanner(f);. The error mentioned appears. Also when prompted to type in the file name in the program, i put "C:/Games.txt".....but when i got the filename to be printed out the filename is registerd as C:\Games.txt....why is the forward slash turning into a backslash. Thank you for taking the time to help me.
Make sure the folder named "file" exists (for creating a file). It might throw that error if it's not there. For reading you need to have the proper rights.
why is the forward slash turning into a backslash?
Because you're on Windows, and directories are natively separated by a \
Next, you don't appear to be writing with your PrintWriter. And if you want to check for a file that exists, call File#exists().
File f = new File(filename);
if (f.exists()) {
System.out.println(f);
Scanner inputFile = new Scanner(f);
while (inputFile.hasNextLine()) {
System.out.println(inputFile.nextLine());
}
} else {
System.out.println(f.getPath() + " does not exist");
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Answer {
public static void main(String args[]) throws IOException, FileNotFoundException {
// Have to throw a FileNotFoundException just in case an error occurs the compiler needs to know how to process the error.
PrintWriter pw = new PrintWriter("C:/file/Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out
.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n"
+ "---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.nextLine(); //Input for strings
System.out.println(filename);
File f = new File("C:/file/"+filename+".txt"); //Must have a location for your files
f.createNewFile(); //The file's pathname is the only thing that you can supply when you instantiate the object
//you actually have to invoke the createNewFile method upon the object.
if(f.exists()) { //Don't be afraid to check your code this is a must for every programmer.
System.out.println("Good! The File Exists");
}
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
When you create a file you always have to throw a FileNotFoundException if you do not the compiler will not know what to do if the error occurs. Use / when specifying directories of files.
\ is generally used as an escape sequence and when you type this \ \ your basically telling it to escape itself this code is useful in other situations but not this one.
You can NOT create a new file by the initiation of the object you always have to invoke the createNewFile method upon the object so that you can create a new file. This is because no constructors automatically call the createNewFile method in the class. You might be wondering what the words in the parameter are, they just serve the purpose of naming the file directory. I have found a helpful link if you want to review creating Files. Just look under the constructors tab. API Files Class
BE SURE! to always check your code, it does not matter how good of a programmer you are. You ALWAYS have to check for errors and if you make a game, and don't know where the error is among the millions of lines of code. You are going to have a hell of a time.
Lastly, I was not sure what you were trying to do after the if statement, but you will receive an error after the if statement, so if you want to ask me how to help with that just type in the comments of my post.
I'm working on a school programming lab and I've gotten stuck. The book is not too helpful in teaching how to format I/O properly, or at least I'm not understanding it properly. I need a bit of help getting on with the next steps, but here's the full requirements of the program I'm supposed to be making:
A hotel salesperson enters sales in a text file. Each line contains
the following, separated by semicolons: The name of the client, the
service sold (such as Dinner, Conference, Lodging, and so on), the
amount of the sale, and the date of that event. Write a program that
reads such a file and displays the total amount for each service
category. Display an error if the file does not exist or the format is
incorrect. In addition to the program specifications listed, your
program should both print the results as well assend the results to a
separate output file.
Example of input.txt:
Elmer Fudd;Lodging;92.00;11-01-2014
Elmer Fudd;Conference;250.00;11-02-2014
Daffy Duck;Dinner;19.89;11-02-2014
Daffy Duck;Conference;275.00;11-02-2014
Mickey Mouse;Dinner;22.50;11-02-2014
Mickey Mouse;Conference;275.00;11-02-2014
I'm currently stuck on figuring out how to get the file properly loaded and formatted, which I think I did right, but then my professor suggested breaking each into it's own line, but nowhere in my book does it clearly tell how to do that. Just to be clear, I'm not looking for a coding miracle, I just would like someone to help guide me in the right direction as to what I should do next. Possibly a better way to handle this situation in a nicely detailed guide? Nothing fancy though. Thank you in advance, and here's my current code.
import java.util.*;
import java.io.*;
public class Sales
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter("output.txt");
double dinnerTotal = 0;
double conferenceTotal = 0;
double lodgingTotal = 0;
Scanner lineScanner = new Scanner(inputFile);
lineScanner.useDelimiter(";");
while (lineScanner.hasNext())
{
String line = in.nextLine(); //Here's where I'm really stuck
System.out.print(line); //Not to say I'm not stumped all over.
}
in.close();
out.close();
lineScanner.close();
}
}
From what Jason said, I'm at this now:
import java.util.*;
import java.io.*;
public class Sales
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter("output.txt");
double dinnerTotal = 0;
double conferenceTotal = 0;
double lodgingTotal = 0;
while (in.hasNext())
{
String line = in.nextLine();
String[] parts = line.split(";");
if(parts[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(parts[2]);
}
}
in.close();
out.close();
}
}
Stick to one scanner.
Read each line in total, rather than breaking on the ';'.
Then use String.split() to break the line of text apart at the ';' separator.
Then check the second part (zero based index) to retrieve the service category and add the value in the third part to the relevant total.
String line = in.nextLine();
String[] parts = line.split(";");
if(parts[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(parts[2]);
}
I'm utterly lost in Arrays and need help...Here is the end objective of this program....
In a file called AccountArray.java, write a client program (your main method) that reads from the file called customers.txt. Read the first number in the file and create an
array of Account objects, with that number of elements. Use a “for” loop to create an Account object for each line of information you read from the file and store that into an element of the array
Here's where I am at so far... my main concern is the FileNotFound Exception Error.... I have a file named customers.txt saved in the program folder but do I need to initialize it somehow or something?
Any other input regarding things I am doing wrong in this program would be greatly accepted, I'm just beginning to learn this stuff.
public class AccountArray {
/**
* #param args
*/
public static void main(String[] args) {
List<Account> accountsArray = new ArrayList <Account>();
String name, accountnumber, balance;
Scanner diskScanner = new Scanner(new File("customers.txt"));
Scanner scanner= new Scanner ("customers.txt");
scanner.useDelimiter(" ");
int objects= scanner.nextInt();
Account[] accounts=new Account[objects];
while (objects>0){
name = scanner.nextLine();
accountnumber = scanner.nextLine();
balance = scanner.nextLine();
for(int i = 1; i < objects; i++) {
accountsArray.add(new Account(i, name, accountnumber, balance));
}
objects=objects-1;
System.out.println(name+ " " + accountnumber + " " + balance +"\n"); }// just for debugging
}
}
sample of file :
4
John Anderson
4565413
250.00
Louise Carter
2323472
1250.45
Paul Johnson
7267881
942.81
Sarah Wilson
0982377
311.26
Well, first of all, you're using the wrong Scanner object:
Scanner diskScanner = new Scanner(new File("customers.txt")); // Scans through your file --Use this one
Scanner scanner= new Scanner ("customers.txt"); // Scans through the String "customers.txt" --Not helpful
To fix the FileNotFound Exception, you need to move the file customers.txt to the folder that is output by new File("customers.txt").getAbsoultePath(); as suggested by Freaky Thommi.
You will also run into a few other errors further down, but I'll let you figure those out on your own...
Is this run form eclipse. If yes you need to have this file under your project root folder. You can always find out the absolute path by using
new File("customers.txt").getAbsoultePath();
Print this to console and see if file is present at this location
I'm currently attempting to write a program that can scan a text document and replace a specified word / string / whatever with another phrase, specifically using the classes Scanner and Printwriter. Unfortunately, I'm having a little bit of trouble finding the correct methods to use and how exactly to implement them. Here's my code:
class Redaction {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the filename of the sensitive information");
String f = input.next();
System.out.println("Please input what text you want 'lost'");
String o = input.next();
System.out
.println("Please input what you want the new, improved filename to be called");
String n = input.next();
File sensitiveDocument = new File(f);
if (!sensitiveDocument.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}
Scanner in = new Scanner(sensitiveDocument);
in.useDelimiter("[^A-Za-z]+");
PrintWriter out = new PrintWriter(n);
while (in.hasNext()) {
if (in.hasNext(o)) {
// ...
}
}
in.close();
out.close();
}
}
I'm pretty lost at this point. Any help would be much appreciated.
Start by reading PrintWriter and Scanner documentation, to decide which methods to use.
Pseodo code:
Get line by line (or word by word, depends on what you want to remove).
look for the string you want to remove
if the string contains the content to remove, remove it.
print the string to the file.
The simplest although not so efficient algorithm would be to read the contents of the file into a string variable. After which you could use a String Tokenizer to find and replace the word you don't want with the word you want and rewriting the contents of the variable back into the file.