Link to home
Start Free TrialLog in
Avatar of Talulia
Talulia

asked on

I/O Exception

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

Avatar of sciuriware
sciuriware

Homework!   Homework!   Homework!   Homework!   Homework!   Homework!   Homework!   Homework!  
Avatar of Talulia

ASKER

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;
}

}
}
Avatar of Talulia

ASKER

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

Avatar of Talulia

ASKER

Sorry, meant to say it doesn't show up in my wordpad/notepad.
Avatar of CEHJ
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

Avatar of Talulia

ASKER

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
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

Avatar of Talulia

ASKER

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

Avatar of Talulia

ASKER

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

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!
ASKER CERTIFIED SOLUTION
Avatar of spoxox
spoxox
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial