Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: Help with a beginner's java assignment: Survey results

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Red face Help with a beginner's java assignment: Survey results

    (This is my first time posting here, so I hope that I have the right place! Also, I haven't been programming very long, so I'm sorry if I am not using the right terminology. Feel free to correct me, though. That way I'll learn!)

    Basically, what I'm trying to do is write a program that will read a text file of survey results, and send those results to a graphics window that has been separated into rectangles (each row represents a question, and each column will represent the answer, ranging from agree to disagree. Each answer is designated a number).The first rectangle in the row is supposed to have be labeled with the question identifier and the other rectangles are to visually show the degree of popularity of people's answers. The more popular a vote, the more intense that color is supposed to get visually.

    To try and clear up any remaining confusion on just what it is I'm dealing with, please allow for me to give you an example. If the text file I gave to Java is the following:
    ---text file starts here---
    Name: Jenny

    HAPPY: 2

    CAT_V_DOG: 1

    ---
    Name: Franky R.

    HAPPY: 2

    CAT_V_DOG: 1

    BOOKS: 2
    ---text file ends here---

    The output of this should be a graphics window separated into 3 columns and 3 rows (The final amount of questions will be known ahead of time, so that will be a constant). The rectangles of the first column, would just have the labels "HAPPY", "CAT_V_DOG", and "BOOKS". Initially, only the questions would be labeled with the rest of the canvas being black, but after a set amount of delay in milliseconds (200), the canvas would get refreshed and the third rectangle on the first row (HAPPY) and the second rectangle on the second row (CAT_V_DOG) would get filled in with blue rectangles (RGB 0,0,25) and be labeled "Jenny". There has only been 1 vote for those options cast, so the colors are relatively dim.

    After another same-length delay, the canvas would refresh and the next person's "results should be shown". Rectangles (0,2) and (1,1) would now be filled in a darker blue (RGB 0,0,50 because 2 people have "voted" for that same option), rectangle (2, 2) would be filled in a lighter blue (RGB 0,0,25 since he's the first vote for that question) and they would all now be labeled "Franky R" because he was the last person who's vote was tallied for that particular answer.

    I already have a separate class that I'm not allowed to change that opens up a graphics window with the appropriate number of rectangles. This finished class also has methods that allow for me to write labels to the graphics, a custom delay method, and several methods that allow me to set colors into specific rectangles as long as I provide a coordinate pair or to test a particular square and get the color that it has been filled with.

    I have already worked on this for quite some time and I'm feeling like I know what it is I want my program to do, but being a beginner, I don't quite know how to make Java understand. Thus far, I've been able to: create some code that can read through file and (using .split which I'm just learning about) list the test results (assuming I fed it the above file) as:

    HAPPY, 2, 2
    CAT_VS_DOG, 1, 1
    BOOKS, 2

    by printing out the Identifier + the comma-separated list of results.

    I also learned how to parse comma-separated lists into different array elements. At first my results array had only, say "2,2" listed for results[0]. I realized this would be helpful if I were writing a file, but since I would want to send each element (+ the name of the person who cast that vote) to the canvas, I would have to split them up into their own parts of the array. After much confusion and frantic researching, I am now capable of doing such a thing. For example results[0] would be 2 and results [1] would be 2 as well.

    Being a beginner, I got stuck on this project rather quickly, and my code is probably filled with needless data manipulation. I don't really know what I need, so I've been trying anything I could think of. I'm able to draw the appropriate canvas and even get all of the question identifiers to list correctly. But when it comes to getting the squares to fill blue and list the person who cast that vote, I don't even know where to start. I've been jumping around different kinds of convoluted if, while and for loops, trying arrays and attempting stacks, but I don't know what direction I should use. My code just gets more and more convoluted the more I explore different options (basically the antithesis of KISS), so I get the feeling I'm going about the problem all wrong. When I tried to set out the steps on a flow chart, it seemed pretty straightforward, but it doesn't seem like I know enough about Java at my current level to be able to do this. Then again, maybe it's just a small fix that I just can't see because I've been struggling with this code for almost a week now.

    I could really use some folks who are more experienced with Java than myself to give my some suggestions. Do you have any examples? What should I research? I really want to learn to program properly, so any help you can give me, I would be incredibly appreciative!


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,612
    My Mood
    Hungover
    Thanks
    145
    Thanked 658 Times in 563 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    The best suggestion I can give you is to break your problem up into smaller pieces. It sounds like you're already doing that to a certain extent, which is awesome, but keeping those pieces separate can be pretty tricky.

    Get all of the pieces working completely independently of each other, and when you have them all working, then try to combine them.

    At the very minimum, it sounds like you have four different steps: reading data from a file, storing data into the appropriate data structures, drawing a GUI, and drawing a GUI based on input from data structures.

    When you get stuck on a certain piece, focus only on that piece. Eliminate any extra steps, and post some runnable code that demonstrates where you got stuck.

    Hope that helps!

  3. #3
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    Thank you very much for the response! I went through my current code and tried to make it presentable. It's gone through a lot of hard times with me, so its no where near as neat and organized as I normally like my final programs to be, but hopefully it's not too confusing. I'm also including the text file I'm using and the Mosaic canvas class so that you can run the current code I'm using. This is my first time putting code online, so I hope I'm doing it right...

    First the text file. It's called sampleinput1.txt. There are more samples with a total of 10 final questions. These only have like 8 questions that were answered. The code I write should be able to handle that gracefully. (I don't know how to upload txt files here, so I'm sorry for just putting it here!!)

    From - Thu Sep 16 13:09:32 2010
    To: fakeaddress@cs.fakeuniversity.edu
    From: nobody@cs.csustan.edu (megan)
    Subject: CS2500 Hwk 2 Survey Submission
    Date: Thu, 16 Sep 2010 13:04:45 -0700 (PDT)

    Below is the result of your feedback form. It was submitted by
    megan () on Thursday, September 16, 2010 at 13:04:45
    ---------------------------------------------------------------------------


    charname: Darth Vader

    V_VS_DV: 1

    SHOES: 5

    INVIS_FLY: 2

    LIFE_FREE: 1

    COLSANDERS: 0

    VEY_APOLLO: 4

    LAK_CELTIC: 2

    CS_MAJOR: 1

    request: Submit the survey

    ---------------------------------------------------------------------------



    From - Thu Sep 16 13:44:12 2010
    To: fakeaddress@cs.fakeuniversity.edu
    From: nobody@cs.csustan.edu (Alfredo Torres)
    Subject: CS2500 Hwk 2 Survey Submission
    Date: Thu, 16 Sep 2010 13:41:32 -0700 (PDT)

    Below is the result of your feedback form. It was submitted by
    Alfredo Torres () on Thursday, September 16, 2010 at 13:41:32
    ---------------------------------------------------------------------------


    charname: Alfredo

    V_VS_DV: 2

    SHOES: 1

    LIFE_FREE: 4

    COLSANDERS: 2

    VEY_APOLLO: 5

    LAK_CELTIC: 5

    CS_MAJOR: 4

    request: Submit the survey

    ---------------------------------------------------------------------------



    From - Thu Sep 16 20:05:10 2010
    To: fakeaddress@cs.fakeuniversity.edu
    From: nobody@cs.csustan.edu (Billy Joe Jon)
    Subject: CS2500 Hwk 2 Survey Submission
    Date: Thu, 16 Sep 2010 15:26:38 -0700 (PDT)

    Below is the result of your feedback form. It was submitted by
    Billy Joe Jon () on Thursday, September 16, 2010 at 15:26:38
    ---------------------------------------------------------------------------


    charname: IDK?

    V_VS_DV: 5

    SHOES: 4

    INVIS_FLY: 2

    LIFE_FREE: 4

    COLSANDERS: 3

    VEY_APOLLO: 5

    LAK_CELTIC: 3

    CS_MAJOR: 4

    request: Submit the survey

    ---------------------------------------------------------------------------

    --This would be the end of the text file here --

    Here is the class that was provided for me by my professor. I am not to change anything in it.

    import java.awt.*;
     
    class MosaicCanvas extends Canvas {
     
       private static final int DEBUG = 0;
       protected int rows, columns;
       protected int blockWidth, blockHeight;
     
       protected Color defaultColor = Color.black;
       protected Color defaultLabelColor = Color.white;
     
       private Color[][] grid;
       private String[][] gridLabels;
       private Color[][] gridLabelsColors;
       private boolean blemished = false;
     
       public MosaicCanvas(int rows, int columns) {
          this(rows,columns,0,0);
       }
     
       public MosaicCanvas(int rows, int columns, int blockWidth, int blockHeight) {
          this.rows = rows;
          this.columns = columns;
          this.blockWidth = blockWidth;
          this.blockHeight = blockHeight;
          grid = new Color[rows][columns];
          gridLabelsColors = new Color[rows][columns];
          gridLabels = new String[rows][columns];
          for (int i = 0; i < rows; i++)
             for (int j = 0; j < columns; j++) {
                grid[i][j] = defaultColor;
    	    gridLabels[i][j] = "";
    	    gridLabelsColors[i][j] = defaultLabelColor;
    	}
          setBackground(defaultColor);
       }
     
       public Dimension getPreferredSize() {
          if (blockWidth <= 0)
             blockWidth = 10;
          if (blockHeight <= 0)
             blockHeight = 10;
          return new Dimension(columns*blockWidth, rows*blockHeight);
             // fixed July 24, 1998: order of parameters was reversed.
       }
     
       public synchronized void paint(Graphics g) {
          if (!blemished) {
             g.setColor(grid[0][0]);
             g.fillRect(0,0,getSize().width,getSize().height);
          }
          else {
             double rowHeight = (double)getSize().height / rows;
             double colWidth = (double)getSize().width / columns;
             for (int i = 0; i < rows; i++) {
                int y = (int)Math.round(rowHeight*i);
                int h = (int)Math.round(rowHeight*(i+1)) - y;
                for (int j = 0; j < columns; j++) {
                   int x = (int)Math.round(colWidth*j);
                   int w = (int)Math.round(colWidth*(j+1)) - x;
                   g.setColor(grid[i][j]);
                   g.fillRect(x,y,w,h);
                   g.setColor(gridLabelsColors[i][j]);
                   g.drawString(gridLabels[i][j],x,y+h);
     	       if (DEBUG > 0)
    		    System.out.println("paint: drawing " + gridLabels[i][j] + 
    			" at " + x + ", " + (y+h) + " in " + gridLabelsColors[i][j]);
                }
             }
     
          }
       }
     
       public synchronized void drawSquare(int row, int col) {
          double rowHeight = (double)getSize().height / rows;
          double colWidth = (double)getSize().width / columns;
          int y = (int)Math.round(rowHeight*row);
          int h = (int)Math.round(rowHeight*(row+1)) - y;
          int x = (int)Math.round(colWidth*col);
          int w = (int)Math.round(colWidth*(col+1)) - x;
          Graphics g = getGraphics();
          g.setColor(grid[row][col]);
          g.fillRect(x,y,w,h);
       }
     
       public void update(Graphics g) {
          paint(g);
       }
     
       public Color getColor(int row, int col) {
          if (row >=0 && row < rows && col >= 0 && col < columns)
             return grid[row][col];
          else
             return defaultColor;
       }
     
       public int getRed(int row, int col) {
          return getColor(row,col).getRed();
       }
     
       public int getGreen(int row, int col) {
          return getColor(row,col).getGreen();
       }
     
       public int getBlue(int row, int col) {
          return getColor(row,col).getBlue();
       }
     
       public void setColor(int row, int col, Color c) {
          if (row >=0 && row < rows && col >= 0 && col < columns && c != null) {
             grid[row][col] = c;
             blemished = true;
             drawSquare(row,col);
          }
       }
     
       public void setColor(int row, int col, int red, int green, int blue) {
          if (row >=0 && row < rows && col >= 0 && col < columns) {
             red = (red < 0)? 0 : ( (red > 255)? 255 : red);
             green = (green < 0)? 0 : ( (green > 255)? 255 : green);
             blue = (blue < 0)? 0 : ( (blue > 255)? 255 : blue);
             grid[row][col] = new Color(red,green,blue);
             drawSquare(row,col);
             blemished = true;
          }
       }
     
       public void fill(Color c) {
          if (c == null)
             return;
          for (int i = 0; i < rows; i++)
             for (int j = 0; j < columns; j++)
                grid[i][j] = c;
          blemished = false;
          repaint();      
       }
     
    //MEGAN - experimenting with Strings
       public synchronized void drawLabel(int row, int col, String lab, Color c) {
          double rowHeight = (double)getSize().height / rows;
          double colWidth = (double)getSize().width / columns;
          int y = (int)Math.round(rowHeight*row);
          int h = (int)Math.round(rowHeight*(row+1)) - y;
          int x = (int)Math.round(colWidth*col);
          int w = (int)Math.round(colWidth*(col+1)) - x;
          Graphics g = getGraphics();
          Color save = g.getColor();
          g.setColor(c);
          g.drawString(lab,x,y+h);
          gridLabels[row][col] = lab;
          gridLabelsColors[row][col] = c;
          if (DEBUG > 0)
    	  System.out.println("drawing " + lab + " at " + x + ", " + (y+h) + " in " + c);
          g.setColor(save);
          blemished = true;
       }
     
       public void fill(int red, int green, int blue) {
          red = (red < 0)? 0 : ( (red > 255)? 255 : red);
          green = (green < 0)? 0 : ( (green > 255)? 255 : green);
          blue = (blue < 0)? 0 : ( (blue > 255)? 255 : blue);
          fill(new Color(red,green,blue));
       }
     
       public void fillRandomly() {
          for (int i = 0; i < rows; i++)
             for (int j = 0; j < columns; j++) {
                int r = (int)(256*Math.random());
                int g = (int)(256*Math.random());
                int b = (int)(256*Math.random());
                grid[i][j] = new Color(r,g,b);
          }
          blemished = true;
          repaint();
       }
     
       public void delay(int milliseconds) {
          if (milliseconds > 0) {
             try { Thread.sleep(milliseconds); }
             catch (InterruptedException e) { }
          }
       }
     
    }

    And finally, here's what I've been working on. I've added what I hope to be helpful comments just to give you an idea of where I think I need to go with the code.:

    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.io.FileWriter;
     
    public class Outline{
     
    	public static final int ROWS = 10;        //you may change this value
    	public static final int COLS = 7;        //you may change this value
    	public static final int SIZE = 85;        //you may change this value
    	public static final int WAIT = 1000;        //you may change this value
    	public static final int QUESTION = 10;	//This is the total number of questions in the survey.
    	public static final int IDENTLOCALE = 0;
    	public static final Color IDENTCOLOR = Color.WHITE;
    	public static final String[] identifiers = {"V_VS_DV", "SHOES","INVIS_FLY", "LIFE_FREE",
    							"COLSANDERS","VEY_APOLLO","LAK_CELTIC","CS_MAJOR","SMILE","LOVEFIRST"};
     
     
    public static void main(String[] args)throws FileNotFoundException {
     
    	File inFile = new File("C:/Users/Irena/Desktop/Homework2/sampleinput1.txt");
    	Scanner scanner;
     
    	try {
    		scanner = new Scanner(inFile);
    	} catch (Exception e){
    		System.err.println("File not found: " + e.toString());
    		return;
    	}
     
    	//OPENS CANVAS: Works correctly 
    	Mosaic.open(ROWS,COLS,SIZE,SIZE); 
     
    	//METHOD: LABEL QUESTIONS: Works correctly
    	labelQuestions();
     
     
    	//METHOD: SENDS ANSWERS TO CANVAS: Does not work.
    	colorAnswers();
     
    	//METHOD: WRITEFILE: Does not work.
    	exportCSVFile(scanner);
     
     
    }//end of main
     
    	public static void labelQuestions(){
    		for(int i = 0; i < QUESTION; i++){
    			Mosaic.drawLabel(i, 0, identifiers[i], IDENTCOLOR);
    		}
    	}
     
     
    	/*The following method has two Strings added manually for the sake of testing. If you run it, you'll see 
    	the animation as its supposed to run. In the real version of this method, I want ansers to represent 
    	the answers given to any one of the ten questions asked. I guess that means that answers and names would be more dynamic.
    	I don't really know how to do this, though, but the testing at the very least shows that my idea of how to get 
    	the colored rectangles to look like they're growing more opaque seems to be correct.*/
    	public static void colorAnswers(){
    		String[] answers = {"4", "5", "5", "1", "4", "1"};
    		String[] names = {"Darth Vader", "Alfredo", "IDK?", "Pancho Villa", "Miguel Hidalgo", "Bob"};
    			for(int i = 1; i < 7; i++){
    				if(answers[i-1]=="0"){
    					Mosaic.getBlue(0,1);
    					Mosaic.setColor(0, 1, 0, 0, Mosaic.getBlue(0,1)+25);
    					Mosaic.drawLabel(0, 1, names[i-1], IDENTCOLOR);
    				}
    				if(answers[i-1]=="1"){
    					Mosaic.getBlue(0,2);
    					Mosaic.setColor(0, 2, 0, 0, Mosaic.getBlue(0,2)+25);
    					Mosaic.drawLabel(0, 2, names[i-1], IDENTCOLOR);
    				}
    				if(answers[i-1]=="2"){
    					Mosaic.getBlue(0,1);
    					Mosaic.setColor(0, 3, 0, 0, Mosaic.getBlue(0,3)+25);
    					Mosaic.drawLabel(0, 3, names[i-1], IDENTCOLOR);
    				}
    				if(answers[i-1]=="3"){
    					Mosaic.getBlue(0,2);
    					Mosaic.setColor(0, 4, 0, 0, Mosaic.getBlue(0,4)+25);
    					Mosaic.drawLabel(0, 4, names[i-1], IDENTCOLOR);
    				}			
    				if(answers[i-1]=="4"){
    					Mosaic.getBlue(0,1);
    					Mosaic.setColor(0, 5, 0, 0, Mosaic.getBlue(0,5)+25);
    					Mosaic.drawLabel(0, 5, names[i-1], IDENTCOLOR);
    				}
    				if(answers[i-1]=="5"){
    					Mosaic.getBlue(0,2);
    					Mosaic.setColor(0, 6, 0, 0, Mosaic.getBlue(0,6)+25);
    					Mosaic.drawLabel(0, 6, names[i-1], IDENTCOLOR);
    				}		
    				Mosaic.delay(WAIT);
    		}
    	}//end of colorAnswers
     
    	public static void exportCSVFile(Scanner scanner){
    		//I do not know how to write an array into a CSV file yet, but the following is the information I would want 
    		//to be written in the csv file.
    		//There would also be a line here, asking for the user to input the name of the csv file to be written. 
     
    		String[] results = {"","", "", "", "", "", "", "", "", "", ""};
    			while(scanner.hasNextLine()){
    			String[] line = scanner.nextLine().split(": ");
    			for(int i = 0; i < identifiers.length; i++){
    				if(line[0].equals(identifiers[i])){
    					if(!(results[i].equals("")))
    						results[i] += ", ";
    						results[i] += line[1];
    				}
    			}
    		}
     
    		for(int i = 0; i < identifiers.length; i++){
    			System.out.println(identifiers[i] + ": " + results[i]);
    		}
      }
     
     
    }//end of class

    I think right now, the hardest problem I'm having is being able to isolate the information I need from the text file that's filled with all of that needless information. Verbally, I want to tell Java that when it first reads a character name, I want it to remember that name and to attribute every following integer answer to that character name (that way I'd have 2 arrays I could feed into my colorAnswers method), until a new character name is read. But I don't now how to write that, or if that's the most elegant way of solving my problem.

    I really hope this is enough to get some helpful feedback! I could use all the help I can get!

  4. #4
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    Use a multi-dimension string array to hold the users data

    String userSurveryData = new String[3][10]; 
    //Makes a new multi-dimensional String array that allows for 3 users, and 10 answers for each user.

    All you have to do now is make a couple changes to the following loop:

    while(scanner.hasNextLine()){
                String[] line = scanner.nextLine().split(": ");
                for(int i = 0; i < identifiers.length; i++){
                    if(line[0].equals(identifiers[i])){
                        if(!(results[i].equals("")))
                            results[i] += ", ";
                            results[i] += line[1];
                    }
                }
            }

    If you're not sure what changes to make then just ask.

    PS: This is a bit off-topic, and possibly akward, are you Russian? When reading through your code I noticed the name Irena in your User directory.
    Last edited by Brt93yoda; October 12th, 2010 at 02:09 PM.

  5. #5
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    I knew it! I kept getting this idea of a multi dimensional array while I was struggling with this since I kept having to handle so much data all at once.

    Do you mind walking me through the changes I have to make? I've read up on multidimensional arrays, but I've never actually had to use them before in anything.

    (And you're close about the Russian! I'm a little Russian on my mother's side and I actually started to take Russian a few weeks ago. Nice catch!)

  6. #6
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    Ok, here we go! (keep in mind that you might have to do further editing, this is just so you get the point)

    int userCount = 0;
    String userSurveryData = new String[3][10]; 
    while(scanner.hasNextLine() && userCount < names.length){  //keeps looping until we reach the last user or the EOF accidently
              String[]  line = scanner.nextLine().split(": "); 
              for(int i = 0; i < identifiers.length; i++){
                    if(line[0].equals(identifiers[i]) && !line[1].equals("")){
                       userSurveyData[userCount][i] = line[1]; //stores the data into the correct slot
                    }
              }
            if (line[0].equals("request") && line[1].equals("Submit the survey"))  
               userCount++; //If we reach the last item, then go to the next user
    }

    If there is anything else you need help with feel free to ask.

    As for the side conversation; I'll send you a Private Message. I don't want the mods/admins to get cranky.
    Last edited by Brt93yoda; October 12th, 2010 at 06:47 PM.

  7. #7
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    Thank you for the help! I've been editing and exploring the code you gave me and I was hoping you could further explain a few more things?

    When I initially ran the code in my program, I got three errors.
    ---------

    OutlineTest.java:39: incompatible types
    found : java.lang.String[][]
    required: java.lang.String
    String userSurveryData = new String[3][10];
    ^
    OutlineTest.java:40: cannot find symbol
    symbol : variable names
    location: class OutlineTest
    while(scanner.hasNextLine() && userCount < names.length){ //keeps looping until we reach the last user or the EOF accidently
    ^
    OutlineTest.java:44: cannot find symbol
    symbol : variable userSurveyData
    location: class OutlineTest
    userSurveyData[userCount][i] = line[1]; //stores the data into the correct slot
    ^
    ---------

    The first one I solved by changing the line to String[][] userSurveyData = new String[3][10];. I hope this was the correct solution. The error message went away after I did that, but just because Java doesn't spot an error, it doesn't mean it'll run the code as I want it run.

    Now, for the second error, I think I understand the meaning at least. I haven't defined "names" anywhere so it can't find it. However, what is names supposed to be? The names of the people who took the survey? If I don't know that ahead of time, is there a way to write a method that will find those names so that "names" will have a length? The code is supposed to be able to handle files that have 3 responders or 100. I'm not entirely sure how one would write something so dynamic that it could handle such a diverse range.

    Now for the third error. I don't understand it at all. userSurveyData is defined already, so I don't get why Java can't find it. Could the error actually be with the line[1]?

    Finally, I have a question about the new String [3][10]. Is there a way to write it so that the the size of String[][] could be made to change depending on the size of the file? I read String[3][10] to mean 3 responders with 10 questions each. I can know the number of questions ahead of time (so I figure I could handle this by using a constant instead of hard coding a numerical value], but what should I do about the the number of people who responded? The file could hold any number of names and the program is supposed to be able to handle it.

    Thank you so much for the help so far! I really feel like I'm starting to get it.

  8. #8
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    I'm sorry about all of the errors. I was at the campus and I didn't have an IDE OR a compiler at hand. I had to write it all in the forum chat box. I'm going to fix all of the bugs and add more detail. Once finished, I will edit this post.

    EDIT: Here is the fixed code. The problem was I made many different typos. (How embarrassing)
    In order to fix the names problem you have to bring this line: String[] names = {"Darth Vader", "Alfredo", "IDK?", "Pancho Villa", "Miguel Hidalgo", "Bob"}; and bring it to the top where you initialize all of the static variables.
     int userCount = 0;
            String[][] userSurveyData = new String[3][10];
            while(scanner.hasNextLine() && userCount < names.length){ 
                      String[]  line = scanner.nextLine().split(": ");
                      for(int i = 0; i < identifiers.length; i++){
                            if(line[0].equals(identifiers[i]) && !line[1].equals("")){
                               userSurveyData[userCount][i] = line[1]; //stores the data into the correct slot
                            }
                      }
                    if (line[0].equals("request") && line[1].equals("Submit the survey"))  
                       userCount++; //If we reach the last item, then go to the next user
            }

    If you want to make it so the program will run with an unknown amount of users, then you should use an arraylist. I'll try to change the loop for you.

            ArrayList<String[]> userSurveyData = new ArrayList<String[]>();
            String[] userTempSurveyData = new String[10];
            while(scanner.hasNextLine()){  //keeps looping until we reach EOF
                      String[]  line = scanner.nextLine().split(": ");
                      for(int i = 0; i < identifiers.length; i++){
                            if(line[0].equals(identifiers[i]) && !line[1].equals("")){
                               userTempSurveyData[i] = line[1]; //stores the data into the correct slot
                            }
                      }
                    if (line[0].equals("request") && line[1].equals("Submit the survey"))  {
                       userSurveyData.add(userTempSurveyData); //once we have reached the submit, then add the array to the array list.
                       userTempSurveyData = null;
                    }
            }

    The ArrayList method waits until userTempSurveyData is full, and then it adds it to an arrayList.
    Last edited by Brt93yoda; October 13th, 2010 at 01:00 AM.

  9. #9
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    Those two codes look very similar to me. Do they both do the same thing? I tried putting the latter in main (since I don't know where else to put it). I changed it slightly to the version below, adding a println just so I could see what was going on). This is what my code currently looks like.

     
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.io.FileWriter;
     
    public class OutlineTest{
     
    	public static final int ROWS = 10;        //you may change this value
    	public static final int COLS = 7;        //you may change this value
    	public static final int SIZE = 85;        //you may change this value
    	public static final int WAIT = 1000;        //you may change this value
    	public static final int QUESTION = 10;	//This is the total number of questions in the survey.
    	public static final int IDENTLOCALE = 0;
    	public static final Color IDENTCOLOR = Color.WHITE;
    	public static final String[] identifiers = {"V_VS_DV", "SHOES","INVIS_FLY", "LIFE_FREE",
    							"COLSANDERS","VEY_APOLLO","LAK_CELTIC","CS_MAJOR","SMILE","LOVEFIRST"};
     
     
    public static void main(String[] args)throws FileNotFoundException {
     
    	File inFile = new File("C:/Users/Irena/Desktop/Homework2/sampleinput1.txt");
    	Scanner scanner;
     
    	try {
    		scanner = new Scanner(inFile);
    	} catch (Exception e){
    		System.err.println("File not found: " + e.toString());
    		return;
    	}
     
    	//OPENS CANVAS: Works correctly 
    	//Mosaic.open(ROWS,COLS,SIZE,SIZE); 
     
    	//METHOD: LABEL QUESTIONS: Works correctly
    	//labelQuestions();
     
     
    	ArrayList<String[]> userSurveyData = new ArrayList<String[]>();
            String[] userTempSurveyData = new String[10];
     
            while(scanner.hasNextLine()){  //keeps looping until we reach EOF
                      String[]  line = scanner.nextLine().split(": ");
                      for(int i = 0; i < identifiers.length; i++){
                            if(line[0].equals(identifiers[i]) && !line[1].equals("")){
                               userTempSurveyData[i] = line[1]; //stores the data into the correct slot
    									System.out.println(userTempSurveyData[i]);
                            }
                      }
                    if (line[0].equals("request") && line[1].equals("Submit the survey"))  {
                       userSurveyData.add(userTempSurveyData); //once we have reached the submit, then add the array to the array list.
                       userTempSurveyData = null;
                    }
            }
     
     
     
     
    	//newloop(scanner);
     
    	//METHOD: SENDS ANSWERS TO CANVAS: Does not work.
    	//colorAnswers();
     
    	//METHOD: WRITEFILE: Does not work.
    	//exportCSVFile(scanner);
     
     
    }//end of main
     
    	public static void labelQuestions(){
    		for(int i = 0; i < QUESTION; i++){
    			Mosaic.drawLabel(i, 0, identifiers[i], IDENTCOLOR);
    		}
    	}
     
     
    	/*The following method has two Strings added manually for the sake of testing. If you run it, you'll see 
    	the animation as its supposed to run. In the real version of this method, I want ansers to represent 
    	the answers given to any one of the ten questions asked. I guess that means that answers and names would be more dynamic.
    	I don't really know how to do this, though, but the testing at the very least shows that my idea of how to get 
    	the colored rectangles to look like they're growing more opaque seems to be correct.*/
    	public static void colorAnswers(){
    		String[] answers = {"4", "5", "5", "1", "4", "1"};
    		String[] names = {"Darth Vader", "Alfredo", "IDK?", "Pancho Villa", "Miguel Hidalgo", "Bob"};
    			for(int i = 1; i < 7; i++){
    				if(answers[i-1]=="0"){
    					Mosaic.getBlue(0,1);
    					Mosaic.setColor(0, 1, 0, 0, Mosaic.getBlue(0,1)+25);
    					Mosaic.drawLabel(0, 1, names[i-1], IDENTCOLOR);
    				}
    				if(answers[i-1]=="1"){
    					Mosaic.getBlue(0,2);
    					Mosaic.setColor(0, 2, 0, 0, Mosaic.getBlue(0,2)+25);
    					Mosaic.drawLabel(0, 2, names[i-1], IDENTCOLOR);
    				}
    				if(answers[i-1]=="2"){
    					Mosaic.getBlue(0,1);
    					Mosaic.setColor(0, 3, 0, 0, Mosaic.getBlue(0,3)+25);
    					Mosaic.drawLabel(0, 3, names[i-1], IDENTCOLOR);
    				}
    				if(answers[i-1]=="3"){
    					Mosaic.getBlue(0,2);
    					Mosaic.setColor(0, 4, 0, 0, Mosaic.getBlue(0,4)+25);
    					Mosaic.drawLabel(0, 4, names[i-1], IDENTCOLOR);
    				}			
    				if(answers[i-1]=="4"){
    					Mosaic.getBlue(0,1);
    					Mosaic.setColor(0, 5, 0, 0, Mosaic.getBlue(0,5)+25);
    					Mosaic.drawLabel(0, 5, names[i-1], IDENTCOLOR);
    				}
    				if(answers[i-1]=="5"){
    					Mosaic.getBlue(0,2);
    					Mosaic.setColor(0, 6, 0, 0, Mosaic.getBlue(0,6)+25);
    					Mosaic.drawLabel(0, 6, names[i-1], IDENTCOLOR);
    				}		
    				Mosaic.delay(WAIT);
    		}
    	}//end of colorAnswers
     
    	public static void exportCSVFile(Scanner scanner){
    		//I do not know how to write an array into a CSV file yet, but the following is the information I would want 
    		//to be written in the csv file.
    		//There would also be a line here, asking for the user to input the name of the csv file to be written. 
     
    		String[] results = {"","", "", "", "", "", "", "", "", "", ""};
    			while(scanner.hasNextLine()){
    			String[] line = scanner.nextLine().split(": ");
    			for(int i = 0; i < identifiers.length; i++){
    				if(line[0].equals(identifiers[i])){
    					if(!(results[i].equals("")))
    						results[i] += ", ";
    						results[i] += line[1];
    				}
    			}
    		}
     
    		for(int i = 0; i < identifiers.length; i++){
    			System.out.println(identifiers[i] + ": " + results[i]);
    		}
      }
     
    }//end of class

    When I try to compile it, it works fine. When I actually run it, I get the following:

    ----
    1
    5
    2
    1
    0
    4
    2
    1
    Exception in thread "main" java.lang.NullPointerException
    at OutlineTest.main(OutlineTest.java:45)
    ----

    The numbers are the proper answers for the first character, but it doesn't go to the next character's answers. But I don't know what the exception means.

    The line it refers to is this one:

    	ArrayList<String[]> userSurveyData = new ArrayList<String[]>();
            String[] userTempSurveyData = new String[10];
     
            while(scanner.hasNextLine()){  //keeps looping until we reach EOF
                      String[]  line = scanner.nextLine().split(": ");
                      for(int i = 0; i < identifiers.length; i++){
                            if(line[0].equals(identifiers[i]) && !line[1].equals("")){
                               userTempSurveyData[i] = line[1]; //It says that the problem is with this line.
    									System.out.println(userTempSurveyData[i]);
                            }
                      }
                    if (line[0].equals("request") && line[1].equals("Submit the survey"))  {
                       userSurveyData.add(userTempSurveyData); //once we have reached the submit, then add the array to the array list.
                       userTempSurveyData = null;
                    }
            }

    I tried looking up the error and it says something about initialization. Could it be that it's not working properly because I don't have something in the right place?

    (Sorry if I'm making a lot of mistakes! A lot of this is kind of new to me.)

  10. #10
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    how about this.

    ArrayList<String[]> userSurveyData = new ArrayList<String[]>();
            String[] userTempSurveyData = new String[10];
     
            while(scanner.hasNextLine()){  //keeps looping until we reach EOF
                      String[]  line = scanner.nextLine().split(": ");
                      for(int i = 0; i < identifiers.length; i++){
                            if(line[0].equals(identifiers[i]) && !line[1].equals("")){
                               userTempSurveyData[i] = line[1]; //stores the data into the correct slot                
                            }
                      }
                    if (line[0].equals("request") && line[1].equals("Submit the survey"))  {
                       userSurveyData.add(userTempSurveyData); //once we have reached the submit, then add the array to the array list.
                       for (int j=0; j < 10; j++)
                    	   userTempSurveyData[j] = "";
                    }
            }

    normally I run the program before I post my code, but I can seem to get the MosaicCanvas class to work properly.

  11. #11
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    Ah, that would...be my mistake. As soon as I read that you couldn't get the Mosaic Canvas to work, I realized I forgot to give you the other class. I hadn't opened it up in a while and forgot about it entirely. This is the second class I've been using, called Mosaic.

    /* 
       The class Mosaic makes available a window made up of a grid
       of colored rectangles.  Routines are provided for opening and
       closing the window and for setting and testing the color of rectangles
       in the grid.
     
       Each rectangle in the grid has a color.  The color can be
       specified by red, green, and blue amounts in the range from
       0 to 255.  (It can also be given as an object belonging
       to the class Color.)
     
       David Eck (eck@hws.edu), 3 February 2000.
       Modified by Megan Thomas, Sept 2010, to remove use of deprecated methods.
    */
     
     
    import java.awt.*;
    import java.awt.event.*;
     
    public class Mosaic {
     
       private static final int DEBUG = 0;
       private static Frame window;         // A mosaic window, null if no window is open.
       private static MosaicCanvas canvas;  // A component that actually manages and displays the rectangles
     
       public static void open() {
             // Open a mosaic window with a 20-by-20 grid of squares, where each
             // square is 15 pixels on a side.
          open(20,20,15,15);
       }
     
       public static void open(int rows, int columns) {
             // Open a mosaic window with the specified numbers or rows and columns
             // of squares, where each square is 15 pixels on a side.
          open(rows,columns,15,15);
       }
     
       synchronized public static void open(int rows, int columns, int blockWidth, int blockHeight) {
             // Open a window that shows a mosaic with the specified number of rows and
             // columns of rectangles.  blockWidth and blockHeight specify the
             // desired width and height of rectangles in the grid.  If a mosaic window
             // is already open, it will be closed before the new window is open.
          if (window != null)
             window.dispose();
          canvas = new MosaicCanvas(rows,columns,blockWidth,blockHeight);
          window = new Frame("Mosaic Window");
          window.add("Center",canvas);
          window.addWindowListener(
                new WindowAdapter() {  // close the window when the user clicks its close box
                   public void windowClosing(WindowEvent evt) {
                      close();
                   }
                });
          window.pack();
          //window.show();
          window.setVisible(true);
       }
     
       synchronized public static void close() {
              // If there is a mosiac window, close it.
          if (window != null) {
             window.dispose();
             window = null;
             canvas = null;
          }
       }
     
       synchronized public static boolean isOpen() {
              // This method returns a boolean value that can be used to
              // test whether the window is still open.
          return (window != null);
       }
     
       public static void delay(int milliseconds) {
             // Calling this routine causes a delay of the specified number
             // of milliseconds in the program that calls the routine.  It is
             // provided here as a convenience.
          if (milliseconds > 0) {
            try { Thread.sleep(milliseconds); }
            catch (InterruptedException e) { }
          }
       }
     
       public static Color getColor(int row, int col) {
             // Returns the object of type Color that represents the color
             // of the grid in the specified row and column.
          if (canvas == null)
             return Color.black;
          return canvas.getColor(row, col);
       }
     
       public static int getRed(int row, int col) {
             // Returns the red component, in the range 0 to 255, of the
             // rectangle in the specified row and column.
          if (canvas == null)
             return 0;
          return canvas.getRed(row, col);
       }
     
       public static int getGreen(int row, int col) {
             // Returns the green component, in the range 0 to 255, of the
             // rectangle in the specified row and column.
          if (canvas == null)
             return 0;
          return canvas.getGreen(row, col);
       }
     
       public static int getBlue(int row, int col) {
             // Returns the blue component, in the range 0 to 255, of the
             // rectangle in the specified row and column.
          if (canvas == null)
             return 0;
          return canvas.getBlue(row, col);
       }
     
       public static void setColor(int row, int col, Color c) {
              // Set the rectangle in the specified row and column to have
              // the specified color.
          if (canvas == null)
             return;
          canvas.setColor(row,col,c);
       }
     
       public static void setColor(int row, int col, int red, int green, int blue) {
              // Set the rectangle in the specified row and column to have
              // the color with the specifed red, green, and blue components.
          if (canvas == null)
             return;
          canvas.setColor(row,col,red,green,blue);
       }
     
       public static void drawLabel(int row, int col, String s, Color c) {
              // Set the rectangle in the specified row and column to have
              // the specified color.
          if (canvas == null)
             return;
          canvas.drawLabel(row,col,s,c);
          if (DEBUG > 0) {
     	 System.out.println("drawing " + s + " in " + row + ", " + col);
          }
       }
     
       public static void fill(Color c) {
              // Set all the rectangels in the grid to the color c.
          if (canvas == null)
             return;
          canvas.fill(c);
       }
     
       public static void fill(int red, int green, int blue) {
              // Set all the rectangles in the grid to the color with
              // the specified red, green, and blue components.
          if (canvas == null)
             return;
          canvas.fill(red,green,blue);
       }
     
       public static void fillRandomly() {
              // Sets each rectangle in the grid to a different randomly
              // chosen color.
          if (canvas == null)
             return;
          canvas.fillRandomly();
       }
     
    }  // end of class Mosaic

    With this class, Mosaic Canvas ought to work. Sorry about that oversight!

  12. #12
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    My change in my last post worked perfectly. I added the changes and added some prints for debuging.

    Here is the updated code
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.io.FileWriter;
     
    public class OutlineTest{
     
        public static final int ROWS = 10;        //you may change this value
        public static final int COLS = 7;        //you may change this value
        public static final int SIZE = 85;        //you may change this value
        public static final int WAIT = 1000;        //you may change this value
        public static final int QUESTION = 10;  //This is the total number of questions in the survey.
        public static final int IDENTLOCALE = 0;
        public static final Color IDENTCOLOR = Color.WHITE;
        public static final String[] identifiers = {"charname", "V_VS_DV", "SHOES","INVIS_FLY", "LIFE_FREE",
                                "COLSANDERS","VEY_APOLLO","LAK_CELTIC","CS_MAJOR","SMILE","LOVEFIRST"};
     
     
    public static void main(String[] args)throws FileNotFoundException {
     
        File inFile = new File("C:/Users/Irena/Desktop/Homework2/sampleinput1.txt");
        Scanner scanner;
     
        try {
            scanner = new Scanner(inFile);
        } catch (Exception e){
            System.err.println("File not found: " + e.toString());
            return;
        }
     
        //OPENS CANVAS: Works correctly
        //Mosaic.open(ROWS,COLS,SIZE,SIZE);
     
        //METHOD: LABEL QUESTIONS: Works correctly
        //labelQuestions();
     
     
        ArrayList<String[]> userSurveyData = new ArrayList<String[]>();
            String[] userTempSurveyData = new String[11];
     
            while(scanner.hasNextLine()){  //keeps looping until we reach EOF
                      String[]  line = scanner.nextLine().split(": ");
                      for(int i = 0; i < identifiers.length; i++){
                            if(line[0].equals(identifiers[i]) && !line[1].equals("")){
                               userTempSurveyData[i] = line[1]; //stores the data into the correct slot
                                        System.out.print(userTempSurveyData[i]+" ");
                            }
                      }
                    if (line[0].equals("request") && line[1].equals("Submit the survey"))  {
                       userSurveyData.add(userTempSurveyData); //once we have reached the submit, then add the array to the array list.
                       System.out.println();
                       for (int j=0; j < 10; j++)
                           userTempSurveyData[j] = "";
                    }
            }
     
     
     
     
        //newloop(scanner);
     
        //METHOD: SENDS ANSWERS TO CANVAS: Does not work.
        //colorAnswers();
     
        //METHOD: WRITEFILE: Does not work.
        //exportCSVFile(scanner);
     
     
    }//end of main
     
        public static void labelQuestions(){
            for(int i = 0; i < QUESTION; i++){
                Mosaic.drawLabel(i, 0, identifiers[i], IDENTCOLOR);
            }
        }
     
     
        /*The following method has two Strings added manually for the sake of testing. If you run it, you'll see
        the animation as its supposed to run. In the real version of this method, I want ansers to represent
        the answers given to any one of the ten questions asked. I guess that means that answers and names would be more dynamic.
        I don't really know how to do this, though, but the testing at the very least shows that my idea of how to get
        the colored rectangles to look like they're growing more opaque seems to be correct.*/
        public static void colorAnswers(){
            String[] answers = {"4", "5", "5", "1", "4", "1"};
            String[] names = {"Darth Vader", "Alfredo", "IDK?", "Pancho Villa", "Miguel Hidalgo", "Bob"};
                for(int i = 1; i < 7; i++){
                    if(answers[i-1]=="0"){
                        Mosaic.getBlue(0,1);
                        Mosaic.setColor(0, 1, 0, 0, Mosaic.getBlue(0,1)+25);
                        Mosaic.drawLabel(0, 1, names[i-1], IDENTCOLOR);
                    }
                    if(answers[i-1]=="1"){
                        Mosaic.getBlue(0,2);
                        Mosaic.setColor(0, 2, 0, 0, Mosaic.getBlue(0,2)+25);
                        Mosaic.drawLabel(0, 2, names[i-1], IDENTCOLOR);
                    }
                    if(answers[i-1]=="2"){
                        Mosaic.getBlue(0,1);
                        Mosaic.setColor(0, 3, 0, 0, Mosaic.getBlue(0,3)+25);
                        Mosaic.drawLabel(0, 3, names[i-1], IDENTCOLOR);
                    }
                    if(answers[i-1]=="3"){
                        Mosaic.getBlue(0,2);
                        Mosaic.setColor(0, 4, 0, 0, Mosaic.getBlue(0,4)+25);
                        Mosaic.drawLabel(0, 4, names[i-1], IDENTCOLOR);
                    }          
                    if(answers[i-1]=="4"){
                        Mosaic.getBlue(0,1);
                        Mosaic.setColor(0, 5, 0, 0, Mosaic.getBlue(0,5)+25);
                        Mosaic.drawLabel(0, 5, names[i-1], IDENTCOLOR);
                    }
                    if(answers[i-1]=="5"){
                        Mosaic.getBlue(0,2);
                        Mosaic.setColor(0, 6, 0, 0, Mosaic.getBlue(0,6)+25);
                        Mosaic.drawLabel(0, 6, names[i-1], IDENTCOLOR);
                    }      
                    Mosaic.delay(WAIT);
            }
        }//end of colorAnswers
     
        public static void exportCSVFile(Scanner scanner){
            //I do not know how to write an array into a CSV file yet, but the following is the information I would want
            //to be written in the csv file.
            //There would also be a line here, asking for the user to input the name of the csv file to be written.
     
            String[] results = {"","", "", "", "", "", "", "", "", "", ""};
                while(scanner.hasNextLine()){
                String[] line = scanner.nextLine().split(": ");
                for(int i = 0; i < identifiers.length; i++){
                    if(line[0].equals(identifiers[i])){
                        if(!(results[i].equals("")))
                            results[i] += ", ";
                            results[i] += line[1];
                    }
                }
            }
     
            for(int i = 0; i < identifiers.length; i++){
                System.out.println(identifiers[i] + ": " + results[i]);
            }
      }
     
    }//end of class

    BTW: You're going to have to change your export method alot. What you have to do is loop through the arrayList, and then write down each element in each array.
    Last edited by Brt93yoda; October 13th, 2010 at 02:46 AM.

  13. The Following User Says Thank You to Brt93yoda For This Useful Post:

    lavloki (October 13th, 2010)

  14. #13
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    Thanks so much! The code works really well now.

    I've been experimenting with it and I noticed that the name of the character is always stored at [0] of the array and the answers are are stored in the proceeding points.

    The print out reads (I changed it to System.out.print(userTempSurveyData[i]+"("+identifiers[i]+")"+" "); so I could see how everything was being counted:

    Darth Vader(charname) 1(V_VS_DV) 5(SHOES) 2(INVIS_FLY) 1(LIFE_FREE) 0(COLSANDERS) 4(VEY_APOLLO) 2(LAK_CELTIC) 1(CS_MAJOR) 
    Alfredo(charname) 2(V_VS_DV) 1(SHOES) 4(LIFE_FREE) 2(COLSANDERS) 5(VEY_APOLLO) 5(LAK_CELTIC) 4(CS_MAJOR) 
    IDK?(charname) 5(V_VS_DV) 4(SHOES) 2(INVIS_FLY) 4(LIFE_FREE) 3(COLSANDERS) 5(VEY_APOLLO) 3(LAK_CELTIC) 4(CS_MAJOR) 
    Pancho Villa(charname) 1(V_VS_DV) 5(SHOES) 2(INVIS_FLY) 3(LIFE_FREE) 1(COLSANDERS) 1(VEY_APOLLO) 2(LAK_CELTIC) 1(CS_MAJOR) 
    Miguel Hidalgo(charname) 5(V_VS_DV) 2(SHOES) 3(INVIS_FLY) 4(LIFE_FREE) 2(COLSANDERS) 4(VEY_APOLLO) 3(LAK_CELTIC) 1(CS_MAJOR) 
    Bob(charname) 5(V_VS_DV) 5(SHOES) 5(INVIS_FLY) 4(LIFE_FREE) 3(COLSANDERS) 1(VEY_APOLLO) 3(LAK_CELTIC) 4(CS_MAJOR)

    This is EXACTLY what I was hoping for!

    All that's really left is to try and move that information onto the opened canvas. I plan to write a method that will be able to receive, from the part of the program you wrote, i and userTempSurveyData[i]. if userTempSurveyData[i] is not an integer, I want the method to somehow record userTempSurveyData[i] as String charactername. Then, for all other userTempSurveyData[i] (the numbers), I want the method to do something similar to the colorAnswers method I already attempted to write( it will read the color at i, userTempSurveyData[i] and will fill it in with a higher blue value) all while applying the charactername label to each. Does that sound like something that would be possible? I've attempted to do a skeleton of what I want the method to do, but even though java isn't throwing up any errors, it isn't doing what I want it to do either. Does my method idea sound too complicated? Do you know of a better way?

  15. #14
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    I'm not exactly sure what you mean, but it sounds possible. Can you show your current code? I'll read through it and see what's wrong.

    when ever compare strings you have to use the equal method.

    String test = "hi"
     
    if (test.equals("hi"))
       System.out.println("hai2u!");
    Last edited by Brt93yoda; October 13th, 2010 at 10:16 AM.

  16. The Following User Says Thank You to Brt93yoda For This Useful Post:

    lavloki (October 13th, 2010)

  17. #15
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    I took some time to really explore the nature of the data that's produced in the code and I figured out how to put the data onto the mosaic canvas! Here's what it looks like (its not too pretty yet. I have to go back in and format things so its more visually readable, but this is it basically) :

    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.io.FileWriter;
     
    public class OutlineSecondTest{
     
        public static final int ROWS = 10;        //you may change this value
        public static final int COLS = 7;        //you may change this value
        public static final int SIZE = 85;        //you may change this value
        public static final int WAIT = 100;        //you may change this value
        public static final int QUESTION = 10;  //This is the total number of questions in the survey.
        public static final int IDENTLOCALE = 0;
        public static final Color IDENTCOLOR = Color.WHITE;
        public static final String[] identifiers = {"charname", "V_VS_DV", "SHOES","INVIS_FLY", "LIFE_FREE",
                                "COLSANDERS","VEY_APOLLO","LAK_CELTIC","CS_MAJOR","SMILE","LOVEFIRST"};
     
     
    public static void main(String[] args)throws FileNotFoundException {
     
        File inFile = new File("C:/Users/Irena/Desktop/Homework2/sampleinput1.txt");
        Scanner scanner;
     
        try {
            scanner = new Scanner(inFile);
        } catch (Exception e){
            System.err.println("File not found: " + e.toString());
            return;
        }
     
        //OPENS CANVAS: Works correctly
        Mosaic.open(ROWS,COLS,SIZE,SIZE);
     
        //METHOD: LABEL QUESTIONS: Works correctly
        labelQuestions();
     
     
        ArrayList<String[]> userSurveyData = new ArrayList<String[]>();
            String[] userTempSurveyData = new String[11];
     
            while(scanner.hasNextLine()){  //keeps looping until we reach EOF
                      String[]  line = scanner.nextLine().split(": ");
                      for(int i = 0; i < identifiers.length; i++){
                            if(line[0].equals(identifiers[i]) && !line[1].equals("")){
                               userTempSurveyData[i] = line[1]; //stores the data into the correct slot
    												colorAnswers(userTempSurveyData[0],userTempSurveyData[i],i-1);
     
                            }
                      }
                    if (line[0].equals("request") && line[1].equals("Submit the survey"))  {
                       userSurveyData.add(userTempSurveyData); //once we have reached the submit, then add the array to the array list.
                       System.out.println();
                       for (int j=0; j < 10; j++)
                           userTempSurveyData[j] = "";
                    }
            }
     
        //METHOD: WRITEFILE:kinda works.
        exportCSVFile(scanner);
     
     
    }//end of main
     
     
     
        public static void labelQuestions(){
            for(int i = 1; i <= QUESTION; i++){
                Mosaic.drawLabel(i-1, 0, identifiers[i], IDENTCOLOR);
            }
        }
     
     
        /*The following method gets the input from main and applies it to the mosaic canvas. However, the colors don't seem to get 
    	 brighter as more votes for the same answer are given.*/
        public static void colorAnswers(String Name, String Answer, int i){
                    if(Answer.equals("5")){
                        Mosaic.getBlue(i,1);
                        Mosaic.setColor(i, 1, 0, 0, Mosaic.getBlue(i,1)+25);
                        Mosaic.drawLabel(i, 1, Name, IDENTCOLOR);
                    }
                    if(Answer.equals("4")){
                        Mosaic.getBlue(i,2);
                        Mosaic.setColor(i, 2, 0, 0, Mosaic.getBlue(i,2)+25);
                        Mosaic.drawLabel(i, 2, Name, IDENTCOLOR);
                    }
                    if(Answer.equals("3")){
                        Mosaic.getBlue(i,1);
                        Mosaic.setColor(i, 3, 0, 0, Mosaic.getBlue(i,3)+25);
                        Mosaic.drawLabel(i, 3, Name, IDENTCOLOR);
                    }
                    if(Answer.equals("2")){
                        Mosaic.getBlue(i,2);
                        Mosaic.setColor(i, 4, 0, 0, Mosaic.getBlue(i,4)+25);
                        Mosaic.drawLabel(i, 4, Name, IDENTCOLOR);
                    }          
                    if(Answer.equals("1")){
                        Mosaic.getBlue(i,1);
                        Mosaic.setColor(i, 5, 0, 0, Mosaic.getBlue(i,5)+25);
                        Mosaic.drawLabel(i, 5, Name, IDENTCOLOR);
                    }
                    if(Answer.equals("0")){
                        Mosaic.getBlue(i,2);
                        Mosaic.setColor(i, 6, 0, 0, Mosaic.getBlue(i,6)+25);
                        Mosaic.drawLabel(i, 6, Name, IDENTCOLOR);
                    }      
                    Mosaic.delay(WAIT);
     
        }//end of colorAnswers
     
        public static void exportCSVFile(Scanner scanner){
            //I do not know how to write an array into a CSV file yet, but the following is the information I would want
            //to be written in the csv file.
            //There would also be a line here, asking for the user to input the name of the csv file to be written.
     
    		Scanner scan = new Scanner(System.in);
    		System.out.print("PPlease enter the output file name:\t"); 
          String message = scan.nextLine();    
     
          String[] results = {"","", "", "", "", "", "", "", "", "", ""};
    		System.out.println("question identifier,strongly agree,agree,no opinion,disagree,strongly disagree,N/A or decline,");
     
    		while(scanner.hasNextLine()){
    			String[] line = scanner.nextLine().split(": ");
     
    			for(int i = 0; i < identifiers.length; i++){
    				if(line[0].equals(identifiers[i])){
    					if(!(results[i].equals("")))
    						results[i] += ", ";
    						results[i] += line[1];
     
    					}
    			}
    		}
    		for(int i = 1; i < identifiers.length; i++){
    					System.out.println(identifiers[i]+","+results[i]+",");
    		}
     
     
    }
    }//end of class

    The only real question left for me is how to export data produced in the program to a CVS file as I've never done that before. I'm able to print the information correctly in the program, so I know that it's the information I want. But I don't quite know how to get java to put that information in a csv file named after what the user inputs. I tried looking it up, but I must not be using the right search words because I keep getting entries on how to parse csv files or how to convert from xls to csv. Any suggestions?

  18. #16
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    I've never used CSV, but I searched to how export data to a CSV file in Java. this link looks promising: http://www.mkyong.com/java/how-to-export-data-to-csv-file-java/

  19. #17
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    After messing around with the code on that site, it was exactly what I needed! Thank you so much for all of your help and patience. I really learned a lot thanks to you!

  20. #18
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Help with a beginner's java assignment: Survey results

    You're very welcome.

Similar Threads

  1. beginner's question
    By bardd in forum Java Theory & Questions
    Replies: 5
    Last Post: September 14th, 2010, 05:02 PM
  2. my java assignment -- please help
    By java_beginner in forum Java Theory & Questions
    Replies: 6
    Last Post: May 20th, 2010, 09:32 AM
  3. Replies: 1
    Last Post: February 22nd, 2010, 08:20 AM
  4. I need extensive help with my java assignment
    By MoshMoakes in forum What's Wrong With My Code?
    Replies: 0
    Last Post: December 12th, 2009, 07:44 PM
  5. [SOLVED] Problem with Grading calculator in java program
    By Peetah05 in forum What's Wrong With My Code?
    Replies: 23
    Last Post: March 28th, 2009, 05:25 PM

Tags for this Thread