14 Replies - 5084 Views - Last Post: 23 January 2011 - 04:25 PM Rate Topic: -----

#1 gemoney  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 112
  • Joined: 30-October 09

Two Dimensional Array & User Prompt

Posted 21 January 2011 - 03:20 PM

I am writing a program which should:
1.) Prompt user for the file name to be created
2.) Collect sales data for 4-weeks from the user
3.) read the data into two-dimension array and do some calc.

How do I prompt a user for file name and create it? Here is the code I use, but not competely correct:
  public static void readFile()
            throws FileNotFoundException {
        System.out.print("Enter file name and extension" );
        String fileName = input.nextLine();
        File inputFile = new File(fileName);
        Scanner reader = new Scanner(inputFile);
        while(reader.hasNext()){
            store.add(reader.nextInt());
        }

    }


And how do I put all 4 weeks info in a nested for loop instead of having individual loops?
System.out.print("\nEnter WEEK 1 sales with spaces(e.g: 12 56 23........)"
                + " after each Daily Sales Numbers:");
        int count=0;
        for (int i=0; i <= 4; i++){
            for(int j=0; i <= 7; j++){
            week1 = input.nextInt();
            count=0;
           // System.out.print(week1 + " ");
            }
        input.nextLine();
        System.out.println(count+"\n");
        }

thanks!!

Is This A Good Question/Topic? 0
  • +

Replies To: Two Dimensional Array & User Prompt

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2198
  • View blog
  • Posts: 5,226
  • Joined: 10-September 10

Re: Two Dimensional Array & User Prompt

Posted 21 January 2011 - 10:41 PM

Why is the first code snippet incorrect? Are you getting errors? Is it not doing what you want it to? Explain what's wrong.

Explain also what the file is being used for. Your problem statement is not clear on the file's purpose.

Your second question is unclear. The user needs to enter 4 weeks worth of data, so your program needs to explain how to do that and then be designed accordingly. Is it expecting 7 numbers on a single line for total sales each day of the week repeated 4 times? Once you decide how the user enters the data, the program design will follow (or vice versa).
Was This Post Helpful? 0
  • +
  • -

#3 gemoney  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 112
  • Joined: 30-October 09

Re: Two Dimensional Array & User Prompt

Posted 22 January 2011 - 07:56 AM

The first code snippet I am getting an error at this line. So I can't test the program:
  store.add(reader.nextInt()); 


The second question: I will have 4 weeks of data totally 28 integers with 7 integers per line. I have the code written in this way:
System.out.println("Enter the number of sales for each week STARTING"
                           + " with SUNDAY sale number");
        System.out.print("\nEnter WEEK 1 sales with space(e.g: 12 56 23........)"
                + " after each Daily Sales Numbers:");
  
        for (int i=0; i <= 7; i++){            
            week1 = input.nextInt();
            System.out.print(week1 + " ");
        input.nextLine();
        }
        System.out.println("");

        System.out.print("Enter WEEK 2 sales with space(e.g: 12 56 23........)"
                + " after each Daily Sales Numbers:");
        for (int i=0; i <= 7; i++){
            week2 = input.nextInt();
            System.out.print(week2 + " ");
        }
        System.out.println("");
        System.out.print("Enter WEEK 3 sales with space(e.g: 12 56 23........)"
                + " after each Daily Sales Numbers:");
        for (int i=0; i <= 7; i++){
            week3 = input.nextInt();
            System.out.print(week3 + " ");
        }
        System.out.println("");
        System.out.print("Enter WEEK 1 sales with space(e.g: 12 56 23........)"
                + " after each Daily Sales Numbers:");
        for (int i=0; i <= 7; i++){
            week4 = input.nextInt();
            System.out.print(week4 + " ");
        }

I would like to shorten this code with a nested loop into a few lines instead of having all those for loops.
Then later I would have to use 2D array to get the total and avg by weeks and by days like sundays, mondays....but I have got to this point yet.
Was This Post Helpful? 0
  • +
  • -

#4 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2198
  • View blog
  • Posts: 5,226
  • Joined: 10-September 10

Re: Two Dimensional Array & User Prompt

Posted 22 January 2011 - 10:10 AM

When you're getting errors that you want help with, please post the errors, cut and pasted, and then point us to the same line number in the code you post as you've already done. So, post the error.

For your second question, since you're essentially doing the same thing 4 times, you can put that in a loop that executes 4 times. Use the loop's counter to provide any changes necessary. For example, in your instructions to your user than include the number of the week, use the loop counter to output the number of the week being input.
Was This Post Helpful? 0
  • +
  • -

#5 moobler  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 143
  • View blog
  • Posts: 224
  • Joined: 21-January 11

Re: Two Dimensional Array & User Prompt

Posted 22 January 2011 - 10:33 AM

As far as using a two-dimensional array goes, you know that you will be reading in 4 weeks of information, each of which contains 7 days. So let's use a 4x7 array:
int[][] sales = new int[4][7];


Now when you want to store or access information, you can address it as sales[week][day].
// Store a sales number of 10 in the first day of the first week (remember that array indices start at 0, not 1).
sales[0][0] = 10;

// Display information about a particular day.
System.out.println("Sales for week 2, day 7: " + sales[1][6]);


Was This Post Helpful? 0
  • +
  • -

#6 gemoney  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 112
  • Joined: 30-October 09

Re: Two Dimensional Array & User Prompt

Posted 22 January 2011 - 11:24 AM

View Postmoobler, on 22 January 2011 - 10:33 AM, said:

As far as using a two-dimensional array goes, you know that you will be reading in 4 weeks of information, each of which contains 7 days. So let's use a 4x7 array:
int[][] sales = new int[4][7];


Now when you want to store or access information, you can address it as sales[week][day].
// Store a sales number of 10 in the first day of the first week (remember that array indices start at 0, not 1).
sales[0][0] = 10;

// Display information about a particular day.
System.out.println("Sales for week 2, day 7: " + sales[1][6]);



Thanx moobler but i am not even at the array part yet
Here is my program below....I can't get the program to accept the file name I am giving it. Without that first part I can't store the 28 integers b/c there is no file created for it.
 public class WeeklySales {
   static Scanner input = new Scanner(System.in);
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
                    throws FileNotFoundException{
        int week1=0;
        int week2=0;
        int week3=0;
        int week4=0;


        ArrayList <Integer> store = new ArrayList<Integer>();
        System.out.print("Enter file name and extension: " );
        String fileName = input.nextLine();
        File inputFile = new File(fileName);
        Scanner reader = new Scanner(inputFile);

        while(reader.hasNext()){
           store.add(reader.nextInt());

        }
     
        System.out.println("Enter the number of sales for each week STARTING"
                           + " with SUNDAY sale number");
        System.out.print("\nEnter WEEK 1 sales with space(e.g: 12 56 23........)"
                + " after each Daily Sales Numbers:");
  
        for (int i=0; i < 7; i++){
            week1 = input.nextInt();
            System.out.print(week1 + " ");
        input.nextLine();
        }
        System.out.println("");

        System.out.print("Enter WEEK 2 sales with space(e.g: 12 56 23........)"
                + " after each Daily Sales Numbers:");
        for (int i=0; i < 7; i++){
            week2 = input.nextInt();
            System.out.print(week2 + " ");
        }
        System.out.println("");
        System.out.print("Enter WEEK 3 sales with space(e.g: 12 56 23........)"
                + " after each Daily Sales Numbers:");
        for (int i=0; i < 7; i++){
            week3 = input.nextInt();
            System.out.print(week3 + " ");
        }
        System.out.println("");
        System.out.print("Enter WEEK 1 sales with space(e.g: 12 56 23........)"
                + " after each Daily Sales Numbers:");
        for (int i=0; i < 7; i++){
            week4 = input.nextInt();
            System.out.print(week4 + " ");
        }
        System.out.println("");
        

       
       /* int[][] dailySales = new int[4][7];
        for(int i=0; i < dailySales.length; i++){
            for(int j=0; j < dailySales.length; j++){
            }
        }*/

    }
}


I believe the error is at this part of the program here:
  ArrayList <Integer> store = new ArrayList<Integer>();
        System.out.print("Enter file name and extension: " );
        String fileName = input.nextLine();
        File inputFile = new File(fileName);
        Scanner reader = new Scanner(inputFile);

        while(reader.hasNext()){
           store.add(reader.nextInt());

        }


My error:
Enter file name and extension: test
Exception in thread "main" java.io.FileNotFoundException: test (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.util.Scanner.<init>(Scanner.java:636)
at weeklysales.WeeklySales.main(WeeklySales.java:31)
Java Result: 1

My Debugger gives this code and others, but specifically points to this line:
  public FileInputStream(File file) throws FileNotFoundException {
	String name = (file != null ? file.getPath() : null);
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkRead(name);
	}
        if (name == null) {
            throw new NullPointerException();
        }
	fd = new FileDescriptor();
	open(name);
    }


This is why I believe the way I am trying to create and store the files is incorrect. So the URL I have been to regarding this Matter and even run some of those codes and still get an error like mine. So I am not sure what i am doing wrong apart from not outputing the datas from each week to be store yet, which I can't do with first creating the file to be store.
http://www.dreaminco..._1&#entry827124
http://www.dreaminco..._1&#entry864680
http://www.dreaminco..._1&#entry935626
http://www.dreaminco..._1&#entry950806
http://www.dreaminco...1&#entry1222670
http://www.dreaminco..._1&#entry452905
http://www.dreaminco...or-a-file-name/

This post has been edited by gemoney: 22 January 2011 - 11:27 AM

Was This Post Helpful? 0
  • +
  • -

#7 moobler  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 143
  • View blog
  • Posts: 224
  • Joined: 21-January 11

Re: Two Dimensional Array & User Prompt

Posted 22 January 2011 - 11:39 AM

Have you actually created a file called "test" yet? If the Scanner class tries to open a file that doesn't exist it will throw that FileNotFoundException. To remedy this you can tell Java to try to create the file if it doesn't exist:

File inputFile = new File(fileName);
inuptFile.createNewFile();
Scanner reader = new Scanner(inputFile);
...


This may not be the best solution, since now you can end up with an empty file from which you are trying to read sales numbers.

Now if you already have a file called "test" and your program simply isn't finding it, you can try putting in a debug output line like this:
File inputFile = new File(fileName);
System.out.println(inputFile.getAbolutePath());


This will print out the exact location of where it is looking for the file. If this location is not where you expect it to be, you can make changes to the construction of inputFile to make it fit.
Was This Post Helpful? 1
  • +
  • -

#8 gemoney  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 112
  • Joined: 30-October 09

Re: Two Dimensional Array & User Prompt

Posted 22 January 2011 - 11:57 AM

View Postmoobler, on 22 January 2011 - 11:39 AM, said:

Have you actually created a file called "test" yet? If the Scanner class tries to open a file that doesn't exist it will throw that FileNotFoundException. To remedy this you can tell Java to try to create the file if it doesn't exist:

File inputFile = new File(fileName);
inuptFile.createNewFile();
Scanner reader = new Scanner(inputFile);
...


This may not be the best solution, since now you can end up with an empty file from which you are trying to read sales numbers.

Now if you already have a file called "test" and your program simply isn't finding it, you can try putting in a debug output line like this:
File inputFile = new File(fileName);
System.out.println(inputFile.getAbolutePath());


This will print out the exact location of where it is looking for the file. If this location is not where you expect it to be, you can make changes to the construction of inputFile to make it fit.


I get your point, but the instruction states: Your program must prompt for the file designation ( This will be entered as a single string both the file name and the extension if necessary.)
I will try the codes you gave and see what the outcome is for both.....Thanks
Was This Post Helpful? 0
  • +
  • -

#9 gemoney  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 112
  • Joined: 30-October 09

Re: Two Dimensional Array & User Prompt

Posted 22 January 2011 - 03:33 PM

How do I write to a txt file just created in the program? I have tried
fileName.print(week1);

and inputFile.print(week1) but I am getting an error from the print statement "cannot find symbol. How do I call the file to be written to?
 public static void readFile()
                    throws FileNotFoundException {
            int week1=0;
             try {
        ArrayList <Integer> store = new ArrayList<Integer>();
        System.out.print("Enter file name and extension: " );
        String fileName = input.nextLine();
        File inputFile = new File(fileName);
        inputFile.createNewFile();
        Scanner reader = new Scanner(inputFile);

        System.out.println("Enter the number of sales for each week STARTING"
                           + " with SUNDAY sales number");
        System.out.print("\nEnter WEEK 1 sales: ");
        for (int i=0; i < 7; i++){
            week1 = input.nextInt();
            fileName.print(week1);
            input.nextLine();
        }
         while(reader.hasNext()){
            store.add(reader.nextInt());
         }
   
            } catch (IOException ex) {
            ex.printStackTrace();}
      }


Was This Post Helpful? 0
  • +
  • -

#10 moobler  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 143
  • View blog
  • Posts: 224
  • Joined: 21-January 11

Re: Two Dimensional Array & User Prompt

Posted 22 January 2011 - 03:37 PM

Take a look at this tutorial: Reading And Writing To A File In Java
Was This Post Helpful? 1
  • +
  • -

#11 gemoney  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 112
  • Joined: 30-October 09

Re: Two Dimensional Array & User Prompt

Posted 23 January 2011 - 09:46 AM

I have been at this for days. i can't figure out why the array isn't passing all the integers to be sum correclt. Plus when it does sum up the rows and columns it stops at 4 for both and the sum number is incorrect....I will would appreciated any help.
 //This how I am calling the methods
                    getNums(new File(fileName));
                   readNums = getNums(new File(fileName));
                   sumNumbers(readNums);
                    } 
      }
       public static int[][] getNums(File fileName)
                        throws FileNotFoundException{
            Scanner inFile = new Scanner(new FileReader(fileName));
            int[][] dailySales = new int[4][7];//Array to read all the 28 integers
            for (int row = 0; row < dailySales.length; row++) {
                for(int col=0; col < dailySales.length; col++){
                if (!inFile.hasNextInt())
                break; // stop reading if no more...
                dailySales[row][col] = inFile.nextInt();
                }
            }
          return dailySales;
        }
        public static void sumNumbers(int[][] dailySales)
                        throws FileNotFoundException{
           int sum=0;
           for (int row = 0; row < dailySales.length; row++) {
                sum=0;
                for(int col=0; col < dailySales[row].length; col++){
                    sum=sum + dailySales[row][col];                   
                }
                 System.out.println((row + 1) + " = " + sum);
            }//end sum by roow

           System.out.println("");
           for (int col = 0; col < dailySales[0].length; col++) {
                sum=0;
                for(int row=0; row < dailySales.length; row++){
                    sum=sum + dailySales[row][col];
                }
                 System.out.println((col + 1) + " = " + sum);
            }
        }


The integers by user input:
11 22 33 44 55 66 77
88 99 90 99 88 77 66
55 44 33 22 11 11 22
33 44 55 66 77 88 99

Sum by Rows output:
1 = 110
2 = 286
3 = 376
4 = 242

Sum by Columns output:
1 = 242
2 = 244
3 = 264
4 = 264
5 = 0
6 = 0
7 = 0
Was This Post Helpful? 0
  • +
  • -

#12 moobler  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 143
  • View blog
  • Posts: 224
  • Joined: 21-January 11

Re: Two Dimensional Array & User Prompt

Posted 23 January 2011 - 09:51 AM

The part about stopping at 4 is an easy solution. When you read in your information from the file you use:
for (int row = 0; row < dailySales.length; row++) {
for(int col=0; col < dailySales.length; col++){


As you already figured out in the loops below that, you need to be sure to use dailySales[0].length to get the column size.
Was This Post Helpful? 0
  • +
  • -

#13 gemoney  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 112
  • Joined: 30-October 09

Re: Two Dimensional Array & User Prompt

Posted 23 January 2011 - 10:49 AM

View Postmoobler, on 23 January 2011 - 09:51 AM, said:

The part about stopping at 4 is an easy solution. When you read in your information from the file you use:
for (int row = 0; row < dailySales.length; row++) {
for(int col=0; col < dailySales.length; col++){

I don't understand your point. I thought thats what I was doing with this method:
  public static int[][] getNums(File fileName)
                        throws FileNotFoundException{
            Scanner inFile = new Scanner(new FileReader(fileName));
            int[][] dailySales = new int[4][7];//Array to read all the 28 integers
            for (int row = 0; row < dailySales.length; row++) {
                for(int col=0; col < dailySales.length; col++){
                if (!inFile.hasNextInt())
                break; // stop reading if no more...
                dailySales[row][col] = inFile.nextInt();
                }
            }
          return dailySales;
        }


Quote

As you already figured out in the loops below that, you need to be sure to use dailySales[0].length to get the column size.

And the same with the columns:
 for (int col = 0; col < dailySales[0].length; col++) {
                sum=0;
                for(int row=0; row < dailySales.length; row++){
                    sum=sum + dailySales[row][col];
                }
                 System.out.println((col + 1) + " = " + sum);
            }
        }

Was This Post Helpful? 0
  • +
  • -

#14 moobler  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 143
  • View blog
  • Posts: 224
  • Joined: 21-January 11

Re: Two Dimensional Array & User Prompt

Posted 23 January 2011 - 12:39 PM

In the first loop where you are reading in the information about the columns you are only reading in the first four values, since your end condition is col < dailySales.length. It should be col < dailySales[0].length just like the other nested loops you use.
Was This Post Helpful? 1
  • +
  • -

#15 gemoney  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 112
  • Joined: 30-October 09

Re: Two Dimensional Array & User Prompt

Posted 23 January 2011 - 04:25 PM

Thanks Moobler.....that fixed it. I wouldn't have guess that....
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1