Here\'s a snippet of the file (almost completed no one has answered previous que
ID: 3675280 • Letter: H
Question
Here's a snippet of the file (almost completed no one has answered previous question yet) I want to know how I can adjust the print function when n = 4 so that it prints what the printwriter writes to the file. I believe it is giving me instead the address in memory (java.io.PrintWriter@4577357d). I just need to know how to fix this snippet of code to print out the document just assume everything else is okay!
if (n == 3)
{
int d = 0;
int e = 0;
int cid = 0;
int iid = 0;
System.out.println("Please enter a customer id: ");
cid = scan.nextInt();
System.out.println("Please enter an item id");
iid = scan.nextInt();
while (inputCustomer.hasNextLine())
{
int idNum = inputCustomer.nextInt();
String Last = inputCustomer.next();
String First = inputCustomer.next();
String Zip = inputCustomer.next();
if (idNum == cid)
{
d++;
}
}
while (inputItem.hasNextLine())
{
int id = inputItem.nextInt();
String description = inputItem.next();
if (id == iid)
{
e++;
}
}
if (d == 0)
{
System.out.println("Invalid Customer ID. Record Not Added.");
}
if (e == 0)
{
System.out.println("Invalid Item ID. Record Not Added.");
}
if (d > 0 && e > 0)
{
recordsFile.println(cid + " " + iid);
recordsFile.flush();
recordsFile.close();
count++;
System.out.println("Record Added!");
}
}
if (n == 4)
{
if (count >= 1)
{
System.out.println(recordsFile.toString());
}
else
{
System.out.println("No Records Found");
}
}
Explanation / Answer
Short answer: you can't. You've created a PrintWriter that writes direct to System.out.
It doesn't store the text you write to it, it just writes it out to System.out.
Longer answer: but if you want to create a different PrintWriter, write to that, and then get the contents as a String, you can do that. What you can do is use the StringWriter class. That's a Writer class that adds everything to a string buffer, and you can then get the contents. Once you've created that, you can wrap it in a PrintWriter.
For example:
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
// ...code where you write to writer...
System.out.println(stringWriter.toString());