Solved

I/O Exception

Posted on 2007-11-22
12
230 Views
Last Modified: 2013-11-23
DIRECTIONS:
The file must be called week5.java
Ensure you include ALL files required to make your program compile and run. I would like to see your .java files only.

week5.java Class File
Write a program that will get input from the keyboard to create a shopping list and write it to a text file.
Program must contain 2 methods (inputItems and outputItems)
Both methods MUST be inside the same class file.
Call inputItems
Call outputItems
Exit

week5.java (inputItems Method)
Get Input for shipping items from the keyboard.
Prompt me to enter more items. Keep getting input until I enter 'No'.
(See example below)
Once input is complete, it should be store in a text file called 'shoppinglist.txt'. This file should be stored in the same directory as the main program. (not on a floppy)
File should be in text file format, not binary format.

week5.java (outputItems Method)
Re-open text file ('shoppinglist.txt') and output file to screen.
Output should contain items entered in input method.
(See example below)


Example output of your program
Example Run:

This program will create a shopping list:
Please enter your first item: Ham

Do you wish to enter More Items? Yes/No: Yes
Enter your next item: Cheese

Do you wish to enter More Items? Yes/No: No

Your shopping list contains:
Ham
Cheese
 


Here is what I have. I need help changing this so it meets the requirements.


import java.io.*;

import java.util.*;
 

public class week5

{

	public static void main(String[] args)

	{

		System.out.println("This program will create a shopping list.");

		

		PrintWriter outputStream = null; //Declared outside the try block
 

		try

		{

			outputStream = new PrintWriter(new FileOutputStream("shoppinglist.txt"));

		}

		catch(FileNotFoundException e)

		{

			System.out.println("Error opening the fileout.txt.");

			System.exit(0);

		}
 

		System.out.println("\nPlease enter your first item:");
 

		String line = null;

		Scanner keyboard = new Scanner(System.in);

		int count;

		for (count = 1; count <= 3; count++)

		{

			line = keyboard.nextLine();

			outputStream.println(count + " " + line);

		}

		outputStream.close();

		System.out.println("Those lines were written to shoppinglist.txt.");

	}

}

Open in new window

0
Comment
Question by:Talulia
12 Comments
 
LVL 24

Expert Comment

by:sciuriware
ID: 20337545
Homework!   Homework!   Homework!   Homework!   Homework!   Homework!   Homework!   Homework!  
0
 

Author Comment

by:Talulia
ID: 20337564
Okay here is an update. It will not read in my textpad. It also does not show the results at the end.

import java.io.*; // uses the java io library for the

import java.util.*; // BufferedReader class

public class week5_701

{

public static void main(String [] args)

{

PrintWriter outputStream=null;
try

{
outputStream= new PrintWriter(new FileOutputStream("shoppinglist.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file shoppinglist.txt");
System.exit(0);
}
int items;
String line=null;
System.out.println("This program will put items in your shopping list");
Scanner keyboard= new Scanner(System.in);
boolean numbersLeft= true;
int moreitems=1;
while (numbersLeft)
{
System.out.println("Enter the next item");
line=keyboard.nextLine();
keyboard.nextLine();
System.out.println("Would you like to enter more items, enter 1 for yes or 0 for no");
moreitems=keyboard.nextInt();
if (moreitems==0)
{
numbersLeft=false;
System.exit(0);
}
else
numbersLeft=true;
}

}
}
0
 

Author Comment

by:Talulia
ID: 20337565
Here is code again.
import java.io.*; // uses the java io library for the
 

import java.util.*; // BufferedReader class
 

public class week5_701
 

{
 

public static void main(String [] args)
 

{
 

PrintWriter outputStream=null;

try
 

{

outputStream= new PrintWriter(new FileOutputStream("shoppinglist.txt"));

}

catch(FileNotFoundException e)

{

System.out.println("Error opening the file shoppinglist.txt");

System.exit(0);

}

int items;

String line=null;

System.out.println("This program will put items in your shopping list");

Scanner keyboard= new Scanner(System.in);

boolean numbersLeft= true;

int moreitems=1;

while (numbersLeft)

{

System.out.println("Enter the next item");

line=keyboard.nextLine();

keyboard.nextLine();

System.out.println("Would you like to enter more items, enter 1 for yes or 0 for no");

moreitems=keyboard.nextInt();

if (moreitems==0)

{

numbersLeft=false;

System.exit(0);

}

else

numbersLeft=true;

}
 

}

}

Open in new window

0
 

Author Comment

by:Talulia
ID: 20337567
Sorry, meant to say it doesn't show up in my wordpad/notepad.
0
 
LVL 9

Expert Comment

by:ysnky
ID: 20337620
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20337727
You're so nearly there. Try this:
  public static void main(String [] args)

  {

    PrintWriter outputStream=null;

    try

    {

      outputStream= new PrintWriter(new FileOutputStream("shoppinglist.txt"), true);

    }

    catch(FileNotFoundException e)

    {

      System.err.println("Error opening the file shoppinglist.txt");

      System.exit(0);

    }

    int items;

    String line=null;

    System.out.println("This program will put items in your shopping list");

    Scanner keyboard= new Scanner(System.in);

    boolean numbersLeft= true;

    int moreitems=1;

    System.out.print("Enter the next item: ");

    while (moreitems > 0  && keyboard.hasNext())

    {

      line=keyboard.next();

      outputStream.println(line);

      System.out.print("Would you like to enter more items, enter 1 for yes or 0 for no: ");

      moreitems=keyboard.nextInt();

      if (moreitems==0)

      {

        numbersLeft=false;

        System.exit(0);

      }

      else

        numbersLeft=true;

      System.out.print("Enter the next item: ");

    }

   outputStream.close();

  }

Open in new window

0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:Talulia
ID: 20337768
Program must contain 2 methods (inputItems and outputItems)
Both methods MUST be inside the same class file.
Call inputItems
Call outputItems

How do I incorporate that into my code?

Also, How do I output to the screen something like this for whatever the user inputs for the shopping list?

Your shopping list contains:
Ham
Cheese
0
 
LVL 11

Expert Comment

by:spoxox
ID: 20344136
I've added a snippet that shows a class with two (OK, three) methods that will output to the screen some text. I think this answers your questions without quite doing your homework for you.

If I don't have a "Eureka" moment when something finally or suddenly makes sense, I haven't learned anything - and this usually reveals itself as a major problem when the test comes.
import java.text.DateFormat;

import java.util.Date;
 

public class HiTal {
 

  // Write a greeting

  public static void greetingMessage(String name) {

    System.out.println("Hello, " + name + ". Good luck with learning java.");

  }
 

  // Write the date

  public static void dateMessage() {

    String today = DateFormat.getDateInstance().format(new Date());

    System.out.println("Today is " + today + ".");

  }
 

  // Program driver

  public static void main(String[] args) {

    greetingMessage("Talulia");

    dateMessage();

  }

}

Open in new window

0
 

Author Comment

by:Talulia
ID: 20344895
Okay: I am having problems getting my code to list all the items a
user enters.
System.out.print("Your shopping list contains:\n" + line + "\n");
When I do it this way it only shows the last entry the person
typed as a shopping list item.
There is something I am doing wrong, but can't figure out how to
re-word it. The moreitems==0 which throws everything off.
I'm doing it to where moreitems > 0 but these are not numbers I'm dealing with. Trying to figure out to allow my output to come out on the screen.

Also, I am supposed to use to methods within one class named inputItems and outputItems. How do I incorporate that into the code I have? I'm stuck and this is due by midnight today.
Any help, thanks.







import java.io.*;

import java.util.*;
 
 

public class week5
 

{

public static void main(String [] args)

  {

    PrintWriter outputStream=null;

    try

    {

        outputStream= new PrintWriter(new FileOutputStream("shoppinglist.txt"), true);

        }

        catch(FileNotFoundException e)

        {

            System.err.println("Error opening the file shoppinglist.txt");

            System.exit(0);

            }

            int items;
 

            String line=null;

            System.out.println("This program will create a shopping list:\n");

            Scanner keyboard= new Scanner(System.in);

            boolean numbersLeft= true;

            int moreitems=1;

            System.out.print("Please enter your first item: ");

            while (moreitems > 0  && keyboard.hasNext())

            {

                line=keyboard.next();

                outputStream.println("Please enter next item:");
 

                System.out.print("Do you wish to enter more items? 1 = yes, 0 = no. ");

                moreitems=keyboard.nextInt();

                if (moreitems>0)

                {

                    numbersLeft=false;

                    System.out.print("Your shopping list contains:\n" + line + "\n");

                    System.exit(0);

                    }

                    else

                    numbersLeft=true;

                    System.out.print("Enter the next item: ");
 
 
 

}

                    outputStream.close();

                    }

                    }

Open in new window

0
 

Author Comment

by:Talulia
ID: 20345058
1. Why doesn't this shoppinglist.txt code not output to a textfile? That was my goal to get it to do that.
2. How do I incorporate two methods named inputItems and outputItems with this already working code?
3. How do I output to the DOS screen the final results of the shopping list?


 

import java.io.*;

import java.util.*;
 
 

public class week5
 

{
 

public static void main(String [] args)
 

  {

    PrintWriter outputStream=null;
 
 

	try
 

	{

		outputStream= new PrintWriter(new FileOutputStream("shoppinglist.txt"));
 

		}
 

		catch(FileNotFoundException e)
 

		{

			System.err.println("Error opening the file shoppinglist.txt");
 

			System.exit(0);
 

			}
 
 

			boolean done=false;

			String input = null;

			String ans = null;
 

			System.out.println("This program will create a shopping list:\n");
 

			Scanner keyboard = new Scanner(System.in);
 

			System.out.print("Enter your item: ");
 

			input = keyboard.nextLine();
 

			System.out.print("Do you wish to enter more items? y/n ");
 

			ans = keyboard.nextLine();
 
 

			while(!done)

			{

				if (ans.equalsIgnoreCase("y"))

				{

					System.out.println("Thank you, please enter another item.");

					input = keyboard.nextLine();

					System.out.println("Do you wish to enter other items? y/n:");

					ans = keyboard.nextLine();

					ans.equalsIgnoreCase("y");

					done=false;

				}

				if (ans.equalsIgnoreCase("n"))

				{

					System.out.println("Thank you for your entries. You can find the file shoppinglist.txt located in your textfile. ");

					done=true;

				}

			}
 
 
 
 

			outputStream.close();
 

			}
 

			}

Open in new window

0
 
LVL 11

Expert Comment

by:spoxox
ID: 20345067
Just three little problems to solve! Take them one at a time, and you'll get there.

1) The output shows only the last item entered.
The program is not storing the previous items. You may have come across some kind of data thing that allows storage of multiple occurrences of related objects of the same type. Say you want a list of 10 numbers, you wouldn't use int num1, num2, num3, .... When you know how to store each input, you will have to figure out how to process your new data structure, but that's pretty common stuff.

2) moreitems==0
The program seems to have amalgamated a few different ideas on how to control the loop iterations and exit. It checks moreitems and keyboard.hasNext, and it's setting a numbersLeft switch that is never examined. And it makes life a little more complicated for the user who has to type in chicken 1 duck 1 eggs 1 milk 0. It would be simpler to lose the number scheme altogether, don't you think? You would probably need some String code like "quit" to signal that the shopper was finished entering data.

But that still doesn't get you through your loop control problem.

Suppose the loop is something like this:

while ( shopperWantsToContinue() )   {
/* shopperWantsToContinue might mean shopper entered a 0 in the old scheme, or however else you choose to handle it */
...
/* Here you need to do a few small things.
You need to find out what your shopper wants - an item or to quit. If it's an item, you need to remember it somehow. In either case, make sure your loop exit condition is set properly.
*/
}

The problem this bit still has highlights a minor inelegance in programming languages. When you reach the loop for the first time, you need to already know whether the shopper wants to continue....


3) inputItems and outputItems
Adding these methods is really simple. The question is what do they do? I think the outputItems one is clear: it must be writing the shopping list. (Somehow you remembered those "multiple occurrences of related objects of the same type".)

inputItems... I'm thinking that means one of two things - but I'm guessing for your course it doesn't matter too much which way you go. So inputItems could have the job of getting the user input...or maybe the (simpler?) job of just remembering what the user typed.

Again, break it down into smaller, manageable pieces. (That third thing is two pieces!) You're most of the way there. Good luck!
0
 
LVL 11

Accepted Solution

by:
spoxox earned 125 total points
ID: 20345866
Aha. Talulia and I were adding posts simultaneously. My last was to answer T's second last. Hope there was no confusion.

Loop control problem solved! Good work.

"1. Why doesn't this shoppinglist.txt code not output to a textfile? That was my goal to get it to do that."
You do create/open an output file:
      outputStream = new PrintWriter(new FileOutputStream( "shoppinglist.txt"));
And you close it later:
      outputStream.close();
But there are other file operations required! Check out the documentation for the PrintWriter class (of which System.out is a member) to find other methods you can use to put data into your file. (Note: OutputStream, with an upper case "O", is another java Class. It might be a little clearer to rename your PrintWriter.)

2. How do I incorporate two methods named inputItems and outputItems with this already working code?
Piece of cake. Just stuff 'em in the same file, inside the class, outside the method "main". Of course, to properly identify the signature (name and parameter list) and the return type, you'll need to decide what you want your methods to do for you. So figure this out: what do you want your methods to do for you?

3. How do I output to the DOS screen the final results of the shopping list?
Once you've solved problem 1 and written some data to your file, navigate to it using Explorer or DOS or whatever you use, open it in an editor like Notepad or use the DOS "type" command. (You can do it now, but you have an empty file.)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now