Please use ctrl+f to search for an answer
to your question.
Table of contents:
- Error Message When Running Program
- 101E and the J drive, and simple Java syntax question
- error?
- Moving through directories in command prompt
- Mapping the J drive
- submission
- One long line of code vs. many short lines?
- Command Prompt
- CS 101-E Lab Submissions
- javac
- Invalid Directory in Command Prompt
- how do i reply
- eclipse
- Using a Mac
- lab0 - compile
- Question about grading
- lab0 - compile 2
- Subscribing problems
- Question about replying
- Run the Programme "UseThree"~
- C:\ to J:\
- RoboGrader
- Lab Quiz 1
- Group Assignment question
- Need help with the output's format.
- Assignment 1
- Converting Strings to booleans
- What does it mean?
- Assignment 1-again
- The standard output
- Java Library Documentation
- Lab Quiz 1
- TA office hours
- MixedNumberTypes
- Lab Quiz 1
- changing directories
- Groupwork 1
- Groupwork 1 Question 9
- Re-submitting Corrected Programs
- boolean
- Uploading Group programs
- RoboGrader
- Quiz 1
- Group Assignment #3 - Boolean
- arguments
- Group Assignment problem #7
- Home Directory and Mac
- Robograde DeMorgan
- error message
- error from command prompt
- RoboGrader
- Mixed Number Types
- difference between"print" and "println"
- Mixed Number Types (2)
- "javac" problems
- reply button...
- Errors for min in color program
- Eclipse Won't Let me Access My Workspace Anymore
- Mac Terminal
- Lab1 EC
- Lab Quiz
- Assignment 1
- Laboratory Quiz
- Group Assignment # 5
- Assignment 1: Intervals
- Assignment 1
- computer lab
- Lab quiz error
- One more question about the intervals
- Wrapping
- Lab Quiz Extra Credit Question
- Re: Assignment 1:Intervals
- quiz 1
- Requirements for Assignment One
- Lab Quiz EC Question
- Converting double to string
- quiz??
- Eclipse Freezing
- practicing the quiz
- RoboGrade for Color Lab?
- RoboGrade of Group Work
- I need help with loops
- Waitlist Protocol for Stacks Office Hours
- Fatal Grading Error on quiz!
- fatal grading script error
- Problems with the quiz grade
- float versus double
- Assignment 1
- How Precisely do We Subdivide Intervals in Assmt #1
- Output of No.2 assignment 1
- Double inaccuracy
- Assigning Sub-intervals to Elements
- Question on Part 2, Assignment 1
- RoboGrade for Assignment 1?
- Nit-picky question
- can't compile
- stdlib
- Individual Assigment 1 question
- standard library
- stdlib problems
- can't compile anymore
- Groupwork #18
- ASSIGNMENT 1!!
- How do I use StdLib at Command Line (was "stdlib problems continued")
- Assignment 1 - Edited?
- assignment 1
- Group Assignment # 18
- Why is 1/0 undefined while 1.0/0.0 is legal in java?
- Assignment 1
- Question about the while command
- Assignment 1 - Command Line Argument
- Histogram Question
- Assignment 1 output
- Robograde on random numbers
- Robograde for Groupwork #17
- Running programs within eclipse
- Error Error
- Opening an in-progess project
- Assignment 1
- Using values defined in a for loop, outside the loop
- Formatting Errors
- Question about Individual problem
- problem with results
- Average for part 2?
- individual assignment part 2 output
- How Do I Use StdLib at Command Line (was "Trouble with Stdlib")
- Failed to load Main-Class manifest? (Was How to download stdlib.jar)
- RoboGrade? Assignment 1
- Histogram with DrawDistribution
- I'm sorry but I can't trace variables in Debug menu
- Compiling Lab Study #1 error
- Another Lab Study #1 error
- I need help
- Lab Study #1- command line
- Command Line Compiling Follow-up
- In addition to my previous post
- Problems with Home Directory Login
- StdDraw.picture problems - finding picture file
- How to Read In a File Name using StdIn
- Groupwork2 formatting error
- Lab study 1 Grading
- Troubling Red Xs
- GroupWork submission
- JAR Extension FIle
- Compile and Run in Eclipse - Lab 1
- In addition to my last post
- Red line on grapth (Lab work)
- Please disregard my previous inquiry
- Lab Study #1
- Variable precision
- Lab Study 1
- Running in Eclipse
- Another lab study 1 question
- Assignment2: "
- Something for Groupwork 2
- Groupwork2 formatting error
- Individual Assignment file addresses for grading
- GroupWork Gravity2
- Gravity2 Output error
- Audio For Bouncing Ball
- Gravity2 Output error (in addition to previous post)
- Read the input file - assignment 2
- BluePlanet image not found
- how many points for each program in group assignment 2?
- Changing Input within Eclipse
- end- of -file sequence, Book example Program 1.5.3 Averaging a stream of numbers
- How to run a program in eclipse by using standard input instead of the command line?
- Running Bouncing Ball from command line
- Image Earth.gif not found
- stdlib
- placement of external files
- re: Lab quiz this thursday
- lab quiz
- Question
- Robograde
- More stdlib problems
- Individual Assignment 2 - LeapFrog Method?
- How do I get the console to open?
- Command Line with Std Libraries
- USA.txt
- random stdlib error
- Gravity2 and Robograde
- BluePlanet and Eclipse
- USA.txt
- BluePlanet
- NBody.zip?
- Planets leaving the solar system
- using planets.txt
- selection does not contain a main type
- Readings planets.txt
- Confusion about Assignment 2
- Assignment 2 being weird...
- Having problems with StdDraw.picture
- starfield.jpg
- Is it possible?
- Program with Home Dir. and Stdlib
- Planets really slow
- README Template?
- Galaxy Simulation extra credit deadline
- Step 2:Planet not moving on given velocity
- Deluxe Bouncing Ball
- Student.java Stdin
- HELP
- Another StdIn problem
- Another StdIn problem update
- Clearing image trails....
- StdDraw.show()
- I cannot get StdDraw.picture to work
- Unsure how to compile and run Assignment 2
- Stdlib.jar problems and problem reading files
- Blinking Planets
- Planets velocity
- how to play 2001.mid
- Error message when adding audio
- Path of the planets
- Path of the planets, again
- Massive Loop
- standard audio
- Did Robograde die?
- Audio for NBody wont play
- Image Errors
- resubmit quiz 2
- cast String>Double
- "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
- looping an audio file
- Group work robograde
- StdIn Planets.txt
- groupwork3
- groupwork3
- Extra Credit files won't load
- Submission closed 9:55 p.m
- Click Sound in StdAudio
- sumArrays.java
- Groupwork3 - tone
- Groupwork 3 - Credit Card
- lab today??
- More Mario Help
- Assingment 2 after the fact
- TA's at Stacks on the 14th???
- Groupwork 3, Question 4
- No 101 TA's at Stacks tonight....
- Capitalization in Groupwork #17
- Group Project 3 errors
- Group Project 3 errors (contd)
- Recursions
- Standard In- reading chars
- conversion from int to string
- Referring to the last character in an string
- Groupwork #7
- nchar(#17) problem
- Unsubmitting Group Work
- what is the difference?
- Using Color
- factorial GroupWork 3
- Parameters for sierpinski
- Strict comparison in totient
- Appointment with TA
- Office hour and a maybe not simple question
- Canvas Color
- Individual Assignment 3 Question
- Canvas scale problems for individual assignment
- Groupwork 3 Robograde
- Assignment 3 - Colors
- uninverted triangle outline on assignment page Assign 3
- Exam 1
- Regrades
- Art.java
- Sierpinski Triangle
- Art.java
- question
- Color
- Outline of Triangle
- Edge lengths of triangle
- Art.java
- How many methods?
- Random colours
- question
- What does this mean?
- art.java
- art.java additions
- zip
- #21 -vCCN array length
- StdDraw.setCanvasSize
- midpoint of a line
- name of function for Art.java
- uploading Art_extra.zip
- Saving StdDraw as other file type
- Art.java
- jpg
- redirect standard input from file to terminal
- Eclipse
- mergeSort merge function
- RE: mergeSort merge function
- bubblsort
- MergeSort
- Groupwork4
- MergeSort Again
- changing output of merge
- auxilliary arrays
- Sorry, but Merge this time...
- RoboGrade for Pascal
- RoboGrade for MergeSort, Count??????
- can we change the function to non-static?
- further question for Non-static..
- an outline of my algorithm?
- Thanks so much to the previosu reply
- How could I set an element of an array to be void
- DataCollection
- Re: DataCollection
- Edit Distance Submission
- lab quiz 4
- Quiz 4 Grading
- Quiz 4; problem 1
- Drawing a rectangle??
- Not able to type in an argument into console window and run program
- Arithmatic with complex numbers?
- Individual Assignment Run Time
- lastxgap8.txt and lastygap8.txt
- Just ignore the previous post
- color transparency.
- Quiz 4, AverageArray
- ecoli 500000
- Weird!
- Right Mouse Click
- BubbleSort grading funny?
- Individual Assignment Output
- Individual Assignment - Problem with Opt Array
- Distance - readme.txt
- RoboGrade Group Assignment 4 - Sorting
- what does StdIn.readAll().split("\\s+") mean?
- eclipse program not working
- Ignore previous posts about the robograde
- Error in mergeSort
- Individual Assignment 4 (Std or System)
- Timing the Edit Distance
- Unable to use Windows command line
- Assignment 4-just write a function?
- MergeSort
- Run Time Problem
- Readme Assignment 4
- MergeSort 2
- MergeSort again
- output.txt
- MergeSort Datacollection problem
- Assignment 4 -- Largest N program can handle.
- Question regarding Assignment 4 format
- ecoli2500.txt
- EditDistance Compiling Error
- Question about String length in readme.txt
- Individual Assignment 4 - Estimating amount of memory used in bytes
- java -Xmx300m EditDistance
- Last part of readme.txt
- Spaces?
- EditDistance Command Line Compile
- Spaces in IA
- initializing opt[i][j]
- end of my program
- Incorrect Outputs when piping in txt files
- String Out of Bounds Exception
- String Out of Bounds Exception - Similar Problem
- Time
- Read me last question
- Re: Time
- MergeSort
- Re:Re: Time
- Midpoint
- Making the StdOut work on macs terminal
- EditDistance will not compile in command prompt
- Running in Eclipse
- New Computer set up
- JDK 6 update 5
- CMD line and lib's??
- Import existing Projects?
- Groupwork5
- GW 5
- delayinMSdelayinMS
- runtime of factorial,fib and matrix
- API's
- GuitarHeros
- Groupwork #5
- The number of comparisons in Quicksort
- question regarding order of growth
- pluck
- does the constructor name have to be identical to the class name?
- GuitarHero-Visualizer
- totalItems
- StdDraw & StdAudio
- Groupwork #5
- Public vs private vs nothing
- StdDraw & StdAudio(further discussion)
- the total memory requirements for a 2D double array
- questions about memory requirements
- static vs Non-static
- Factorial - runtime
- Wrap around - queue
- About the Exam
- Is the lab tomorow graded?
- GuitarHeroLite
- Exam Grade
- Exam Grade REPLY TO SELF
- exam grade
- Guitar Directory
- Lab Quiz #4 grade
- Problem with GuitarString
- guitar readme
- past year exam
- CheckoutArea (Group Work)
- Calling Other Classes/Functions
- RingBuffer
- Sample
- Groupwork: Is this supposed to happen?
- Ignore my last question
- Groupwork 5
- Null Pointer Exception -- RingBuffer
- Extra Credit
- String keyboard
- Question about Guitar Hero
- RingBuffer
- Question on guitar string
- GuitarString Output
- Please Ignore my 'Guitar String' Post
- Random Instance Variable.
- Deletion of Sample
- Error with StandardDraw in Guitar Hero
- Error: Class not found Exception
- Groupwork 5
- Ring Buffer enqueue
- GuitarHeroLite
- Group Work: never used server.totalItems?
- GuitarHeroLite running sample before key entry.
- keyboard interaction
- GuitarHeroLite running sample before key entry Response.
- GuitarHeroLite
- NullPointerException in Group Work 5
- Extra Credit Font
- Sound
- Lab Quiz 4/10
- Continued problems with StdDraw
- Error happen when submit the file
- Quiz Grade Discrepency
- Problems with SETs
- SET issue
- RE: Problems with SETs
- Unsafe?
- Art Forum Posting
- Art - Forbidden Error
- SortedList Question
- Saving Graphics As JPG File
- Node references in a linked list
- Do we have to use a "for" loop for toString()?
- Problem with SortList Program in the class
- Adding
- SortList "Hello There Friend" Problem
- Fixed it
- What should be printed out for lab quiz 6?
- Head
- SortedList output
- SortedLinkList value ThreeA
- NullPointerException
- JPG file
- debugger problems
- Ascending order
- Lab Quiz 6
- Posting Artwork
- Assignment6 neareastInsert
- might be a stupid question
- reply to Lesley
- Smallest Insertion
- smallest insertion
- sorry for the previous unthoughtful post
- Exam 3
- [1] 0 1 0
- State machine starting point
- assignment 6
- Turing machine jar file
- usa13509 with insert smallest
- nevermind on "usa13509 with insert smallest"
- TSP in the Command Prompt
- Weird Problem: InsertNearest
- Why is mergesort a poly-time algorithm?
- "ILP is not likely to be in P"- dont understand how to prove
- Does "accepting state" in a FSM mean "Yes"?
- draw() in Point.java
- Sub-directory on J-drive
- Halting Problem
- Intractable=No poly-time solution? Or=in NPC?
- Partition problem:)
- Problems in NP but not in P or NPC
- optimal 1000?
- DFA's and Turing Machines
- tsp answer files
- The NP-Complete problem
- Examples of NP problems not in P nor in NPC
- Replication Operator
- TSP Checking
- Error when running Tour
- Checking TSP
- Pre made aspect of TSP
- individual assignment 6
- Zip file wrong
- Readme
- Art
- Ungraded Quizzes
- Big Integers
- Posting the artwork
Error Message When Running Program
User 28 said: Hey all,
I'm using my laptop at home (it is a UVA computing initiative laptop if that makes a difference) and I'm getting a strange error message when I try to run my Hello World program. When I type "java HelloWorld" I get this error message:
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
I have installed Java successfully (I can type java -version, and it comes up as Java 1.6), followed the configuring Windows to use Java from the command line instructions carefully, and my program compiles fine.
I did find somewhat of a solution. I googled the error message and I found a suggestion to type: "java -classpath . HelloWorld". I did this and it works fine. I was wondering what the problem is and if this will affect my programs when I submit them. Thanks!
Professor Humphreys said: The classpath is a list of directories where Java will look for the program to run.
So when you say "java HelloWorld", java says "okay, where might I find a HelloWorld program? Let's start looking around".
The current directory should be in the default classpath, but it looks like your computer has a customized classpath. You can verify this by typing the command "set" at the command line and looking for a variable called "CLASSPATH".
If you find one, it's probably there for a reason (some other software package needs it, or something like that). However, all is not lost! Edit the CLASSPATH environment variable just like you edited the PATH environment variable when you were setting up Java. CLASSPATH (on Windows) is a SEMICOLON-SEPARATED-LIST of directories.
So add the string ".;" to the beginning of it.
If you have trouble getting this to work, the TAs should be able to do it for you.
User 14 said: Hi Mark,
This might have something to do with Java not knowing what to use for the classpath. I know this happened to some people last semester who accidentally changed their "classpath" environment variable instead of "path". Try going back to your environment variables (where you changed your "path"), find "classpath" and add a simple "." to it. Let us know if that helps at all.
-- Eric
101E and the J drive, and simple Java syntax question
User 39 said: In following the setup instructions, I had a question relating to setting up our network J drive. As I am a 101E student and we don't participate in the actual in class lab sections, I was uncertain as to whether or not mapping a J drive on my home computer was necessary/recommended, or if it wouldn't make any difference over my just storing it on a local drive.
My other question is - is it possible in java to have both a text output as well as an args[...] in the same system.out statement. In other words, in C you could say printf("blah blah, %i", x); and have no worries, but when I tried to mix the args with "....." I'd get compile errors.
Thanks for the help
Lesley said: The concatenation character in Java is a plus sign. You can concatenate whatever you wish (inline strings, variables, mathematical expressions...) inside the print statement (Java also has a printf should you decide to go that route). Please ctrl+f "System.out" on http://www.cs.princeton.edu/introcs/12types/index.php --which is assigned reading for sometime soon if not now-- should you need more help with that, and for printf see http://www.cs.princeton.edu/introcs/15inout/.
I took 101E last semester and found it imperative to have my J drive mapped. If, for some reason, there is a submission error, you need a version of your code on the UVA server so that there is no dispute over the time and honor code.
error?
User 26 said: i set up my computer with java etc and when i type java -version into the command, it does list a version.
i put the helloworld program into notepad and saved it as HelloWorld.java
when i put javac HelloWorld.java in command this is what I get:
javac: file not found: HelloWorld.java
Usage: javac <options> <source files>
use -help for a list of possible options
whats up? and if this was a setup error on my part and TAs can help with setup - do they have office hrs today (thrs) or ever? I'm ur typical Liberal Arts major - I can't follow directions to save my life.
Professor Humphreys said: You need to make sure you have changed to the same directory that contains the .java file. This is shown in the videos; look for the part about the "cd" command.
Lesley said: Also, make sure you use quotes around the file name when saving or Notepad will sneakily save the file as HelloWorld.java.txt - see attached image.
User 167 said: Think of the command prompt a lot like Windows Explorer - at any given time, you're "in" a particular folder. Typing commands like "javac
" will call javac on the file of the given name *in whatever directory you're in*. The error message you got indicates that you were in a folder that didn't contain a file called 'HelloWorld.java'
To change directories, you use the 'cd' command: type 'cd ' to use this.
Thus, 'cd workspace/HelloWorld/src/' will take you to the src dir for your HelloWorld project (assuming that you've started off in the folder containing your workspace, and your project is called HelloWorld).
Also be sure that the file really is called 'HelloWorld.java' - type 'dir' at the command line to see a list of files in the current directory, or just open the folder normally through Windows Explorer or whatever to see what's in it. As Lesley pointed out, some programs try to be "helpful" and screw up your filenames.
Moving through directories in command prompt
User 200 said: Is it possible to go back through directories in the command prompt without closing and reopening it entirely? I went through the command prompt to compile and test my Hello World program, so I was at:
C:\student\workspace\Hello World\src\
and I wanted to go back to my workspace folder and test my UseThree program right afterwards. Is it possible to get to my folder
C:\student\workspace\Use Three\src
without closing and reopening the command prompt?
Professor Humphreys said: cd ..
Mapping the J drive
User 240 said: I was wondering if someone could explain how to set up the J-drive on my personal laptop. I am in CS 101E, so I don't have a lab time, but I figure it would be useful to be able to save things to the network so that I can go to Thornton Stacks and get help if necessary. Thank you.
Professor Humphreys said: I believe ITC has instructions about how to install Home Directory Services on personal machines.
submission
User 26 said: now I have a HelloWorld.java txt file and a HelloWorld.class file...
which am i submitting?
Professor Humphreys said: Every assignment will have a list of filenames at the bottom. In this case, it's the .java file.
One long line of code vs. many short lines?
User 240 said: Which is better, to have one long line of code or to have about half a dozen shorter lines of code?
Professor Humphreys said: Generally, the latter, although this is a style issue and sometimes it's just personal preference..
Command Prompt
User 200 said: Sorry to repost this in an entirely new thread, but I didn't see a reply option on my old post:
Is it possible to go back through directories in the command prompt without closing and reopening it entirely? I went through the command prompt to compile and test my Hello World program, so I was at:
C:\student\workspace\Hello World\src\
and I wanted to go back to my workspace folder and test my UseThree program right afterwards. Is it possible to get to my folder
C:\student\workspace\Use Three\src
without closing and reopening the command prompt?
When I tried using "cd" to move backwards, I kept getting a message saying
"The system cannot find the file path specified"
Professor Humphreys said: cd ..
CS 101-E Lab Submissions
User 449 said: For submitting the CS 101-E labs, it says that you may re-submit files as many times as you like. Does that mean that the following scenario is legit?:
- Submit program X.
- RoboGrade.
- Bad program, so credit is not received.
- Submit program X again (after fixing).
- RoboGrade.
- Credit received!
I am wary of the RoboGrader.
-Joel
User 167 said: Yes, that is exactly right.
This is also true for students in 101, but for 101 students you can only keep doing this as long as you do it from a lab computer during your assigned lab time. 101E students can do it any number of times before the lab is due.
Professor Humphreys said: Yes. You can re-robograde as much as you like.
The pattern is:
submit
robograde
curse
fix
submit
robograde
curse
...
submit
robograde
HOORAY!
javac
User 355 said: When I type the javac command in, it says that javac is not a recognizable command...what's wrong??
Professor Humphreys said: It's probably not in your path. You need to follow the installation instructions on the course website, or see a TA with your laptop.
Invalid Directory in Command Prompt
User 106 said: When I use the command prompt window to compile my program, I use "cd workspace," but it returns with "Invalid Directory." When I use "dir" to search the directories in my home directory, it shows my workspace to be there, but I can't get to the program.
Professor Humphreys said: So you type "dir", and see the "workspace" directory in the output listing, but when you then type "cd workspace" you get an error?
That is quite mysterious -- I can't think of why that would happen. You might be running into some transient errors with ITC's home directory service; we had a few issues with that in the lab this morning.
User 167 said: Makes sure you're using the right name - if it's called 'workspace', then "cd workspace" should work, but if you've given the workspace folder a different name, then you have to use that name instead (for example, if it's called 'myWorkspaceFolder', type 'cd myWorkspaceFolder').
Lesley said: When you're in the directory where your workspace is, and you do 'dir' and it shows up there, try next typing 'cd ' and then pressing the tab key. This will magically make the first directory alphabetically be fully typed out after cd. Continue to press the tab key to make your way through the directories alphabetically until you see your workspace directory's name, then you can press enter to continue. You can also do 'cd w' and then press tab to shorten up however many to go through if your workspace directory starts with a w.
how do i reply
User 355 said: how do i respond to a post?? (i feel like an idiot...)
User 14 said: Click "reply" next to edit and delete right underneath the text of the message. So you should see Edit | Delete | Reply. Click reply
eclipse
User 221 said: In the video that we were supposed to watch before the lab they used eclipse to write the program. I downloaded drjava but I can't find eclipse. Everyone else is talking about typing it into notepad... Since I'm in CS101 can I just wait until lab and they'll tell me what to do? Do I even need to bring my laptop to lab? Thanks in advance.
Professor Sullivan said: Hi Julianne,
Please sett the instructions on our web site for "Setting up your computer." Everything that you need is there. You (and your colleagues) should all be using Eclipse. If you get stuck, bring your laptop to the 101 Office Hours for help from the TAs.
KS
Using a Mac
User 124 said: I've downloaded Eclipse, but I don't know where or how to use the command prompt as seen on Windows. Professor Sullivan said that the java application was already installed on a Mac, but I can't find it. So, what should I do about this?
Professor Sullivan said: None of the Windows command line stuff applies (at least not in the same way) to the Mac.
Just run Eclipse and try to write an compile the HelloWorld program. It should just work! If not, see a TA during office hours Sunday, Monday or Tuesday eve, or see my in my office hours for help.
KS
Professor Humphreys said: You can do all the same stuff from the "Terminal" program. Instead of "dir" use "ls".
lab0 - compile
User 546 said: I'm trying to compile the program putting "javac HelloWorld.java" in the prompt, but it is saying that 'javac' is not recognized as an internal or external command, operable program or batch file.
Do you know why? The rest of the things before are equal to the assignment video. And I clicked Run in the Eclipse just to test and it worked (the Hello, World showed up in the window...
Thanks!
Professor Sullivan said: Hi Camila, Please see the directions for "Setting Up Your Own Computer," on the web site, and specifically the part about setting your search path.
Question about grading
User 71 said: Is it true that as long as it can be compile and runs properly and has the desired function it will be graded with 100, or the program has to be exactly the same as it appears in the book?
Also, is it cool if I use Jdrjava(instructed by the book) instead of Eclipse, so I don't have to compile and run somewhere else?
Professor Humphreys said: As long as the program behaves as specified, it will get credit.
You need to use Eclipse.
Professor Sullivan said: You said ...
so I don't have to compile and run somewhere else?
You can use Eclipse anywhere you can bring your computer. Just install it on your machine following the instructions on our web site: setting up your own computer.
lab0 - compile 2
User 546 said: I couldn't reply the other message...
I did what is written in the "Setting up my computer" but it didn't work. It is saying there that we should put in the path: C:\Program Files\Java\jdk1.6.0_04\bin;c:\Program Files\Java\jre1.6.0_04\bin
But I only have the "jre" ... I dont have the "jdk"...
Do you know why?
Thanks!
Lesley said: It is very important to follow the directions exactly as they appear on this page #10 specifically:
Visit http://java.sun.com
Under popular downloads (on the right) click on Java SE
Next to JDK 6 Update 4 click on Download
Professor Sullivan said: You must not have downloaded the JDK properly. Try again. Be sure to dowload the JDK.
Subscribing problems
User 337 said: I can't subscribe the announcements and technical help programs.
Professor Sullivan said: You'll need to provide more information in order that we might diagnose the problem you're having.
Question about replying
User 344 said: Can only teachers/TA's reply to posts in the technical help forum? Because I don't have a reply button here, but do have one in the social forum.
User 14 said: Ah, you're probably right about this, and that might explain the earlier post about not knowing how to reply. It might be that way by design, but one of the professors would know more about this.
User 14 said: Can one of the professors and/or someone familiar with the set up of the site address this question?
Professor Sullivan said: We currently have the technical help forum set up for faculty/TA replies only. We can revisit this decision if there's a push for that, or we might consider setting up a student help-each-other forum. Let us know what you think!
Run the Programme "UseThree"~
User 161 said: When I ran the programme "UseThree", all the words and punctuations lied in different lines,
it appears like:
Hi,
Alice
,
Bob
,
Lucy
.
Why not "Hi, Alice, Bob, Lucy."
Thanks!!
Professor Humphreys said: You probably used "println" instead of "print". Please read the portion of the book that describes the difference between these functions.
C:\ to J:\
User 100 said: How do you switch from the C:\ to the J:\ in the command prompt?
Professor Sullivan said: Just type
J: at the command prompt
RoboGrader
User 449 said: My question is similar to one posted under the thread title, "Question about Grading", though I am still mildly flummoxed by this RoboGrading beast, and I quest for clarity:
How precise does the output have to be?
For example, one of the programs we have to write for groupwork requires computation of rise, run, slope, and distance. Would the three following outputs be received the same by RoboGrader? (assuming the values were correct):
Output 1:4
3
1.3
5
Output 2:
4 3 1.3 5
Output 3:
Rise: 4
Run: 3
Slope: 1.3
Distance: 5
-Joel
Professor Humphreys said: Once you write the program, you can just run the robograder and see what it does!
Professor Sullivan said: Joel,
This is a great question, and precisely the kind of question that a really good software developer would ask. The problem that you've identified is that the
specification is incomplete: it doesn't specify the output format. Problems of this kind often lead to conflicts (e.g., lawsuits), where the developer think he or she has done the work that was required, and the customer begs to differ. It's very important in such cases to clarify the specification before too much time has been invested in coding.
We will now clarify the specification. Each output item should appear alone on separate, adjacent lines, in the order indicated in the assignment. I'll go update the assignment now.
Thanks for asking!
Kevin Sullivan
Lab Quiz 1
User 380 said: If you put 0 0 0 into the program you get 0/0 for the values of cyan magenta and yellow and the program displays NaN. Is this okay, or do we need to make it output 0s for these values?
Professor Humphreys said: 0 0 0 represents pure black; your program needs to get this right.
This is covered in the "Testing Your Program" portion of the assignment.
Group Assignment question
User 31 said: Directions for the fifth program are written as follows:
Write a program QuadraticEval.java that reads in three double values, a, b, c, and x, from the command line and that prints the result of evaluating the expression ax2+bx+c.
My question is whether all the program is required to do is to have three inputs from the command line (a, b, and c) and output (ax2+bx+c) in the terminal window. Seems almost too easy.
Professor Sullivan said: Oops! The specification should have said, "reads in
four double values, a, b, c, and x, from the command line ..." Yes, it's not a hard program to write! --KS
Need help with the output's format.
Professor Humphreys said: can you please tell us which ones you think are ambiguous?
Also you can always run the robograde script after you have submitted if you are not sure.
Professor Sullivan said: English-language specifications are notorious for their ambiguity and incompleteness. In practice, it's usually impossible to make them satisfactoryily precise and complete (but we try). For this reason, in the industrial
engineering of software (as opposed to
amateurish hacking), natural language (e.g., English)
specification are supplemented by other approaches. In particular,
software testing is an important practice. Testing means that you run a program, giving it known inputs, and you check to see whether its actual outputs match those known to be correct for the given inputs.
(Question: If a program produces the correct output for one test case, can you conclude that it produces the correct output for all test cases?)
Test cases constitute a partial but precise specification of the required behavior of a program. The incompleteness and imprecision in our CS101 specifications (whether intended or not

) will give you an excellent sense of the kinds of ambiguities that you'll face when you're developing software in whatever field you end up working in.
Our automated on-line testing mechanism, by contrast, will give you a good sense of the power of testing to help developers to develop programs that
satisfy precise, documented specifications. These specifications are not written in English, but in
code -- test code that runs your code to see if it behaves correctly in certain cases!
Assignment 1
User 71 said: As for the Histogram, should we print out the amount of random values in a certain sub-integral or its probability of percentage?
Professor Humphreys said: Good question! The assignment page says to output "the values in the array", so don't reinterpret the histogram counts as probabilities, just print them out.
Professor Sullivan said: Right. It's just a histogram: a count of the number of elements in each interval. (What would you do if you wanted to output an estimate of the probability of a random draw falling in any given interval?)
Converting Strings to booleans
User 200 said: I tried using the following syntax:
[source code removed by admin]
to cast a string from the command line into a boolean. When I compile the code on Eclipse, it doesn't display any error messages, but when I try compiling it on the command prompt, I get the following error message:
"cannot resolve symbol
[code information removed by admin]
1 error"
Did I write the code incorrectly, or is my computer just not recognizing the Boolean class?
(Edited by Greg Humphreys - original submission Saturday, 19 January 2008, 04:52 PM)
Professor Humphreys said: I edited your post to remove code that you really should NOT be posting on the internet. Please re-read the course collaboration policy.
In repsonse to your specific question, the solution code looks identical to the code I cut out, so it's hard to say what's going on. It might be possible that your version of Java is not correct, but it's really hard to say.
Try running your same code on other computers (like the ones in stacks) and see if it works there. If so, then your installation of Java needs to be redone with the latest versions of everything.
Lesley said: This might also be a result of an old version of javac even if java is version 1.6 (typing java version produces a 1.6 version but javac still gives this error).
Instructions for solving this problem on Vista, as done right now in the Stacks:
Go to Control Panel (classic view) > System, then click Advanced settings on the side menu
Click on the "environmental variables" button in the window that pops up (bottom of window)
Go to the SYSTEM variables, not the user ones (these are in the lower half of the window that pops up)
In the PATH variable, put the directory to the JDK you have installed in there (ie. edit the variable and at the BEGINNING add C:\Program Files\Java\jdk1.6.0_04\bin;)
Exit and restart the command prompt
What does it mean?
User 71 said: When I try to run the StdGaussianHistogram.java I typed "java StdGaussianHistogram 1000" and it said this:"Exception in thread 'main' java.lang.ArrayIndexOutofBoundsException:100 at StdGaussianHistogram.main<StdGaussianHistogram.java:25>",
what does it mean?
Professor Humphreys said: It means you tried to access element 100 of some array, but the array is smaller than that.
easy way to generate an error like that:
public class MakeError {
public static void main( String[] args ) {
int some_array[] = new int[100];
some_array[100] = 5;
}
}
Oops, some_array is a 100-element array, so only slots 0,1,2,...,97,98,99 are legal.
Assignment 1-again
User 71 said: Because there are two arrays in this program, and basically I want to to do the problem by using "for" loop with two variables of "i" and "j". But because those two arrays don't have same amount of elements, if I still use the for loop and if say the first arrays has 1000 elements and the second has 100, the loop command basically doesn't work as I want it to do. Because the second arrays has 100 elements, I don't want to write 99 lines of "else if". What else can I do?
Professor Humphreys said: I apologize, but I'm not sure I understand your question.
The assignment says to loop twice. The first loop populates the array (it will run N times) and the second loop will print out the array (it will run Number-Of-Array-Elements times).
The standard output
User 189 said: What does "on the standard output" means in the team assignment? Is System.out.print()" good for the homework? I typed in "StdOut.print(d)" and the system said "StdOut can not be resolved".
Thank you.
Professor Sullivan said: System.out.print() and System.out.println() do indeed output data to what we call the "standard output."
By default "standard output" is connected to the console. In Eclipse output to the console is presented in a panel down at the bottom of the screen. If you're using command line commands, standard output appears in the command window (on Windows) or the terminal window (Mac) in which you're running the program.
When we learn (shortly) about input/output "redirection" you'll see that it's very easy to connect the "standard output" of a program to other outputs, e.g., to send the standard output of a program not to the console but to a file so that the data can be saved for later use.
The short answer: System.out.print() and System.out.println() are just right!
Java Library Documentation
Professor Sullivan said: Here's a
link to all the relevant on-line documentation for the Java libraries.
It's worthwhile early in the semester to have a look at the following classes:
- Math
- Integer
- Double
- Boolean
Lab Quiz 1
User 199 said: During the quiz will we be able to look at the instructions for the quiz, and therefore the formulas to convert between the different colors? Or, do we need to memorize the formulas?
Professor Sullivan said: You don't have to memorize the quiz. Accessing the quiz web page and Eclipse, and you should be able to write, compile, run, test and submit the program.
TA office hours
User 364 said: I couldn't find on the website a schedule for ta office hours. Does anyone know what time they are today and tommorrow?
Professor Humphreys said: They are 6-10 Sunday, Monday, and Tuesday, in Thornton stacks.
MixedNumberTypes
User 393 said: The program will not let me submit MixedNumberTypes and I believe it is because it is not listed under the list of the finals that is supposed to be submitted.
Professor Humphreys said: Whoops! Fixing, check back in a minute or two.
Thanks.
Lab Quiz 1
User 223 said: In the directions it states that the program should take 3 intergers (RGB) and convert them to 4 reals (CMYK). Does this mean that your program should only work if intergers are entered. Technically if it works if three real numbers are entered is that ok too as long as it also works for intergers.
Professor Humphreys said: The program only needs to work when integers are supplied. If it behaves reasonably when other types of input are supplied (like reals, as you point out), that's basically a bonus, and good for you for realizing this.
We won't be testing anything outside of the specification, though, so it's unnecessary.
Professor Sullivan said: This is a great question. It goes to the question of what we mean when we say that a program satisfies its specification. One possible answer is that a program
does at least what the specification requires (and if it does more that's okay). A different answer is that
it does at least what the specification requires and no more. For purposes of the current assignment, your program must do at least what the specification demands. If it can do more, that's okay. In some systems, it's important to ensure that a program can do no more than it's asked to do. For example, if software is controlling a safety-critical device (such as a fast-moving train full or a radiation treatment machine for cancer patients), it is important to know precisely what the software will do for all possible inputs: it should do no more than has been explicitly stated. One can handle this in the specification by saying something like this:
any other input is considered erroneous, and any such case should be handled as follows: ... details
changing directories
User 128 said: This is a general question. I know you the command "cd" will move you to a more specific directory, but what is the command if you want to move back "up" the hierarchy to a more general folder?
Professor Sullivan said: This question was answered in an earlier post on the technical help forum. Thanks, everyone, for checking earlier posts.
Groupwork 1
User 71 said: Will we lost score if we put (or omit) names before the values in the printout while the assignment does not ask us to do so.
Professor Humphreys said: Yes.
The assignment specifies what your program should print out. You should follow the directions in the assignment.
If you feel that the directions are ambiguous, by all means, let us know.
Also, if you're ever confused about precisely what the output should look like, you can <i>always</i> submit your program and run the robograde test!
Groupwork 1 Question 9
User 99 said: I've tried to figure out what this problem means for a while and I've gotten nowhere.
Write a program DeMorgan.java that reads two boolean values from the command line, stores them in two boolean variables b1 and b2, and prints out true if the negation of the conjunction of the values is equal to the disjunctions of the negations of the values, and that prints false otherwise. The bolded text is primarily where the confusion lies.
Professor Humphreys said: Somehow, this question does use a lot of logic jargon.
Here's a glossary:
conjunction: "and"
disjunction: "or"
negation: "not"
Re-submitting Corrected Programs
User 179 said: I first submitted one version of Distance.java that was incorrect, so I ran through Robograde to test and took it off. I fixed the program so that now when tested in the command prompt it works as directed, but when I submit the new program and check on Robograde, it still uses the first program I submitted. What should I do?
Professor Humphreys said: When you resubmit, it overwrites the previous program, so my guess is that you didn't resubmit properly.
Professor Sullivan said: It's possible that you didn't
save the file in Eclipse. In that case, the version on disk might be old, even though you're working on a newer version in Eclipse. Hit Control-S (hold down Ctrl while pressing S) to save.
boolean
User 166 said: In problem #3 from the group work my group in unsure about the format for typing in a boolean value. Also, is the answer supposed to print out true and false?
Professor Humphreys said: You should pass the boolean to System.out.println().
And just type "true" or "false".
Uploading Group programs
User 113 said: We seem to be having trouble uploading Echolnt.java. Although it is listed as one of the programs we need to include, after we have selected it and hit the upload button, we receive the message:
I'm sorry, but Echolnt.java is not one of the files for this assignment, so I'm skipping that one.
You didn't give me any legal filenames to upload. Please try again.
What should we do?
Professor Humphreys said: Try replacing that lowercase ell with an uppercase eye.
RoboGrader
Professor Humphreys said: Hmm. It probably means I broke the robograde script this morning.
Please bear with me...
Professor Humphreys said: Okay, this has been fixed. Sorry about that.
Quiz 1
User 91 said: Are we allowed to consult TAs for help on the quiz prior to Thursday?
Professor Humphreys said: You are *encouraged* to do so.
Group Assignment #3 - Boolean
User 52 said: I'm having a problem with the command prompt for the boolean exercise.
for some reason the command prompt cannot resolve the symbol "parseBoolean"
but in the previous exercise the command prompt worked fine in resolving the symbol "parseDouble". I had no problem using command prompt for the previous two exercises.
User 13 said: See previous post "
Converting Strings to booleans" please
Lesley said: Please see the other thread on this (titled something like Strings and booleans). Your java and or javac version is out of date and you will need to go update your path variable.
arguments
User 555 said: when ever i use a write a program on my computer that needs an argument to be entered i get the following error mesage.
java.lang.NoClassDefFoundError: 3
Caused by:
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Exception in thread "main"
java.lang.ClassNotFoundException: 3Native Method)
Professor Sullivan said: How are you editing, saving, compiling and running your program?
User 167 said: You need to type "java
"
For example,
java EchoInt 3
I'll bet you typed something like
java 3
which would produce exactly the error you got above.
This is because 'java' is itself a program that takes several arguments. The first is the name of the java program to run (in this case "EchoInt"), and the remainder of the arguments go to that program. So "java 3" tells java to look for a program called "3", which doesn't work; but "java EchoInt 3" tells java to run the program called "EchoInt" and pass it an argument of "3".
Group Assignment problem #7
User 151 said: I have tried writing a program And.java, but no matter what I give as arguments, even if both arguments are the same, the output is false. I am at a loss as to why this is happening, as I have tried several things with no result.
Lesley said: There are a number of things you could do to determine what is going on.
Have you recently saved and recompiled the proper program? You need to do both if you want your program to do something different than the last time you compiled it.
Is your algorithm correct? Try printing out the arguments, and seeing if they are what you expect. If they're correct, then you will need to inspect your algorithm to see why it isn't doing what you want it to do.
If you still have problems, you might consider coming to TA office hours tonight. It's hard to diagnose a problem with an algorithm without seeing the algorithm in use, and as you can't post it here, that leaves you with few options.
Home Directory and Mac
User 124 said: Eclipse won't allow me to set my Home Directory as my workspace... any ideas?
User 167 said: Eclipse has a bug (registered as
bug 44735 that screws up the file locking for some NFS file systems. I haven't seen this bug manifest except when a Mac user attempts to set the workspace to a directory on an NFS filesystem such as the one ITC uses to host home directories. Essentially, the filesystem doesn't support a particular form of file locking that Eclipse wants to use to lock the workspace.
The error message you'll get is either that "the workspace is in use or cannot be created" or a long error message about file locking.
I'm looking for an elegant solution to this; so far I haven't found one, but here's an ugly workaround if you have this problem:
Ugly Hack for Disabling Eclipse Locking on Mac OS XFind your Eclipse.app (probably in /Applications/eclipse).
Right-click (or control-click) on it and select "Show package contents".
This pops up a window containing a single folder called "Contents". Go into this folder, and into the sub-folder called "MacOS".
In "MacOS" you'll find a file called "eclipse.ini".
Open eclipse.ini in your favorite text editor, and add the following line to the end of the file:
-Dosgi.locking=none
This disables the locking, and should allow you to use the workspace in your Home Directory.
This is a fix for
MAC users only, and since it involves hacking Eclipse's configuration files you should
ONLY; do this if you have the error above.
I'll keep looking for a better way to do this.
Robograde DeMorgan
User 130 said: In our DeMorgan program, the robograde tests b1 is true and b2 is false twice. The program said the first test was false and the second test was true. The same happens when b1 is false and b2 is true on the robograde progam. Testing the program in Eclipse and on the Command Prompt, we get the right answer in all cases.
Professor Humphreys said: The DeMorgan robograder tests the following combinations:
false, false
false, true
true, false
false, false
error message
User 240 said: What does this error message (when trying to run the program through Command Prompt) mean?
Exception in thread "main" java.lang.NoSuchMethodError: main
User 14 said: This means that java can't find your main method, which is where it starts executing code in your program. Make sure you typed correctly "java (programName) (arguments)" in the command prompt. You can get this error if you type in "programName.class" instead of just "programName". You can also get this error if you didn't compile your program before running it.
error from command prompt
User 210 said: when i try to run the program "HelloWorld" in command prompt, an error message appears: exception in thread "main" java.lang.unsupportedClassVersionError: bad version number in .class file
User 14 said: Yufei,
This happens when your jdk version (the program you use to compile your code) is different from your jre version (the program you use to run your code). Please see the directions for "Setting Up Your Own Computer," on the web site, and make sure you follow them exactly. Particularly, make sure your java jdk and jre are the same version. Any older version of the java
jre should be uninstalled. If you still need help setting this up, come to the TA office hours.
RoboGrader
User 194 said: After submitting the programs and using the RoboGrade program, the program first said that our programs were incorrect because the output didn't match. However, after resubmitting it over and over again- we eventually got full credit on the programs submitted (without changing anything in our original programs). A TA suggested we mention this on the forum because many other students have had similar problems where RoboGrade first says that the programs are incorrect, but then after resubmitting they are correct.
Professor Humphreys said: When robograde said that the output didn't match, was it right? It shows you the output of your program and the solution program, so you should easily be able to look at the output that it's comparing.
User 13 said: The problem is that, when the students run the program on the desktops, it works. But when they submit to the RoboGrader, it does NOT. And they submit it many times without changing the file, finally accepted by the RoboGrader. (This is the situation the students described)
Another group of students mentioned the same problem.
Professor Humphreys said: I understood the post, but without information about the nature of the failure it's very hard to figure anything out.
For example, when robograde says that the outputs don't match, what are the outputs? If someone can reproduce this error and post the output on the forums I might be able to see what's going on.
Mixed Number Types
User 240 said: I started writing my code for the MixedNumberTypes.java program (#13 of the group assignment). I copied the line that they gave us exactly, compiled and ran the program, just to make sure everything was in working order before I continued. However, instead of printing out 1/3, like it's supposed to, my program printed out 0. What did I do wrong?
Professor Humphreys said: What did you do wrong? Nothing.
1/3 in java is zero. Welcome to the world of integer arithmetic.
Try 1.0/3.0 and see if you like that answer better :)
Professor Sullivan said: Jennifer,
What you're seeing is the point of the exercise. The expression 1/3 denotes
integer division of 1 by 3. 1 divided by 3 in the integers is
0 remainder 3, which is why the answer is 0. If you write 1.0/3.0, a different kind of division is indicated: namely
floating point division. In this case, you'll get an answer that looks like one third approximately, as a decimal number.
As a programming you have to be able to recognize when integer operations will be performed and when floating point operations will be performed. In brief, if all of the operands in an expresssion are of type
int then in most cases, you'll get integer operations. If any of the operands are of a floating point type, then all of the operands are typically converted to floating point values and floating point operations are used.
Kevin Sullivan
difference between"print" and "println"
User 210 said: first time i tried to type "print"
2nd time i typed "println"
surprisingly, the outcomes were the same
I'm wondering what are the differences between "print" and"println"
Thanks
Professor Humphreys said: "print" prints.
"println" prints, and then begins a new line.
Mixed Number Types (2)
User 323 said: Referring to the same question asked in 'Mixed Number Types':
Can you possibly say "1/3" instead of 1.0/1.3? That solved my problem (Using quotation marks), but I was wondering if that was the intention of the question.
Lesley said: "1/3" is a String. It is not equal to 1.0/3.0 which is a number.
1/3 is the int 1 divided by the int 3. Please see Professor Sullivan's detailed explanation on why this is 0.
1.0/3.0 is one-third the floating point (decimal) number as you expect it.
Try adding "1/3" + "2/3", ie. System.out.print("1/3" + "2/3") - I think you won't get 3/3 or 1 like you seem to want!! What will (1/3 + 2/3) yield? What will (1.0/3.0 + 2.0/3.0) yield? This is the point of the exercise.
"javac" problems
User 105 said: I have quadruple checked that I added the info into my PATH like the instructions on the website, and when I enter "java -version" into the command prompt I get a java version number, however whenever I try to compile anything I am told that "javac is not recognized as an internal or external command..." even when I'm sure I'm in the right directory.
Help?! Thanks.
Lesley said: It's possible that you don't have the JDK installed but rather just the JRE (which doesn't contain javac). If your directory that you added to the PATH variable doesn't have JDK in it, then you'll need to reinstall the correct version of Java accordingly.
If you do have JDK in your PATH variable, make sure it points to /jdk_(version number)/bin because javac lives in that bin directory.
After modifying the PATH variable, you will need to exit and restart the command prompt.
Professor Sullivan said: If anyone is struggling too much with installing the software, see the TA in office hours for help
reply button...
User 550 said: Is it just me, or is there no way to reply to someone's post in the technical forum?
thanks
Andrey
User 167 said: Only TAs and the profs can reply to the technical forum. If there's a lot of demand for letting students reply as well, that can probably be changed.
Errors for min in color program
User 282 said: I don't know what I'm doing wrong, but eclipse doesn't like the way I'm using the min method. Has anyone else gotten these error messages?
Syntax error on token "min", { expected RGBtoCMYK/src RGBtoCMYK.java line 11 1200976283187 49
Syntax error on tokens, Expression expected instead RGBtoCMYK/src RGBtoCMYK.java line 11 1200976283187 50
User 167 said: Make sure that you have the right number of opening and closing curly braces ({}) and that they're all in the right places. If that doesn't work, and you still can't figure out what's wrong, bring your code into office hours, and we'll take a look at it.
Eclipse Won't Let me Access My Workspace Anymore
User 53 said: I was writing a while loop and I think I may have accidently created a program that runs forever. I can no longer open up the workspace that I saved the java file in. Windows won't let me delete the program file either. Help. I've tried restarting my computer.
User 167 said: When Eclipse opens a workspace, it creates a file
/.metadata/.lock that marks the workspace as "in use". This prevents multiple copies of Eclipse from accidentally editing the same workspace. When Eclipse stops using the workspace, it deletes this file.
However, if Eclipse crashes or otherwise gets forced to quit, it frequently leaves the lockfile behind, and so it will think that the workspace is still in use.
If the error you get when you try to use the workspace is that the workspace "is already in use", then the above is most likely what's happened. To fix it, go to the ".metadata" folder in your workspace and delete the file called ".lock"
In the future, if you run a program from Eclipse that goes into an infinite loop, press the little red square over the Eclipse console to force your program to stop.
Mac Terminal
User 323 said: I am not sure how to switch to my J: drive when using Terminal on my Mac.
User 167 said: Instead of mounting as a separate drive, on a Mac the home directory appears as a networked drive in the /Volumes folder.
Type "cd /Volumes/
" in the Terminal, where is your UVa network ID, to move to your home directory.
Lab1 EC
User 343 said: What exactly is the "more difficult
edge case mentioned above" that gives us 5 pts extra credit on the colors lab? What must our program do differently as opposed to just going for the basic requirements?
Professor Humphreys said: (r,g,b)=(0,0,0)
Professor Sullivan said: That's right: (0,0,0) is a legal input according to the specification, but the formulae provided do not work for this value. Why? What color does (0,0,0) represent? What is the correct CMYK equivalent? You will get an extra 5 points for handling this case correctly. Hint: You probably need to read ahead about "conditionals" (
if statements).
Lab Quiz
User 95 said: For the lab quiz, will we be given the formulas for cyan, magenta, etc.? And will it only be the program we have to create and run or will there be an actual pen and paper quiz?
Professor Humphreys said: You will have access to the lab web page during the lab.
There is no written component to the quiz.
Professor Sullivan said: You have to write the program :-) We're just looking to be sure that you can write a program that implements simple arithmetic conversions without help.
Assignment 1
User 251 said: For part two of the assignment, is there a specific method for splitting the interval [-5.0, 5.0] into equal sub-intervals?
Professor Humphreys said: Are you asking if Java has some sort of built-in support for this?
In that case, the answer is no - the splitting is just conceptual. You will just create an array with the right number of slots, one for each sub-interval.
Laboratory Quiz
User 90 said: In the instructions for the first lab quiz it says "The program should assume (and not check) that the inputs are between 0 and 255." Does this mean it assumes you input numbers between 0 and 255, or should we create a way for an error message to be output when a number greater than 255 is entered? Thank you!
Nic
User 14 said: The specification says that you should assume (and not check) that the inputs are between 0 and 255. This means that when your program is run, you can assume that the user gives it an integer value between 0 and 255, and you don't need to check this within your code.
Group Assignment # 5
User 432 said: When I run my program for QuadraticEval.java through Command Prompt, I get a message saying, "Exception in thread "main" java.lang.NoSuchMethodError: main." Just wondering what the means and how to fix the code.
User 14 said: See the earlier post titled "error message" about 15 posts down to answer why this can happen.
Assignment 1: Intervals
User 380 said: When we break up the interval [-5,5] into the smaller intervals, does it matter which of the endpoints we exclude and which one we include (i.e [-5,-4.9) or (-5,-4.9])?
User 181 said: This is a very good question. I think there is a small problem with this range. We'd better consider [-5,5] as [-5,5), in which each interval is like this: [-5,-4.9), [-4.9,-4.8),......,[4.9,5).
Professor Sullivan said: >We'd better consider [-5,5] as [-5,5), in which each interval is like this: [-5,-4.9), [-4.9,-4.8),......,[4.9,5).
That's almost right. The interval [-5,5] is the interval [-5,5] not the interval [-5, 5). In other words, -5 is included in the interval on the left and 5 is included on the right.
But the question remains: what are the intermediate intervals. The specification was indeed ambiguous in this regard. Zhiheng has given a fine resolution. Let's disambiguate as follows. The sub-intervals are like this:
[-5,-4.9), [-4.9,-4.8) ... [4.8, 4.9), [4.9, 5.0]. The last sub-interval on the right is different than the rest, being "closed" on both ends.
Professor Humphreys said: [Post removed because of complete and utter incorrectness]
Professor Humphreys said: Please ignore my previous post about ranges and so forth, it demonstrates a complete lack of understanding about math and how numbers work.
Sorry.
Professor Sullivan said: Hi Everyone: This is exactly how software development works in practice. We talk through problems and work out understandings of (1) precisely
what is to be done, and (2)
how do get it done, e.g., by programming in Java. In many cases, in fact in general in practice, (1) is actually much harder than (2).
The current discussion is an example. In the problem at hand, we ask you to use the basic Box-Muller formula, which takes
uniformly distributed pseudo-random numbers in the interval [0.0, 1.0) as inputs (and these are indeed the numbers that Math.random() generates for you).
But then you run these numbers through the Box-Muller formula, and what you get out are (pseudo-) random numbers from (approximately) a normal or Gaussian distribution. Such numbers cluster around 0.0 but in principle can be arbitrarily large negative or positive numbers. The probability of picking such
outliers is low, but it is certainly possible. (In fact, in applications such as options pricing, it's important to calculate the probability distribution on the selection of such outliers -- Google for
order statistics). So, indeed, the random picks that your program will generate can be >= 5. Unless you generate a very large number of samples, you're unlikely to see very many numbers outside the interval [-5,5]. But there can be some. When you create your histogram, we're asking you to account for such
outliers in the [-5.0, 4.9) and in the [4.9, 5.0] intervals, respectively.
Assignment 1
User 343 said: The directions ask that the values in the array be outputted on a single line in the command promt, but my outputs (for all my programs) always wrap down the next line in the command prompt once they reach the end of one line. Is there java code that will make it all appear on a single line or would I have to change something in my command prompt settings in some other way?
Professor Sullivan said: See the difference between print and println
computer lab
User 406 said: last time i went to computer lab at Olson i did not have a user name and a password, i signed in with the temporary user name and password that they had. i asked one of the TA s and he told me it should have been emailed to me, but i have not gotten any email concerning this issue.
User 35 said: please wait with patient, we will solve that, thank you.
Lab quiz error
User 188 said: Hi:
For the most part my code seems to be working, but for some reason whenever I put in an input other than 255 255 255, it comes up with:
cyan = NaN
magenta = NaN
yellow = NaN
black = 1.0
When I put in 255 255 255 everything is 0.0.
Can anyone tell me what NaN is supposed to mean? I can't see what I'm doing wrong!
Thanks,
Becca
Professor Humphreys said: NaN stands for "Not a Number". It's the sort of thing you would get, for example, if you tried to divide by zero. That would be the first thing I would check -- look for anywhere you are doing division and PRINT OUT the denominator. See if any of them are zero or otherwise goofy.
One more question about the intervals
User 161 said: Are we asked to count and print out the number of "random numbers" falling in each subinterval?
If they are intervals with 0.1 width, then there will be 100 intervals...Then when we output the values in the array, there will be an array with length 100. But why are we asked to print out an array "from index 0 to index n-1"?
Or should we divide [-5,5] to n subintervals?
Thanks!
Professor Sullivan said: There are n numbers in the range 0 ... n-1. Check it out. Suppose n=3. An array ,
a, with n=3 entries will have elements
a[0], a[1], a[2]. See? The indices go from
0 to
n-1.
Wrapping
User 343 said: This forum doesn't let me reply to my own post, but this is a continuation of my previous "Assignment 1" post. I understand the difference between print and println. I'm having the trouble that even when i use "print", my text output from codes still wraps down to the following line in the command prompt. It's all technically the same line, it just gets carried down to the next line when there's no more room. Is this ok (i.e. still considered one line) or is there something i can do with my code to correct this? For example, is there a way to make a horizontal scroll bar appear in the command prompt so that my output will continue forever on one long line if I wish to do so?
Professor Sullivan said: Oh, I see. It is actually one line. There's no embedded "carriage return" or "line feed" characters. The output window, however, does its own thing and wraps long lines. Here's a good way to see what's really going on.
If you usually run your program like this, at the command line
java myprogram
Do this instead
java myprogram > filename
Instead of printing on the console, the program output will be "redirected" into the file given by
filename. You can then look at that file using any old text editor, e.g., on Windows, WordPad. In a program like WordPad I believe it'll be clear that it's really just one long line of text.
KS
Lab Quiz Extra Credit Question
User 270 said: Is "the more difficult edge" mentioned in the quiz 255, 255, 255? What kind of output from the program do we need to have for that input?
Professor Sullivan said: First, ask yourself, what color does this represent? What if I add the brightest red, the brightest green, and the brightest blue light together? What do you get? Next, run those numbers through the formulae and see if the result makes sense. Remember, what the CMYK numbers indicate is how much of each color of ink to put on the paper to reproduce the given RGB color. Does the result make any sense? If so, then that's probably not the edge case we're talking about. There are values for which the formulae "blow up." What are they?
Re: Assignment 1:Intervals
User 380 said: "So, indeed, the random picks that your program will generate can be >= 5. Unless you generate a very large number of samples, you're unlikely to see very many numbers outside the interval [-5,5]. But there can be some. When you create your histogram, we're asking you to account for such outliers in the [-5.0, 4.9) and in the [4.9, 5.0] intervals, respectively."
Does this mean you want the 'outliers' in the first and last indexes of the array? I thought we had to account for the outliers in separate variables 'leftTail' and 'rightTail'.
Professor Sullivan said: Oh good grief. You're right. I should have re-read the assignment. Sorry. Yes, account for the outliers in the outlier variables. That's exactly right. --KS
quiz 1
User 473 said: How to express min{c,m,y} in Java? Thank you!
Lesley said: Taken from the quiz page:
Hint: Math.min(x, y) returns the minimum of x and y.
The min function will not take 3 arguments, but you can think of a way to use it as it is (taking 2 arguments) to do what you want.
Requirements for Assignment One
User 200 said: I've been reading through posts and the specifics for Assignment 1, and I'm still confused about what the exact requirements are. The requirements specify to output:
- the values in the array, from index 0 to index n-1, all on one line, separated by spaces
- the values of the leftTail and rightTail variables, each on its own line
- the average of the generated numbers, on its own line
Unless I interpreted these directions incorrectly, I see that we have to output the randomly generated numbers, the number of times it fell outside the [-5.0, 5.0] range, and the average of the numbers, but I don't see anything about outputting the histogram itself. Can someone please clarify?
Lesley said: "then account for it by incrementing the corresponding value in the array"
Thus, the array keeps track of how many numbers fall in that range, not the actual numbers themselves... From what I understand.
Professor Sullivan said: Lesley's right.
Lab Quiz EC Question
User 270 said: After looking at the formulae for 1 hour, I still don't see what numbers will "blow up" the formulae. Only numbers I could think of are numbers outside of the range 0 to 255. I tried numerous inputs, and outputs came out fine. I still don't see the edge case mentioned in the quiz. Can you tell me what is that edge case?
Professor Sullivan said: What might cause one of the operations to have an undefined result? Work backwards through the formulae to figure out what inputs lead to that result.
Professor Humphreys said: r=0
g=0
b=0
Converting double to string
User 459 said: Is there a way to convert a double, X, into a String with the same name, X?
(i.e. this is done so in some cases X displays a number and in others - a message).
Thanks,
Vladimir
User 14 said: I'm not sure if I quite understand your question, but if you want to convert a double into a string representation of that value, you can use String.valueOf(x) to do it.
Lesley said: "displays" -> You can print a double without turning it into a String;
double d = 3.14;
System.out.println(d);
is valid code.
You can also concatenate as you wish...
double d = 3.14;
String s = "Pi is approximately " + d;
s now contains "Pi is approximately 3.14"
The only time you would have to worry about this is when you want to use a function that only takes Strings as arguments. Then you need to convert the double to a string. This is most easily done like this:
double d = 3.14;
String s = d + "";
Attempting to do String s = d; is a compile time error.
It is going the other way that is more problematic.
double d = 3.14;
String s = "1";
s += d;
s now contains "13.14" and not 4.14 like you wanted. d += s; is a compile time error. This is why you use Double.parseDouble().
User 167 said: Or, are you trying to use the name of a variable as data?
That is to say, you want a way to do:
double myDouble = 3.14;
System.out.println(
);
so that it prints the exact string "myDouble"?
The short answer is that this is impossible, because Java doesn't support that sort of introspection.
The long answer is that A) there might be a way to do it, but I'm sure if it exists it's very obscure and hard to use, and B) in practice you will NEVER need to do this.
For example, in the above, you'd be typing out the characters in the name myDouble anyway, so you might as well just type System.out.println("myDouble").
I hope one of the TA responses answers your question.
quiz??
User 448 said: i was trying to figure out the quiz today, and i finished it, but i just realized that out of habit i saved it on my J: drive. I went to delete it, but it was already gone. Im wondering what happened, and how i can get the program i wrote back, without saving it to the J: drive.
Professor Sullivan said: John,
If you wrote the program in Eclipse, with your workspace set to J:\workspace, then your program should be there.
KS
Eclipse Freezing
User 380 said: So I have been talking to some people and we have all noticed that Eclipse tends to "freeze up" periodically while you're in the middle of typing and you have to wait a few seconds for it to unfreeze and catch up with what you typed. Is there any way to fix this?
User 14 said: Joseph,
I believe this is not an Eclipse problem, but a home directory problem. Unfortunately, the home directory is often slow or unresponsive. But it is the best place for you to keep your work, so for this semester all we can do is deal with it and hope it doesn't become more than a small annoyance.
practicing the quiz
User 221 said: For this lab quiz and any other quiz, I understand that its ok to work them out ahead of time. However, are we required to delete them from our workspace before we go into the quiz or are we on our honor to not look at our practice java program while we do the quiz? Just making sure :-)
Lesley said: You're on your honor - just like when a professor gives a take home, closed notes quiz: the notes are in your room (you don't have to burn them or something else ridiculous), but you're on your honor not to look at them while taking the test, and your pledge and signature signifies you did not cheat.
You should not even mount your J: drive during lab quizzes, either.
RoboGrade for Color Lab?
User 268 said: Do we get to have the automatic grader check our color program?
I just want to be sure I have exactly the right output.
Professor Humphreys said: No, we are going to robograde after all the labs are in.
You should match the format of the sample output given on the web page.
RoboGrade of Group Work
User 331 said: Is robograde disabled for anyone else besides me? Just wanted to see what was going on.
Thanks,
Daniel McCarron
Professor Sullivan said: Yes. The grading robot is broken. Sorry about that. Will be back ASAP. --KS
I need help with loops
User 440 said: I am having trouble with the HelloFor and HelloWhile problems. I know its group work but I don't understand how to make it say hello world n times. I don't know how to define that.
Matt Cassi
Professor Sullivan said: Matt,
Study carefully the concept of the
for loop. The basic idea is this: whenever you need to make
something happen some number of times (let's say
n times), then you use a for loop. In particular, you do the following:
- initialize to zero a variable (often simply called i or j) that will serve to count the number of times that you've already executed the loop body;
- at the top of the loop you use a a boolean expression involving the count variable (e.g., i or j) to see whether you've already executed the loop enough times; and each time after you execute the loop you increment the value of the counter (i or j) to properly reflect the number of times you've been through the loop.
- Inside the loop body you take the required action (e.g., printing Hello)
If you're having trouble we strongly recommend that you download, run, and experiment with some of the code examples in the book. You should (all) be doing that, anyway.
Ok?
Kevin Sullivan
Professor Sullivan said: By the way, we also
strongly recommend that everyone use groups to work out these sorts of questions. In computing, there's often nothing so useful as having someone to talk to about a particular issue. It's really almost miraculous. I have often struggled for hours, sometimes days, to figure out what's wrong with a program. As soon as I ask someone to come have a look, voila, before they say a word, I see the problem. I'm not sure why it is this way, but that's very much my experience. I guess we think differently sometimes when we're with someone. It can really help. Use your groups. Explain things to each other: the problems you're having, and what you know about how to solve problems. Go beyond the work we've assigned. Do little programming experiments together. Have fun.
Waitlist Protocol for Stacks Office Hours
Professor Sullivan said: Hi Folks,
In the past, once class gets underway, the demand for help from TA's tends to get a little out of hand sometimes. In these circumstances it's important that we serve students in a fair way. So, the best thing to do is to have a
signup list in the stacks, and to have TA's serve students in the order in which they've signed up for help. It's best to limit the attention give to any one student to 5 minutes or so, if there's a waiting line.
Kevin
Fatal Grading Error on quiz!
User 54 said: Hi, When I checked my grade for my Lab quiz today I recieved an error message. The message said, "FATAL GRADING SCRIPT ERROR, PLEASE REPORT THIS IMMEDIATELY AND WE WILL FIX IT." If you could please help me with this it would be greatly appreciated.
Professor Humphreys said: sorry, I'm in the middle of doing the lab grading, those things will be in flux. Very sorry about the panic.
fatal grading script error
User 91 said: my quiz also has an error
Professor Humphreys said: this should be fixed very soon, if not already.
Problems with the quiz grade
User 337 said: When I finished my quiz, I checked it on command prompt and had the correct answers, but the robograde gave me a zero out of 105 points. I'm really confused and frustrated. Can you tell me whats going on?
Professor Humphreys said: Robograde was being a bit temperamental.
Reading the results now, you definitely don't have a zero.
float versus double
User 236 said: So, I have an interesting question. In the lab quiz 1 document, it says such things as "This scheme represents a single color as a four-tuple,
(c,y,m,k), of floating point values between 0.0 and 1.0" and "mixed integer and floating point expressions
."
When I was coding my program for practice and when I went into lab to code, I assigned type float to the variables. I know good and well of type double. In fact, I ran and compiled the program using double or float for the type. However, the reason why I used type float for this quiz was that is what seemed to be indicated in the quiz document (see excerpts in first paragraph), which is deceiving. And, yes I realized that type float did yield accuracy out to a certain decimal place. Given this, I found the use of type float (given the last sentence) justified in the first paragraph of this post and problem 20 of the group work.
In order to make the lab quiz document clearer, it would have behooved him to indicate a type of 64-bit or 32-bit.
Given this, and given that everything in my program was correct (even the extra credit) , I feel that the following is not justified:
"Testing the command 'java RGBtoCMYK 75 0 130'...
Your program produced the following output:
Line 0: cyan = 0.42307687
Line 1: magenta = 1.0
Line 2: yellow = 0.0
Line 3: black = 0.49019605
Running our sample solution with the same command line...
Testing the command 'java RGBtoCMYK 75 0 130'...
Our solution produced the following output:
Line 0: cyan = 0.423076 9230769229
Line 1: magenta = 1.0
Line 2: yellow = 0.0
Line 3: black = 0.4901960 784313726"
I received an 85/105 on this assignment. Twenty points were subtracted from my grade because of the "fuzziness" of specifying double and float in the lab document. I feel that if I am not able to get full compensation, then I should at most get 7-10 points off my grade (especially since they are correct to a specific decimal place: 7th for black and 6th for cyan).
And how my grade for this stands now: it is 85/105
Shouldn't it be 85/100?
Thank You
Best Regards,
Brandon
User 181 said: Any one knows the answer? I have no idea of this.
Professor Sullivan said: Brandon, we agree that the specification was
ambiguous in terms of the issue that you have identified. You analysis is spot-on. We will give you full credit. What's most important are the technical lessons:
- it's really easy to write ambiguous specifications
- ambiguous specifications can lead to all kinds of problems/disagreements
- tests can be important in disambiguating natural language specifications
Assignment 1
User 513 said: For the StdGaussianHistogram, are we suppose to output the number of values that fall into each subinterval or are we outputting the values themselves?
Lesley said: #208
How Precisely do We Subdivide Intervals in Assmt #1
User 86 said:
When we subdivide the interval [-5,5], which values are included in the sub-intervals. For example, is the first sub-interal supposed to be [-5,-4.9) or (-5,-4.9] ?
(Edited by Kevin Sullivan - original submission Friday, 25 January 2008, 11:24 PM)
Lesley said: #194
Output of No.2 assignment 1
User 254 said: "the values in the array, from index 0 to index
n-1, all on one line, separated by spaces"
What is the space requirement of the last number? can I put a space after it?
"the values of the
leftTail and
rightTail variables, each on its own line"
do we need to type "leftTail" or "rightTail" before the value?
Professor Sullivan said: We'll accept a trailing space.
If we do not specify that text should be printed then it should not be printed.
KS
Double inaccuracy
User 449 said: Hey,
What is one way to deal with the problem of Java returning values as exampled in a partial program below?:
double x = 0;
for (int i=0; i<5; ++i)
{
x = x + .1;
System.out.println(x);
}
Output:
.1
.2
.30000000000000004
.4
.5
The third line gives me pause. I realize it is perhaps a trivial inaccuracy for the programs we are writing, but I would like to know how to correct it nonetheless.
As a temporary solution, I have modified the example program to:
double x = 0;
for (int i=0; i<5; ++i)
{
x = x + .1;
x = (int) Math.round(x*10); x = x/10; System.out.println(x);
}
...which fixes the problem in this particular case, but is there a more general solution?
-Joel
Professor Humphreys said: Fantastic question.
Unfortunately, there is no general solution.
When we come to the portion of the course on scientific computing, it will be more clear why.
For now, remember that the "double" type is trying to use 64 bits to SOMEHOW represent a real number.
Therefore there are at MOST 2^64 different possible real numbers that a "double" can represent precisely.
All other real numbers are just approximations.
Yes, this introduces error.
Yes, this error can propagate through a calculation and be multiplied by other such errors, making the problem worse.
Yes, people have lost their lives because of this.
Lesley said: You might also find this interesting:
http://mindprod.com/jgloss/floatingpoint.html
Professor Sullivan said: Yup: Great example illustrating the point that I made in my class the other day: NEVER FORGET: Computer arithmetic is not the arithmetic that you learned in school. It's close, in many circumstances, but there are many subtleties.
Assigning Sub-intervals to Elements
User 236 said: I know that the process of dividing the interval into sub intervals is conceptual, but how do I go about assigning these subintervals to the actual elements?
Professor Sullivan said: The interval from -5 to 5 is to be divided into 100 sub-intervals. If you generate the random number -4.99, for example, that would have be counted in the first sub-interval (i.e., zero'th array element). If you generate the number 4.99, that would have to be counted in the 100'th sub-interval (what's the array index?). What you need is a formula for figuring out which array index to use for any give number in the range [-5,5]. Just work it out. This kind of problem solving is a big part of programming: it's not so much about
how to express something Java as it is figuring out
precisely what to express! That's part of the job.
Question on Part 2, Assignment 1
User 52 said: it seems like so many people are struggling with this, and so am i.
I am wondering, if this assignment is possible with all the knowledge we had been given (from lecture, group assignment #1, lab, and lab quiz). Or if not, which parts of our book should we read, in preparation for this.
I've been trying to figure out this histogram part for the longest time. I still have not gotten anywhere.
Professor Humphreys said: Everyone should have read sections 1.1-1.4 in the book.
Everything you have done so far is definitely adequate to do this assignment.
If you're struggling, ask for help!
Professor Sullivan said: The group work is intended to ensure that you've practiced with the basic building blocks needed to do the individual assignments. If you haven't finished the group work, start there. There are some problems there intended to give you practice with arrays. We will be covering arrays in lecture shortly. In the meantime, read about them, do
simple exercises before trying harder ones, and build up slowly to the hard problems. The only tricky part in the assignment is to derive a formula for the array index to use to account for a give random pick.
RoboGrade for Assignment 1?
User 270 said: I don't see the RoboGrade button on the Assignment 1 page. Does that mean we can't RoboGrade for Assignment 1?
User 181 said: Kevin or Greg,
This question has not been answered yet. So do you know what the problem is?
Professor Humphreys said: Only group works (and possibly lab quizzes) will be robograded.
Nit-picky question
User 449 said: Hey,
I'm pretty sure the answer to my question is obviously implied, but I'm trying to be very exact, so I thought I'd ask (in reference to Part 2 of Individual Assignment #1):
Quote 1: "...produces a histogram of
n pseudo-random values..."
Quote 2: "[Output] the values in the array, from index 0 to index
n-1..."
Am I correct to assume that the two
n's are unrelated?
-Joel
User 167 said: Yes. In the second quote, it refers to the number of elements in the array, which is different from the n used earlier.
Professor Sullivan said: It's very strange: I'm certain that I corrected this issue on the web site last week. I just did it again. Generate
m random numbers and account for them in
n intervals.
can't compile
User 71 said: I can still run java program in cmd, but when I type in "javac" it says it is not either a internal or external command, what can I do?
User 167 said: Most likely, you don't have java installed properly.
See $@FORUMVIEWBYID*12@$ for instructions for setting up java on your machine, and be sure you check your PATH variable.
stdlib
User 449 said: I downloaded the stdlib file to my home directory on J:\ and followed the instructions for including it in a Java project. Here is what happened:
- Eclipse recognized the new library and no longer underlined the statement StdOut.println() in red.
- When compiling the program from cmd, however, I was greeted with errors telling me:
symbol: variable StdOut
location: class HelloWorld
StdOut.print("HelloWorld");
^
Any suggestions?
-Joel
Individual Assigment 1 question
User 196 said: Hey,
I uploaded the first part of the individaul assigment 1 to robograde it and see if what I did was correct except I do not see a place to robograde it...am i looking in the worng place or is there no Robograde for this part?. If there is not is ther anyway I can take off my first upload and take a better look at it so that I can make sure it was right?...If we cannot robograde it, then I need to get it taken off because I did not know you can only submit it once. Can anyone help?
Thanks
Nathan Wethington
Professor Humphreys said: You can submit as many times as you want.
Individual assignments are not auto-graded.
standard library
User 90 said: Every time I try to download the standard library I get an error message saying: Failed to load Main-Class manifest attribute from C:\Users\Owner\Desktop\stdlib.jar. What is the problem?
Professor Sullivan said: It looks like you're trying to "run" the jar file.
In fact, it's possible to package up a Java program as a runnable jar file, but that's not what we're trying to do here.
You need to
save the file to a location on disk and then include it as a library, following the directions on the class web site.
KS
stdlib problems
User 77 said: I was having the same problem as Joel Gillespie, as he explained in his question labelled "stdlib". First, don't you have to mention the stdlib.jar file while compiling the program?, using in the cmd:
javac -cp j:/stdlib.jar HelloWorld.java
I tried this and it compiled the program without complaining, but then when I tried in cmd: java -cp j:/stdlib.jar HelloWorld
I received this message:
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
I added stdlib.jar as an external jar to the java project, and it shows up in eclipse in referenced libraries. Did I miss something?
Professor Sullivan said: You should include the "-cp" thing when compiling. Once the code is compiled, you don't need to specify the jar file.
KS
can't compile anymore
User 71 said: My java was running fine, but today when I type in "javac" it says it is not either a internal or external command, I can still run java program in cmd with"java filename", and I've reinstalled the java, check the path, it still doesn't work, what else can I do?
Professor Sullivan said: Double check your path. That's almost certainly where the problem is. If that doesn't help, see a TA during office hours tomorrow night. --KS
Lesley said: I would suggest bringing your laptop in during TA hours sometime this week then.
Groupwork #18
User 90 said: I'm confused about how our output should look. If the input is 3 should the output be something such as : 0 1 2?
Professor Sullivan said: Almost right. The problem says
in reverse order. --KS
ASSIGNMENT 1!!
User 253 said: I just submitted my standardgaussian.java and it appears there is no Robograde. I am not sure if I want to submit it then, but it will not let you unsubmit it even though it says we can submit it multiple times. Help!
Professor Humphreys said: You can submit as many times as you want, just resubmit the file.
How do I use StdLib at Command Line (was "stdlib problems continued")
User 77 said: As I mentioned in stdlib problems, stdlib was not working for me after compiling a program, as cmd would give me an error message when trying to run the program. I tried, after compiling the program with the -cp stuff, and then the regular java HelloWorld, as recommended, and I essentially get the same error message, except the first few lines are different and read:
Exception in thread "main" java.lang.NoClassDefFoundError: StdOut
at HelloWorld.main(HelloWorld.java:4)
Caused by: java.lang.ClassNotFoundException: StdOut
(and it continues with the rest of the error messages as before) What is going on?
(Edited by Kevin Sullivan - original submission Sunday, 27 January 2008, 12:23 AM)
Lesley said: please try running your program as:
javac -cp j:\workspace\stdlib.jar World.java
java -cp .;j:\workspace\stdlib.jar World
Assignment 1 - Edited?
User 52 said: I just recently looked at the Assignment #1 and it seems to have been edited? Or am I wrong? :
2. Write a Java program called
StdGaussianHistogram.java that produces a histogram of
m pseudo-random values using the Box-Muller formula, where the value
m is given as a command-line argument. Do this in the following way. First, divide the interval [-5.0, 5.0] into
n sub-intervals of width 0.1.
it says... "m" pseudo-random values...while it says "n" sub-intervals of width 0.1.
If its going from -5.0 to 5.0..then..shouldn't there be 100 sub-intervals...instead of..n sub-intervals. I'm just confused by all the variables now.
I looked at it every day for the past ~5 days or so, and it seemed to have made sense, I'm just confused now, because of everything I've read from the forums, and from reading the assignment over and over again. Has the assignment recently been changed?
Professor Sullivan said: Hi Jae,
Yes we tried to clarify it. Here's the deal:
You generate
m random numbers, where the value
m is given as a command line argument. For example, when you run your program, you could define
m to be 1 million. Your program would thus generate m=1000000 numbers, each on picked at random from a standard normal distribution. I can tell you that it very unlikely that you'll pick more than a very small number that are outside the range [-5,5].
Each time you generate a number, we want you to count it as falling into one of
n bins. The bins are intervals of size 0.1 between -5 and 5. You can easily figure out how many there are. This is the value of
n -- the number of bins.
KS
assignment 1
User 91 said: should the output for assignment 1, part 1 have any particular format? For instance should the output line read only the randomly generated number or should it also include "z = "?
Professor Sullivan said: Hi Kara,
Again, if we do not specify that you should add text, then you should not. In this case, we just want to see the numerical output, exactly as specified. Thanks!
KS
Group Assignment # 18
Professor Sullivan said: It's impossible to say what's causing this behavior without looking at your program, except that it's safe to say your program is doing exactly what it's programmed to do!
One of the most important of all skills for a program designer / implementer is the ability to
mentally simulate the execution of a program. What I suggest is that you take a pencil and paper, start at the beginning of your program, and trace its execution statement by statement. If you do this you are very likely to discover with it is about the program you've written that's causing the behavior that you're seeing.
KS
Why is 1/0 undefined while 1.0/0.0 is legal in java?
User 49 said: Why is 1/0 undefined while 1.0/0.0 is legal in java?
Anyone knows the answer?
Thanks
Professor Humphreys said: That is a very strange asymmetry.
1.0/0.0 gives you the value "Infinity", which is not terribly likely to be useful in subsequent calculations, but 1/0 does give a runtime error. I had previously thought (wrongly) that it gave NaN.
The answer to "why" is almost surely "the designers of Java made a choice".
Professor Sullivan said: Virtually all modern computer programming languages and computer hardware implementations implement part or all of the so-called
IEEE 754 specification the behavior of
floating point (but not integer) arithmetic. Java is among the many languages that are designed to conform to this standard. The standard requires the behavior that you see for floating point operations. Rather than exceptions, this standard uses special values,
Inf and
NaN, to indicate pathological results. The designers of Java chose to make integer division raise an exception.
Ok, everyone, let's recite the mantra again: computer arithmetic is weird -- it's not what you learned in school.
You can find more about Java's implementation of IEEE 754
here.
For those of you who read this far, here's some grist for a possible extra credit question on some test. Is it possible for a floating point number to be neither greater nor less than or equal to 0.0? What floating point number has this bizarre property (if there is one)?
And a final bit of trivia: Before IEEE 754, calculators and computers tended to produce vastly different results for the same floating point computations. That was a real problem. Kahan won the Turing Award (Nobel Prize" of computer science) for his work developing IEEE 754.
User 167 said: Also, integer division can't return infinity or NaN because the specification of an integer doesn't provide a way to represent either of these values, whereas the IEEE specification for floats does.
Assignment 1
User 268 said: Is my StdGaussian.java supposed to yield any values above or below the interval [-5.0, 5.0]?
I never seem to get any values outside that interval even after 100 numbers are generated.
User 14 said: James,
You're right. You should very rarely get numbers outside this range because you are simulating a normal distribution with a standard deviation of 1. Look at your numbers close to the edges and you will probably even have all zeros outside of -4 to 4. About 99.9999% of the numbers you generate should lie between -5 and 5. For more information, here is a relevant wikipedia page: http://en.wikipedia.org/wiki/Normal_distribution#Standard_deviation_and_confidence_intervals
Professor Sullivan said: Yup, Eric's right. I generally don't see numbers outside of [-5,5] unless I generate a million or more samples. A normal distribution has this nice property: anything is possible but most everything is close to average!
Question about the while command
User 33 said: So, when coding a while loop in java (like, say while c !=2), does java quit out of the while loop as soon as c = 2, or does it have to go to the end of the set of commands in the {brackets} before it ends the loop?
Thanks in advance
User 14 said: Java will run to the end of the curly braces {} before checking the condition again. So yes, it has to go to the end of the set of commands in the {brackets} before it ends the loop.
Professor Sullivan said: Right. See the graphical representation of the while loop in the lecture notes.
Assignment 1 - Command Line Argument
User 52 said: Hey
I got mine to work, but every once in a while, it says I have an error, but I just type the same exact command line argument again, and it works. Is there a reason? (I'm afraid the same might happen while its being graded, therefore I'll lose points). I'm 99% sure my code is right, but I don't know why it has those failures from time to time.
And also, there is an obvious limit on how high your command line argument can be, but I've compared with someone who already finished it as well, but that person's code could allow much higher command line arguments than I could.
What could be the problem? And would it cost me a lot during the grading process?
Professor Sullivan said: Remember that you're generating
random numbers. So certain "bad" things might happen in one run of your program that don't happen in other runs. It's often the "edge" cases that are problematical. I suggest that you mentally simulate a run of your program to mentally test the "edge" cases -- e.g.,. where the generated numbers are right up against the edge of the [-5,5] interval.
Kevin Sullivan
Histogram Question
User 268 said: When placing the 100 randomly generated numbers do I just put them in a one dimensional array in the order they are generated? Or do I have to put them in the correct sub-intervals of 0.1 thus possibly having multiple values for the same interval? The word histogram scares me.
Professor Sullivan said: The program is to generate random numbers and
count the number of generated numbers that fall into each subinterval.
Assignment 1 output
User 200 said: For the histogram assignment, does it matter whether or not there's a space after the last number of the histogram, or is the grading program going to be that picky?
Lesley said: I don't believe the assignments are graded with Robograder (think about the implications of saying your random number program could be graded by a robograder), but it's only one line of code to make it not print a space after the last number...
Professor Sullivan said: Take a few minutes and see if you can figure out what it would take to do it "right," i.e., with spaces between elements but not before the first one or after the last one.
Here's a hint:
If you repeat the following, it's not right (you get a space before):
space element
Nor is it right to repeat the following pattern (you get a space after):
element space
Assuming that you have at least one element to print, what pattern works to get you what you want? Working through such problems builds intellectual capacity for computational problem solving!
Robograde on random numbers
User 200 said: I was just curious as to how RoboGrade grades programs that have to produce random numbers. Since each set of random numbers will always be different, it can't compare the output to that of another program. Does Robograde just look at the output of the submitted program to see if it makes general sense, or can it actually examine the program's code and see if there's any possibility for logic or run-time errors?
For example, with the histogram assignment, it's very unlikely to produce any values outside of the [-5.0, 5.0] range, but it IS possible. Hypothetically then, someone could just be lazy with their program and decide to leave the leftTail and rightTail variables at 0 without actually checking for outliers. How does RoboGrade detect a situation like that?
Professor Sullivan said: Good question. How do you test programs that by their very definition have non-deterministic behaviors? The real answer is this: testing is just one of quite a few ways to determine whether a program satisfies its specification or not. Other techniques include human inspection of code and use of mathematical proof techniques (where you literally formulate a putative theorem about the behavior of a program and then attempt to prove the theorem based on axioms about how various programming constructs work). In this case we'll combine testing (robograde) and human inspection (using TAs/graders).
Intentional attempts to "fool" our robograder will result in negative increments to grades. (For example, it would not be a good idea to implement a program that simply prints out a long list of numbers, hoping that they'll pass our tests. We're smarter than that -- we hope -- and would in such an instance assign a negative grade :-)
Robograde for Groupwork #17
User 347 said: When Robograde tests our program, the outputs match perfectly, but it is not awarding us the five points.
Lesley said: If it is not awarding you 5 points, then your outputs do not match.
"in ascending order with n numbers on each line and with single spaces between numbers on a given line. Do not include a space after the last number on any line."
I would suggest making sure you've fulfilled that last requirement.
Professor Sullivan said: Double check as Lesley has indicated. If you still disagree, submit a regrade request per our regrade policy. Thanks!
Running programs within eclipse
User 68 said: Running programs from the command prompt works perfectly fine. Whenever I try to run a program from within eclipse, no matter what program I try, eclipse returns the following message:
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
Professor Sullivan said: You've got a configuration error in your Eclipse and/or Java installation. The problem, technically, is that you're compiling with a late version of Java but trying to run the file on a Java Virtual Machine for an earlier version of Java. What computer are you running on? Did you follow our directions for installing Java and then Eclipse?
KS
Error Error
User 236 said: If I am on my account and I go to grades up at the upper right hand corner, and then scroll down to my groupwork grades, in the columns for "grade" and "percent" it has the word "Error" in them. But it has my group's actual grade present in the Bold lettering.
Professor Humphreys said: I logged in as you, clicked on "grades", and it looks like I would expect; no "error" anywhere.
Opening an in-progess project
User 88 said: While working on a project (any of them) I can compile and run it within Eclipse without problems. However, when I close Eclipse and then come back to work on it later and try to run it I get the message "URLClassLoader$1.run()line: not available" even though I see all the code the way it was before.
User 35 said: Actually, I think you'd better first reinstall the Eclipse and Java.
Assignment 1
User 120 said: Is this assignment meant to be really hard because I can't get number 2 at all and I have spent many days trying to figure it out. I read the book, went over my notes, looked up terms on wikipedia, and I'm still not getting it. I've never done programming before and I was under the impression that we didn't need prior experience to be in this class. Is there anything else I can do? Thank you.
Lesley said: Here is what I have been telling people at stacks hours:
Try to do the program like this, to get started:
Make it generate ONE random number. This part you already did in part 1 of the assignment.
Now make an array that covers subintervals, but make them of width = 1. So these intervals are [-5.0, -4.0) [-4.0, -3.0)... [3.0, 4.0) [4.0, 5.0]. This array will be an array of ints (like the assignment specifies) and what it is doing is literally acting like some boxes. Every time you get a random number, you want to put it in the box of the interval it falls into - but the thing the array keeps track of are how MANY numbers you put into each box. If your random number were 4.3, it would go in the [4.0, 5.0] box. If it were -1.2, it would go in the [-2.0, -1.0) box. But how do you figure this out? Well, 4.0 < 4.3 < 5.0, and -2.0 < -1.2 < -1.0 and how does this translate into computer code?? That's a big part of the assignment to figure out.
See if you can get the computer to figure out which interval your ONE random number goes in, and print out the resulting histogram: it will be a bunch of 0's and one 1 for the bin you have put the number in. Now see if you can make it keep track of 2 numbers, then m numbers. You also need to remember that the end result needs an interval width of .1, not 1.
The TAs have office hours tomorrow should you get lost and need more help.
Professor Sullivan said: Hi Boxi,
First, thanks for asking. We appreciate that. There are surely others "in the same boat." We want to make sure that everyone succeeds. So we do want to know when people are having trouble. For some help, please see the note that I just posted on the main web site. (Click to download the PDF file.) Read it over and please let me know if you need more help.
Kevin Sullivan
Using values defined in a for loop, outside the loop
User 427 said: Is it possible to use a variable defined in a for loop, outside to the loop. Because my program does not recognize them. If not, what would be the best way for me to print the values determined in the for loop, outside the loop?
Professor Sullivan said: Great, great question.
You can use variables only
within the code blocks in which they are declared. So, for example, if you say
int i within a for loop, then you can't use that
i outside of the loop. You can always declare a variable
outside of a code block in which a value for it is calculated and assigned, and in that case, the variable will be
in scope outside of that block.
KS
Formatting Errors
User 560 said: on the groupwork assignment, I have submitted everything and robograde has awarded me 5 points for each but took off 10 for "formatting errors". can anyone explain?
Question about Individual problem
User 189 said: For problem 2 if it's ok that I create a 102-slot array, say a[102], and set a[0] as the lefttail and a[101] as the right tail. I think this will work but i wonder if it fulfill the requirement since the instruction says "from index 0 to index
n-1" for the first line.
Thank you
Professor Sullivan said: Shanshan,
In practice what you propose would be a fine solution, because a specification would generally leave the choice of implementation variables and strategies up to you, the program designer. However, the specification here is very clear. It tells you not only to use two separate tail variables, but even what to call them. The general rule is that you must satisfy the specification. You can argue about whether a specification is a
good specification, but whatever it ends up being, that's what your program must satisfy.
KS
problem with results
User 440 said: I can only get my program to use up to m = 100 and nothing more. I'm not sure where I went wrong.
Professor Sullivan said: Matt,
I have two pieces of advice:
(1) Make sure you understand exactly what the program is required to do. For example, without thinking about programming at all, simulate in your mind the process of generating a large number of random numbers and counting how many fall in each of a set of intervals.
(2) Make the effort to understand precisely what your program actually does. There are several ways to do this:
- mentally simulate/trace its execution
- use the debugger to watch it run, line by line
- add code to your program to print out certain intermediate results
KS
Average for part 2?
User 331 said: In part 2 of assingment one it say "the average of the generated numbers, on its own line"
Does it want the average of the z ( random generated number) or does it want the average of the data in the histogram( 0 0 1 2 0 3 2 0)?
Thanks
Professor Sullivan said: The average of the generated random numbers (the z's).
individual assignment part 2 output
User 543 said: I had a question about the output for the individual assignment part 2. For the left tail, right tail, and average, do you want the output to say like "left tail: 0" or do you just want the number(s) alone? And also, the directions say that the
left tail, right tail should be one their own separate line. So I put an
System.out.println(). before printing out the left tail, and when my command
line argument is 1000. it prints fine, but when it's like 100, theres an
extra line between the left tail and they regular array output. Does this extra line matter? Will I get points taken off for it?
Professor Sullivan said: Hi. We continue to receive questions of this form. There are several of them with answers already posted on this help forum. It's a good practice to read over the questions that have already been asked and answered.
As we've said before, yes, your output must conform to the specification. If we do not specify that certain text elements should be included in your output (such as "left tail:") then they should not be included. Blank lines are not specified and so should not be included.
Note: System.out.println(...) can take arguments just like System.out.print(...). They have identical behaviors except that the former includes a carriage return at the end of the specified output (whether an empty blank line or not), and System.out.print does not include a carriage return at the end of the output.
KS
How Do I Use StdLib at Command Line (was "Trouble with Stdlib")
User 200 said: I downloaded stdlib.jar off the website and added it as an additional library on Eclipse. I used StdOut on my Hello World program just to make sure the library was added correctly, and it worked fine when I ran it on Eclipse. However, the command prompt won't recognize the Stdlib methods. How do I fix that?
(Edited by Kevin Sullivan - original submission Wednesday, 30 January 2008, 12:55 PM)
Professor Humphreys said: #267
Failed to load Main-Class manifest? (Was How to download stdlib.jar)
User 309 said: When I try to download the stdlib.jar, I get an error that says "Failed to load Main-Class manifest attribute from ...(file name)." Am I downloading incorrectly?
(Edited by Kevin Sullivan - original submission Wednesday, 30 January 2008, 01:36 PM)
Professor Sullivan said: Don't try to
run the program. Just
save it to your disk.
RoboGrade? Assignment 1
User 136 said: I just submitted both of my programs for Assignment 1, are we not using Robograde? Also it won't let me unsubmit...
Histogram with DrawDistribution
User 200 said: I'm getting an error when I try to compile my StdGaussianHistogram program with the DrawDistribution line of code at the end. Like the directions said, I saved DrawDistribution as a .java file to the src folder of my Histogram project, I downloaded, configured, and tested the stdlib.jar file, so I know that it works.
The error I get when I compile StdGaussianHistogram.java is this:
"cannot find symbol:
symbol: variable DrawDistribution
location: class StdGaussianHistogram"
I guess the problem is that my computer thinks that DrawDistribution is supposed to be a variable instead of an actual class. How do I fix this?
Professor Sullivan said: If you're running your program from within Eclipse (as you should be), the file needs to appear in the "src" folder of the Eclipse project. To get it there is as simple as dragging it from a Windows explorer window and dropping it into the "src" folder.
I'm sorry but I can't trace variables in Debug menu
User 71 said: Things turned out fine in the Console, but nothing showed up in the Variables window, am I doing anything wrong?
Professor Sullivan said: There's not enough information here to provide a good answer. Please see a TA for additional help.
Compiling Lab Study #1 error
User 215 said: I get this error when trying to compile Lab Study #1:
StdGaussianHistogram.java:73: cannot find symbol
symbol : variable DrawDistribution
location: class StdGaussianHistogram
DrawDistribution.drawMyHistogramAsProbabilityDistribution(histogram,-5, 5, leftTail, rightTail);
And there's a little arrow underneath the "a" in "leftTail".
Any ideas on how to fix this?
Another Lab Study #1 error
User 249 said: Here is another confused person adding to this forum. I have stdlib.jar and DrawDistribution where they should be, and am trying to compile the program with -cp and everything but I get the following error...
StdGaussianHistogram.java:448: cannot find symbol
symbol: variableDrawDistribution
location: class StdGaussianHistogram
And then it has the line of code I was told to download with the carrot under the first D. None of the other solutions on this forum work, and frustration is setting in.
HELP!
Professor Sullivan said: Sean,
Please try to compile and run the program from within Eclipse. Have you done that?
KS
I need help
User 368 said: I was wondering if any TA could possible meet with me or let me know when their office hours are to work out some kinks in my computer. A lot of things are concerning eclipse are not working correctly and I think I have made it worse trying to fix it myself. Thanks in advance
Lesley said: TA's have official office hours 6-10pm Sun, Mon, Tues.
If something is due before then, consider going down to Olsson 001 and doing the work on one of those computers with your login that was emailed to you.
There are labs all day tomorrow so if you bring your computer and ask a TA nicely they might be able to debug your computer for you before or after the lab section they teach (times on COD). Consider offering candy as a thank you.
You could also ask another student to help you fix your computer (that would not be a violation of the honor code) if you know someone in 101 or 101E or another CS class that is familiar with Eclipse. Again, consider bribery.
Lab Study #1- command line
User 200 said: Judging by the responses to questions about this assignment, I would say it's safe to assume that we need to be able to run the revised Histogram program only through Eclipse and not necessarily through the command prompt. That being the case, what should we do about the command line argument (where we input "n" for the number of random numbers)? Do we leave the command line input statement as is (because I don't know how to run the program through Eclipse with that statement in there), do we need to change it to use something from the stdlib.jar library, or do we just set a fixed value for n?
Professor Humphreys said: Please read this post to see how to run from the command line:
#267
Professor Sullivan said: Kiran,
How do you run a program that uses the standard libraries?
EclipseIf you want to run your program entirely in Eclipse, you have to specify your command line arguments
in Eclipse and you have to have added stdlib.jar as an external jar file, as covered in an earlier posting.
Command LineThe key here is that
stdlib.java needs to be on your CLASSPATH. The -cp <file> argument to the Java compiler can be used here, where
<file> is a path to a .jar file. So the command
javac -cp .;<path> DrawDistribution.java will compile
DrawDistribution.java and will access
stdlib.jar to resolve symbols not defined within the java file itself. Again,
<path> is a path to the jar file.
You can add that "-cp ..." stuff every time you type
javac if you want, but there's a much more convenient approach. If you're on Windows, here's what we strongly recommend. Create or edit a CLASSPATH system variable,
in just the same way that you had to set a PATH variable so that windows could find the javac
and java
commands. Here's how.
- Right click on My Computer, then click Advanced. The click Environment Variables. In the system variables area look for CLASSPATH. If it's there, edit it and add to the end the following;
;<path-of-your-jar-file>
Here the semicolon separates the new part of the CLASSPATH from what was there before. Be very careful not to remove or change what was there before.
- If there is no CLASSPATH variable, create one and edit it giving it the following value
.;<path-of-jar-file>
The period before the semicolon means search the current directory in which the compiler is running before searching files on the rest of the classpath. My CLASSPATH looks like this:
.;C:\Program Files\Java\jre1.6.0_04\lib\ext\QTJava.zip;C:\Kevin\workspace\stdlib.jar
The material before ;C:\Kevin\workspace\stdlib.jar was already there. I just added that part to include the jar file in the set of files that will be searched for symbols that are undefined in the Java files you're actually compiling.
I hope this helps. If not, let me know, and we'll make it work for you.
Kevin Sullivan
Command Line Compiling Follow-up
User 449 said: I have successfully mastered the ability to compile from the command line using -cp .; etc., but this is terribly inconvenient. I followed the instructions on creating a CLASSPATH variable, but I am still receiving errors. Here is some background:
- stdlib.jar is located in j:\workspace
- I have edited the Java build path for my histogram project to include stdlib.jar
- Under system variables->CLASSPATH, I have: .;C:\Program Files\Java\jre1.5.0_06\lib\ext\QTJava.zip;j:\workspace\stdlib.jar
- It compiles fine, but when I try to run it, I get:
Exception in thread "main" java.lang.NoClassDefFoundError: StdDraw
at DrawDistribution.initialize(DrawDistribution.java:43)
...
Caused by: java.lang.ClassNotFoundException: StdDraw
The program works fine when I do the -cp thing, and I get the graph and everything, so I don't know what the problem is.
-Joel
Lesley said: You can always write yourself a batch program to do it for you.
put this in a file called 'run.bat' in the directory where your .java file is - you can do this by saving it as run.txt and then renaming it should Windows not want to let you edit a file ending in .bat
javac -cp j:\workspace\stdlib.jar %1.java
java -cp .;j:\workspace\stdlib.jar %1
then run it as 'run World' if your file were World.java for example
Should you want to avoid copying this file a bunch of times, you can reference it as 'j:\workspace\run.bat World' ...You could probably even get away with putting j:\workspace in your path variable and then being able to run it as 'run World' regardless of which directory you're in relative to run.bat's location (though remember to be in the appropriate src directory when you run it so Java can find your code).
In addition to my previous post
User 449 said: I should also note that DrawDistribution.java is in its proper place in the src folder of my histogram project.
-Joel
Problems with Home Directory Login
User 282 said: Hey,
Sorry this isn't about programming, but all of a sudden my home directory login client doesn't work. An error screen pops up saying that the client has "encountered an error and needs to close" even though it wasn't running in the first place. Has anyone else run into this problem?
Thanks,
Scott
Lesley said: I believe ITC could best answer your question. Please send them an email. I didn't see your error on their
FAQ page at least...
StdDraw.picture problems - finding picture file
User 188 said: Hi:
I'm trying to practise for the assignment, using deluxe bouncing ball, but I can't seem to make it find the earth.gif file. I've put a copy of the picture in the directory with the .java file, and have added nbody.zip to the libraries, but every time I try to run the program it comes up saying 'image earth.gif not found'.
What am I doing wrong?
Thanks,
Becca
Professor Humphreys said: It needs to be in the same directory as the class file.
If you are running from inside eclipse, this will be the "bin" directory, not the "src" directory.
Professor Sullivan said: If you drag and drop earth.gif (for example) to your Eclipse project, then Eclipse will put the file in the right place to be found when you run your program from within Eclipse.
KS
How to Read In a File Name using StdIn
User 25 said: For Assignment 2, I understand that we must use StdIn.readDouble(); and all those methods for the various parts of the program. However, how do I specify to the scanner being used in StdIn to read a certain file (i.e. planets.txt).
do I make an object constructor to tell it to read planets.txt?
please help!
Rohan
Professor Humphreys said: In order to make the contents of StdIn come from a file, instead of from the keyboard, do the following from the command line:
java YourProgram < the_input_file
If you're trying to use Eclipse, you can't do this. You will have to copy and paste the contents of the file into the input window where you would normally type input.
Groupwork2 formatting error
User 86 said: I submitted uploaded the first 4 programs for the second groupwork assignment and for problem 4 part of the Robograde output was as follows:
Running our sample solution with the same command line...
Testing the command 'java -cp .:/home/moodle/robograde/cs101-spr08/stdlib.jar Gravity1 0.0 0.0 1.9889999999999999e+30 1496300000.0 0.0 5.9700000000000003e+24'...
Our solution produced the following output:
Line 0: -3.5375093490093405E26 0.0
Line 1: 3.5375093490093405E26 -0.0
WHOOPS! YOUR OUTPUT IS CLOSE, BUT NOT QUITE RIGHT! (line 1)!.
Also, robograde deducted 10 points for formatting (which I assume is due to the error above. How can I fix this?
Thanks!
User 14 said: You showed the correct output, but what was your group's output for this problem?
Lab study 1 Grading
User 343 said: Are labs graded by robograder or by a person like the individual assignments? I ask because like other people on here, I can get the histogram and picture to show up fine in Eclipse, but I can't make it work from the command line. Looking at robograder from other assignments, it seems that it uses the command prompt as opposed to running each program in eclipse. Basically, if my program works in Eclipse, is that good enough?
p.s. Someone asked about a red line in the 101E class showing up on the histogram and the professor made it sound like that was not normal. I too have a red line on my graph so i'm wondering if that is/isn't supposed to be there.
User 14 said: When your labs/assignments are graded (either by roboGrader or a human), they are compiled and run with the appropriate support files needed. So I believe if you followed the correct procedure for using these support files (like the jar or the DrawDistribution.java), and your program runs in Eclipse, then you should be fine. And yes, that red line is supposed to be there.
Troubling Red Xs
User 449 said: Everything compiles and runs fine from the command line, but I am still getting these annoying red Xs in Eclipse. Any thoughts? Below is a link to a screenshot... I couldn't get the Insert Image function of the forum to work properly.
http://i25.tinypic.com/2sb9yme.jpg
-Joel
Professor Sullivan said: DrawDistribution.java isn't in your project! Save the file to disk then drag and drop it into the Eclipse src directory.
GroupWork submission
User 200 said: For the groupwork #2, it says that we're allowed to submit a program as many times as we like, but it won't let me unsubmit the programs I already uploaded so that I can do that. Can someone fix this?
Professor Humphreys said: just submit the file(a) again. Unsubmit is not, and never was, necessary.
JAR Extension FIle
User 268 said: How do i extract the stdlib file as an extension to my java file?
I extracted all the files to my src folder... and I got the image of the distribution to work, but I'm worried that my submission won't work if it's not in my src folder.
Professor Sullivan said: James,
Don't extract the files. Save the jar file then do
Project>Properties>Java Build Path>LIbraries>Add External Jar, browse to the jar file, and click ok.
KS
Compile and Run in Eclipse - Lab 1
User 199 said: I have not been able to compile my program through the command prompt window. I tried using -cp and also editing the classpath. Whenever I try to use the -cp command I get an error that reads:
javac: invalid flag: Libraries\stdlib.jar
Usage: javac <options> <source files>
use -help for a list of possible options
Do you have any idea what I should do?
I would also like to know how to compile and run within eclipse and input the command line argument so that I can see if my program works. How do I do this?
Thanks.
User 14 said: To run your program in Eclipse and use command line arguments, click Run --> Open Run Dialog... Make sure the project and Main class match the project and main class you want to run, then click the "Arguments" tab. In the "Program arguments" box, enter the command line arguments you want the program to use. As an example, for the StdGaussianHistogram program, you would enter a number like 1000 here.
In addition to my last post
User 199 said: When I downloaded stdlib.jar it downloaded as a zip file, I have tried to download it again as a jar file but when I do I get an error message saying:
Failed to load Main-Class manifest attribute from J:\private\CS Standard Libraries\stdlib.jar
I really don't understand what zipped files are, so I have no idea if this is part of the reason that I can't get my lab 1 program to compile. Is it? And if so, how do I fix this?
Thanks
Professor Sullivan said: It sounds like you're trying to
Open rather than
Save the file to disk. You need to save the file on disk.
Lesley said: #313
Red line on grapth (Lab work)
User 531 said: Ive got the gaussian distribution to output to a grapth that looks like, but it has a red line that starts out following the data then just runs off up the graph, looks a little like a cubic graph. What is that, and how do I fix it/make it go away?
Professor Sullivan said: That's interesting. It's definitely not what we're expecting. I can't diagnose the problem remotely. See a TA or show me after class / in office hours.
User 14 said: Nick,
I believe that red line is supposed to be there. It has been there on every student's graphs that I've looked at. It represents the cumulative frequency distribution. http://en.wikipedia.org/wiki/Cumulative_frequency
Professor Sullivan said: Eric's right. The red represents the cumulative probability, but it should not diverge upwards. Rather it should start at zero, rise quickly where the prob. density is the highest, and then flatten out to the right, at the value one.
Please disregard my previous inquiry
User 449 said: The red Xs referenced in my previous post (Troubling Red Xs) have gone away upon reboot and re-mounting the j:\ drive. Regardless of the source of their disappearance, I am rather pleased with this development.
-Joel
Lab Study #1
User 344 said: If my original histogram program had a problem with it, and thus the graphical output for this lab does not display exactly right, should I attempt to fix the program or leave it how it was when I turned it in the first time?
User 14 said: you can use the solution file from the lab page
Variable precision
User 449 said: Is there a way to account for variable precision using printf()?
Pretend that I have a variable called places_past_decimal, which accounts for the following:
Example #1Input: 4.5
places_past_decimal = 1
Example #2Input: 2.3109000
places_past_decimal = 4
If I wanted to print out 4.5 instead of 4.500000 (let's store this number in a variable x) in Example 1, I would do:
StdOut.printf("%.1f\n", x);
Similarly with Example 2, I would do:
StdOut.printf("%.4f\n", x);
But say I wanted to more generally truncate zeroes from an arbitrary double, how would I go about doing this? A statement like:
StdOut.printf("%.places_past_decimalf\n", x)
yields an error, which I fully expected it to do, because the "f" is mixed up with the variable name.
-Joel
P.S. Is this what you are asking from us in VariableArgs3 (based on the sample output)?
User 14 said: Joel,
If you want to print a variable precision in your floating point values, remember that the first argument to printf is a string. Thus, you can concatenate things together to create this string. Something like "%." + places_past_decimal + "f\n" would do what you describe in example 3. However, VariableArgs3 is not asking you to change the precision of the floating point arguments.
Lesley said: VariableArgs3 isn't asking you to code the kind of formatting you are requesting. You just have to print out the -double-, however it makes its way through your program. You should get the kind of behavior you wish "for free" (ie. without additional work).
I would like to quote Professor Humphreys: "Convince yourself: Either you understand the code, in which case, you’re on the road to greatness... Or... The rabbit hole goes deeper than you wish to go, in which case, you’re on the road to redemption."
Basically, your goal (do I have to code something that formats numbers like this to get credit) is accomplishable without answering your question specifically. If you want a solution to YOUR question (how to format a STRING that looks like a number into nice output), I would suggest regular expressions over printf mainly because: exactly how are you going to calculate your places_past_decimal variable? With regular expressions you can eliminate the need to calculate it at all. This code at least works with your test cases and a few others I tried.
import java.util.regex.*;
public class Precision {
public static void main (String[] args) {
String regex = "^0*((0|[1-9][0-9]*)(\\.([0-9]*[1-9]|0))?)0*$";
Matcher m;
m = Pattern.compile(regex).matcher(args[0]);
m.find();
System.out.println(m.group(1));
}
}
Lab Study 1
User 166 said: What if we can't get the graph to work/print out, but we edited our program to your specifications? If we submit that would that be ok? I still can't seem to get it to work and I don't really understand your directions becuase I'm mostly computer illiterate. Thank you.
User 14 said: You should really test your code before submitting it, and at the very least run it to make sure it works. Otherwise you won't know if you've made a small mistake that could cause your program to do something unintended (resulting in a lower grade than you could have gotten). My advice would be to start from scratch and make sure you follow the directions for the lab very carefully, especially noting where to put the code that draws the graph and how to correctly import the jar file.
Professor Sullivan said: Lynna, You can also see me after class today and I can have a look at what's up.
Running in Eclipse
User 368 said: When I try to run my program in Eclipse, I go to Run As and it says (none applicable). What can I do?
User 14 said: That could be a workspace issue caused by not using the correct workspace. I saw the same thing in lab last week. First make sure you're using the correct workspace. Otherwise, what worked in that case was just creating a new project and copying all the source files into that new project.
Another lab study 1 question
User 33 said: I know I've already turned it in and all, this is more for my curiosity. I'm pretty sure my histogram program worked (seemed to for me, at least), but when DrawDistribution made the graph, it always had horrendously inaccurate values for leftTail and rightTail in the picture. For example, I ran the histogram with an input of 2 billion (yay core2duo!), and had it print the two tail values. They were 576 and 578 respectively. Yet, the drawn image said they were 2.88E-7 and 2.89E-7. Why is that?
User 14 said: if you look closely at the drawn image, the leftTail and rightTail are displayed as P[leftTail] and P[rightTail]. These values are the
probabilities that a random number in your sample fell in the left tail or right tail. And so these numbers are what you'd expect, very small.
Assignment2: "
User 71 said: two questions about A2:
1.
I finished the program and try to run it, it will only work if I copy the data out from the txt into the console window after press debug/run, if I try put "< planets.txt"(brackets not included) in the arguments, it will start but is not doing anything (debug said the Thread(main) is running), until I type "< planets.txt" into the console and it will said source not found(in debug,error when run). I thought it was something wrong with the file's directory but I put it in that project's root directory which works for Blueplanet that I did for Groupwork, so it should not be a problem. So I trace the variable and found out that it read "< planets.txt"as two string instead of a special command(I try without the space in between and didn't work either). Since the "PlotFilter" file in the book can use the < command without doing anything else special, I don't know what the problem is here.
2.
When running, my planets all flying away from the sun outside the window. Since there's nothing run with the program I don't see a way to solve it by debugging. And it is a lot of work trying to find out the problem by tracing the variables...any advice based on former experience? Or I should just trace the variables and calculating them one by one :( ?
Lesley said: 1. #337
2. From the checklist:
My planets repel each other. Why don't they attract each other? Make sure that you get the sign right when you apply Newton's law of gravitation: (x[j] - x[i]) vs. (x[i] - x[j]). Note that Δx and Δy can be positive or negative so do not use Math.abs(). Do not consider changing the universal gravitational constant G to patch your code!
Something for Groupwork 2
User 71 said: I discover that the one of the test that are used the Robograde for Gravity1 is requiring a result of "-0.0" or negative zero, which will never be achieve unless you do the calculating within the printout command.
I discover it when trying to debug my program, and I guess that is the reason many people can pass 2 test in Robograde but just fail the one with negative zero.
Professor Sullivan said: We'll have another look at the test case and fix it if necessary (which seems likely).
Groupwork2 formatting error
User 86 said: Oops! Sorry. Our output is missing the "-" on the 0.0.
Compiling Gravity1...
Testing the command 'java -cp .:/home/moodle/robograde/cs101-spr08/stdlib.jar Gravity1 0.0 0.0 1.9889999999999999e+30 1496300000.0 0.0 5.9700000000000003e+24'...
Your program produced the following output:
Line 0: -3.5375093490093405E26 0.0
Line 1: 3.5375093490093405E26 0.0
Running our sample solution with the same command line...
Testing the command 'java -cp .:/home/moodle/robograde/cs101-spr08/stdlib.jar Gravity1 0.0 0.0 1.9889999999999999e+30 1496300000.0 0.0 5.9700000000000003e+24'...
Our solution produced the following output:
Line 0: -3.5375093490093405E26 0.0
Line 1: 3.5375093490093405E26 -0.0
WHOOPS! YOUR OUTPUT IS CLOSE, BUT NOT QUITE RIGHT! (line 1)!.
Thanks!
Professor Sullivan said: Ann,
I believe this is an example that illustrates the point that "floating point" arithmetic is complex in sometimes unexpected ways. A negative sign before a zero exponent is mathematically meaningless but it does cause our test to fail. In this case, the test should be changed (or ignored). Please submit a regrade to the TAs in the usual way, with a copy of this note, and they'll take care of it.
KS
Individual Assignment file addresses for grading
User 77 said: For the Galaxy Simulation individual assignment, where should we assume the the external files required (.gif and .jpg files) are located, since we have to call those files in the program?
Professor Humphreys said: #334
GroupWork Gravity2
User 200 said: Part of the description for Gravity2 reads as follows:
Your program should store this data in arrays:
one for the x positions, one for the names,
one for the x positions, one for the
y positions, and one for the masses
I assume that the redundancy is a typo, so is that supposed to be omitted, or is one of those statements supposed to say something else?
Professor Sullivan said: Thank you. We're sorry for the typo. It is now fixed. --KS
Gravity2 Output error
User 14 said: It's hard to say what happened without looking at your code. Make sure you're using doubles everywhere instead of "float". Floats will give you less precision. Otherwise, the best thing to do is show a TA during office hours.
Professor Sullivan said: Mathematically equivalent expressions can produce subtly different results when using floating point arithmetic. This case might well be an example of a subtlety in floating point computation. In general it's a bad idea to compare floating point numbers using == (which is probably, in essence, what our test case is doing). I'd have the TAs look at your code, and call us with us if you've done everything right but are getting and answer that differs in the last bits. In that case, we'll probably fix our test case.
So, if you generally should not compare floating point numbers using ==, how should you compare such numbers for "equality"?
KS
Audio For Bouncing Ball
User 251 said: I am able to compile and run my DeluxeBouncingBall program by taking out the audio parts with lazer and pop. I can not find any audio files in the n-body file. Any help on where to find the files?
User 14 said: 2001.mid is an audio file located in the nbody folder of nbody.zip
Professor Sullivan said: When you find the audio file you want to use, store it somewhere on your disk
other than in the workspace/project directory. Then drag and drop the file to the project icon in Eclipse. That'll add the file to the project in a place where your running program will find it.
Gravity2 Output error (in addition to previous post)
User 449 said: The previous post of this same name quoted rounding problems in Gravity2 (and presumably in Gravity3).
I think it is worth noting that my output was
identical to Kiran's. RoboGrader says to me:
Your program produced the following output: Line 0: Earth -3.541410008204977E22 0.0 -0.005928038179117805 0.0 Line 1: Mars -1.639662166651638E21 0.0 -0.0025543887936620006 0.0
Line 2: Mercury -1.3067081912709674E22 0.0 -0.03957323413903596 0.0
Line 3: Sun 1.0529518828292188E23 0.0 5.293875730664751E-8 0.0
Line 4: Venus -5.51743441215108E22 0.0 -0.011331760961493284 0.0 Our solution produced the following output: Line 0: Earth -3.5414100082049774E22 0.0 -0.005928038179117806 0.0 Line 1: Mars -1.639662166651638E21 0.0 -0.0025543887936620006 0.0
Line 2: Mercury -1.3067081912709674E22 0.0 -0.03957323413903596 0.0
Line 3: Sun 1.0529518828292188E23 0.0 5.293875730664751E-8 0.0
Line 4: Venus -5.517434412151081E22 0.0 -0.011331760961493286 0.0
ERROR! YOUR OUTPUT DOESN'T MATCH OURS! (line 0)!. The exact same statement is true of Gravity3 (considering they are basically the same problem). I suspect that once people get around to doing the groupwork, this will be a common error message. I am using doubles everywhere, so that is not the problem. I doubt the TAs want to process Regrade Requests from every student, so if the test case were changed, that would make things much easier for everyone. Also, if the case is not changed, would it be acceptable to change my program to fit the RoboGrade output in this particular instance?
Professor Sullivan said: Dude, you're off by a quintillionth. What do you expect?

I'll ask the good Dr. Humphreys to fix the test case.
Thanks for the diagnoses.
And remember, everyone: In general it's a bad idea to try to compare floating point values for exact equality. Numbers that should be equal are often off by just a tad. == will return false in such cases, even though the numbers should be considered equal (as here). It's best to compare floating point numbers
a and
b like this: if (Math.abs(a-b)<EPSILON) { ... }. That is, take the absolute value of the difference and make sure it's sufficiently small. EPSILON here is a floating point variable with a very small value, e.g., 1.0e-10 or something. Picking good values for EPSILON is an application-specific problem. The bottom line is that floating point numbers are problematical. They really don't act like
real real numbers. We'll talk later in the semester about conditions under which they are and are not reasonable substitutes for
real reals.
Read the input file - assignment 2
User 546 said: How can I make my program read the input file "planets.text"?
I am typing in the command prompt java NBody.java < planets.text and it is saying that "The system cannot find the file specified". But my file is the right directory...
I read some advices in the forum and saw that we could write in the Eclipse in the input window the things that are in the input file. Where is this inpu window? I can't find it... is it the console? I couldn't write in it...
Thanks!
Camila.
Lesley said:
- DOS: java NBody < planets.txt (not java NBody.java or planets.text)
- Eclipse: #346
BluePlanet image not found
User 380 said: When we run our BluePlanet program, it says that the file earth.gif cannot be found. We have added the nbody.zip and the stdlib.zip files to the libraries being used and it still won't work. Eclipse recognizes the file because when we add the nbody.zip to the library the red squiggly line disappears, but when we run the file (from eclipse or the command prompt) it can't find it. what are we doing wrong?
Lesley said: #334
how many points for each program in group assignment 2?
User 49 said: well, we have 7 programs totally. I submitted one and got 14. Is that full credits for one program?
Cuz some of my answers are "pretty close to" the keys. I was not sure if I lost some credits for minor differences.
Professor Sullivan said: 100/7=14.3, so that looks like it's close to full credit. That said, small differences are generally not ok, unless they're very small differences in floating point math (where small differences are to be expected). That is, we define equality a bit more loosely for floating point (doubles, floats), than we do for String, int, etc.
Changing Input within Eclipse
User 41 said: After some experimentation, it seems that attempting to redirect input from within the Eclipse arguments box (an option of Run Dialog) has no effect. In fact, the attempted command is simply stored within args[].
My command was "< planets.txt" (without the quotation symbols, of course).
Wondering over the logic of this, I ran the same program from within my terminal (with the same arguments), and args[] was empty. Presumably, there my command had the desired effect.
I would greatly appreciate any advice to aid in the circumvention of this issue.
Professor Sullivan said: Ethan,
There's no way to do it (that we know of). There is however a work-around: copy and paste the contents of the file you want to read from into the Eclipse console window. It's not great, but it works. Be sure to add a
ctrl-Z return at the end.
KS
end- of -file sequence, Book example Program 1.5.3 Averaging a stream of numbers
User 305 said: end- of -file sequence, Book example Program 1.5.3 Averaging a stream of numbers
I get an error when i type <ctrl-d> or <ctrl-z> as an end-of-file sequence and according to pg 131 in the book there are different conventions for this sequence.
so, am i doing something wrong? i cut and paste example onto eclipse, compiled it, all the normal stuff, but i get an error after typing in some numbers and using the end of file sequence.
Professor Sullivan said: Are you holding down the CTRL key while typing Z?
How to run a program in eclipse by using standard input instead of the command line?
User 49 said: Is that exactly the same as by using command line? type data in the argument?
Professor Sullivan said: No, copy and paste the data to the "console" window. When running a program within Eclipse, Standard Input is connected to the Console Window.
Running Bouncing Ball from command line
User 200 said: I got the Bouncing Ball program to work from Eclipse when I use audio and picture files, and it compiles fine on the command prompt, but when I try to run it on the command prompt, it gives me a message saying that the audio file wasn't found and that my picture file was corrupt. What do I do to fix this?
Professor Sullivan said: The files should be in the directory where you're running the code. When you compile from the command line, the .class files end up in the src subdirectory. When you compile in eclipse, they go into the bin directory.
Image Earth.gif not found
User 199 said: I am trying to run the DeluxeBouncingBall program but I get an error (whether I run it in the command prompt or through Eclipse) saying that the image earth.gif cannot be found.
I have added stdlib.zip and nbody.zip to my libraries and have tried to make sure the earth.gif file is in the same directory as the class file which is what you said to do in an earlier post.
In the explorer on the left side of the Eclipse screen there is no directory labeled bin; however I tried putting the earth.gif file under "default package" which is where the class file is. When I do this I get an error saying, "cannot place contents into the selected elements". I also tried to simply drag the earth.gif file into the project, but when I do this my pointer turns into a "no" sign (circle with line through it) and nothing happens.
What am I doing wrong??
Professor Sullivan said: That's strange. I just dropped Earth.gif into the top-level project (in Eclipse), and after that everything worked fine. See a TA or see me. I'm around tomorrow (in my office). If you want to stop by shoot an e-mail to make sure I'm here.
stdlib
User 53 said: I don't think that my standard library is working properly because everytime I run a program using standard library voids nothing happens. I went through the whole process of adding a JAR to my workspace and stdlib is listed under reference libraries.
Professor Sullivan said: See the TA in the stacks tonight. It's probably just a little glitch somewhere.
placement of external files
User 77 said: This isn't a problem per se (at least I hope it's not), but I've tried dragging external files (*.mid, *.gif, etc) into the project folder shown on eclipse (as shown in class), and I've tried to run the programs like that, but it never works. However, I've found that if I place the files in the src folder of the program, it runs perfectly, with no errors (at least at the command line). I know we were explicitly told that that wouldn't work, and that they had to be in the bin folder, but if it works this way, I guess there's no harm, right?
Professor Humphreys said: They need to be in the bin folder to run from within eclipse.
They need to be in the src folder to run from the command line.
re: Lab quiz this thursday
User 505 said: Will we have access to our textbooks during the lab quiz this thursday?
Professor Sullivan said: Yes
lab quiz
User 250 said: Are there any examples to practice where we have to "read an integer value n in from StdIn then use a for loop to read in n additional values from StdIn (ints, doubles, Strings)" which was from lab description
Question
User 368 said: I can't run programs through eclipse. The option to run as java app is not even there. What should I do?
Professor Sullivan said: See a TA in the stacks before 10PM tonight. Last chance before next weekend.
Robograde
User 124 said: After submitting Gravity1.java, I had it Robograded and it said I received 14 points for it; however, at the very bottom of the page the program said, "MINUS 10 POINTS FOR FORMATTING"... why's it doing this?
Professor Humphreys said: In general, the robograde output tells you exactly what LINE it's taking off points for.
However, looking at your output, it's clear that robograde isn't properly handling the case when one of us produces 0.0 and the other produces -0.0 (that's right, NEGATIVE ZERO).
This has been fixed, and your grade has changed.
Sorry about the panic.
More stdlib problems
User 89 said: I've changed my CLASSPATH so that it now includes the location for the stdlib.jar file, yet when I use the cmd line to compile I receive the following error:
javac: invalid flag: File\stdlib.jar
Usage: javac <options> <source files>
use -help for a list of possible options
The same error comes up even when I use the -cp function.
Professor Humphreys said: Does the stdlib.jar directory path (whatever you added to your CLASSPATH) contain any spaces?
If so, you should put the entire directory path in quotation marks.
Individual Assignment 2 - LeapFrog Method?
User 52 said: Hey
How are we suppose to make Force, (and all the other stuff in relation to time)? I have no clue how time gets factored into this (formula-wise). I get it conceptually, but I have a hard time writing it down mathematically. Could someone please elaborate?
Lesley said: If your Gravity2 program works correctly, you can just repeat the process you have already successfully implemented - forever (to quote the checklist, "Add an outer loop to repeat Steps 2 and 3 forever"). If your Gravity2 program is not working yet, you NEED to do that first. Please try following the steps on the checklist if you get lost, or see the section on the assignment page called "The numerics" because it will aid you greatly. The formulas for force are in the diagram under "Pairwise force." All of the formulas you need are listed in the assignment. I promise. I did this assignment last semester without any prior physics knowledge. Just follow the directions, don't overthink things. PS If you look carefully, t isn't even in any of the formulas!! Just dt (Δ
t) = 25000.
How do I get the console to open?
User 347 said: I'm attempting to run a simple program I found in the text book so I can practice using StdIn and StdOut. I got it to run fine in the command prompt, but I can't seem to get Eclipse to cooperate with me. To the best of my understanding, I need to work through the console window. However, I don't seem to have one, or maybe I just can't find it. Any help would be greatly appreciated.
Professor Humphreys said: You can use StdIn and StdOut within eclipse; you just type into the little window at the bottom of your run.
The command prompt on Windows is usually located in the start menu under "Accessories".
You can also get there by going to Start->Run... and typing "cmd" in the dialog box that comes up.
Professor Sullivan said: Window>Show View>Console
If you've explicitly closed the console window this will "get it back" for you.
KS
Command Line with Std Libraries
User 222 said: I've been reading up on everyone else's similar problems with being able to compile in Command Prompt. I've changed the CLASSPATH and everything, and I'm still having problems compiling...Any other suggestions?
User 14 said: It's hard to know what the problem is without seeing what the compiler is telling you and what commands you're using. The easiest way to fix this is to see a TA at office hours, but that will have to wait until Sunday. The only other suggestion I can give is to make sure you refer classpath to all sources of libraries you're using. So if you are referencing both stdlib.jar and files in the current directory, you would need to say "javac -cp .;j:\workspace\stdlib.jar something.java" In this case, the ".;" at the beginning is important.
Professor Sullivan said: Be sure that the CLASSPATH environment variable includes the full path to the stdlib.jar file, including the name of the file, stdlib.jar. If your path name has any embedded spaces, you need to enclose the whole thing in double quotes. Come see me if you can't get it to work.
USA.txt
User 250 said: I am having trouble getting the PlotFilter program to run. I do not know how to get the USA.txt folder into the arguments so that I can run the program. How can I do this?
Professor Humphreys said: On the slides, USA.txt is redirected into standard input; it's not an argument.
So run:
java PlotFilter < USA.txt
If you're using Eclipse, you will need to copy-and-paste the contents of the file into the input window and press control-Z to terminate the input, as always.
Professor Sullivan said: I think Prof. H. meant to say, at the command line do this:
java PlotFilter < USA.txt
Notice the "< USA.txt", which connects the standard input of the program to the file, USA.txt
If you want it to work in Eclipse, open USA.txt in an editor and copy and paste the contents of the file into the Eclipse console window
random stdlib error
User 89 said: I've had my stdlib working fine until I closed the cmd prompt window I had been working in. When I started a new cmd prompt window, I received the following error:
symbol: variable StdIn
location: Class Gravity2
double mass1 = StdIn.redDouble();
^
This appears to treat StdIn like a variable, but I have Eclipse and CLASSPATH set up correctly, as they worked 15 minutes ago.
User 14 said: Changing classpath while the command prompt is open won't always immediately update it. Try closing all command prompt windows, then changing the classpath to the correct value. Then when you open a new command prompt, everything should work, ideally. But If that doesn't work, try just setting the classpath after the javac or java command. i.e. "javac -cp ..."
Lesley said: StdIn.
redDouble, hrm?
Gravity2 and Robograde
User 124 said: I've repeatedly submitted Gravity.java, and every time at the very end, Robograde reads just one last sample that has output values that don't match mine... I have no idea what to take from that. Help?
Professor Humphreys said: Looking at your robograde output (and your grade!) it appears that you have gotten all the points for Gravity.java, so I'm not sure what your concerned about. Your program is correct.
BluePlanet and Eclipse
User 124 said: This program would not run in my Terminal (I have a Mac), yet I received full credit for it in Robograde. In my Terminal it says i have 3 errors, all having to do with not naming "Std." I'm pretty sure I downloaded all the appropriate files into my library, but what's going wrong?
Professor Sullivan said: You have to set up your CLASSPATH environment variable to include the path to the stdlib.jar file. You do this for any command line compilation independent of your Eclipse settings. There are several other postings on this forum on this issue
USA.txt
User 250 said: Where can I download the file USA.txt so that I can upload it?
Professor Sullivan said: Booksite, appropriate chapter and section (as stated in class)
BluePlanet
User 124 said: I've done everything I know to try and add the right files to this program, yet this keeps popping up in my terminal window... Help?
d-172-26-31-196:~/desktop/CS101/BluePlanet/src michaelincerto$ javac BluePlanet.java
BluePlanet.java:6: cannot find symbol
symbol : variable StdDraw
location: class BluePlanet
StdDraw.setXscale(-R, +R);
^
BluePlanet.java:7: cannot find symbol
symbol : variable StdDraw
location: class BluePlanet
StdDraw.setYscale(-R, +R);
^
BluePlanet.java:8: cannot find symbol
symbol : variable StdDraw
location: class BluePlanet
StdDraw.picture(0.0, 0.0, "earth.gif");
^
3 errors
d-172-26-31-196:~/desktop/CS101/BluePlanet/src michaelincerto$
NBody.zip?
User 196 said: I am trying to get the things i need from the NBody file downloaded off the site but whenever i download it it will only save as a .zip file. Im was not sure what to do becaus I know this wouldnt work so I tried to extract it to make it a .jar but it will never let me get it. So i cannot get all the audio/picture files for the individaul assignment. What should I do?
Nathan Wethington
Professor Humphreys said: NBody.zip is, well, a zip file. It's just a bunch of files that you will find useful. They're not Java programs or anything, just unzip the file somewhere and you will have a directory full of universe descriptions.
Lesley said: If you have Windows XP or higher, do right click - explore on nbody.zip. Then select all (click in the folder window it pops up and press 'control' and 'a' or edit - select all) and copy the files (right click - copy, edit - copy, or ctrl+c) and then copy them into where you need them (the bin folder of your project most likely) by doing edit-paste or ctrl+v.
If you don't have this "explore" option, you could consider downloading shareware like WinZip which will extract the files for you.
Planets leaving the solar system
User 380 said: For the individual assignment, I plug in the sample values given on the assignment page:
5 2.50e11
1.496e11 0.000e00 0.000e00 2.980e04 5.974e24 earth.gif
2.279e11 0.000e00 0.000e00 2.410e04 6.419e23 mars.gif
5.790e10 0.000e00 0.000e00 4.790e04 3.302e23 mercury.gif
0.000e00 0.000e00 0.000e00 0.000e00 1.989e30 sun.gif
1.082e11 0.000e00 0.000e00 3.500e04 4.869e24 venus.gif
and the planets start to orbit the sun, but when they get about 60% of the way around the orbit, they shoot straight off into space. Is this supposed to happen or is there some problem with my leapfrog approximation?
Professor Sullivan said: That doesn't seem like it's consistent with the behavior of astronomical bodies under the force of gravity! My guess is that the model is wrong, not the laws of gravity
using planets.txt
User 53 said: The help page for the individual assignment recommends that we read in planets.txt using StdIn. and print it before starting to write the program. How exactly do we do this?
Professor Sullivan said: Figuring that out is really the essence of the exercise. Apply some of the strategies we've talked about before. Break the problem into parts and then solve the parts separately. For example, ...
- Read in the data and store it in appropriate variables (including arrays)
- Then print out those variables (including arrays -- using for loops of course)
selection does not contain a main type
User 473 said: When I try to run Triangle, it shows that selection does not contain a main type. How to solve this problem? Thanks.
Professor Sullivan said: Be sure that Triangle.java is selected in Eclipse when you issue the run command, and be sure that you typed
public static void main and all that stuff exactly right.
Readings planets.txt
User 200 said: I'm having trouble getting NBody to work by reading the planets text file as input. When I manually type in all of the arguments from the text file into the command prompt(which took a LOOONG time), the program works fine, but when I actually type % java NBody < planets.txt, I get an ArrayOutofBounds Exception: 0. I went into the text file and made sure everything was spaced appropriately, and I figure that the ArrayOutofBounds Exception means that my computer can at least find the text file, but it's not inputting any of the arguments into the program. Any ideas?
Lesley said: Make sure you're using StdIn to read the values, not args[].
Professor Sullivan said: First, you can cut and paste the contents of the file into the Eclipse console pane. Just open the file in any word processor, e.g., notepad, wordpad, etc (which are both available under Windows Start>Applications). Then select all the text (control-A), copy to your clipboard (control-C), and paste into the Eclipse window (control-V). I'd start by doing this and see if it runs okay in Eclipse, and take it from there.
Confusion about Assignment 2
User 347 said: I'm a bit stuck on Assignment 2. My gravity 1, 2, and 3 programs all worked fine, but my NBody program doesn't. As soon as my planets cross the 90 degree mark, they fly off into space. I've seen several posts about this but I haven't been able to figure out why my planets are doing this. I've checked all of my signs and everything seems to be ok, but my planets keep flying away! It seems like if all of my other programs worked, my planets should stay in the solar system.
Also, I read that we should not include steps 1-3 in the same loop, but it seems like we kind of have to in order to make sure that the x and y components of the gravitational force are constantly updating. Otherwise, the system is using values for which components have been changed but unaccounted for.
Professor Sullivan said: I recommend using the debugger to see what's going on with the values in your program. It's clearly doing something wrong at some point. Set a breakpoint at the beginning of the main animation loop. You can use the debugger's resume command to start the program running again from a breakpoint. Execution will stop when control gets back to the breakpoint. You might have to resume quite a few times before your planets get themselves into the position where the bug takes hold.
Assignment 2 being weird...
User 347 said: My assignment 2 is being really weird. It seems like whenever I stop using the arrays for fx and fy and have the program constantly calculate the acceleration, things start working. However, the program only works when the sun is the last element on the list. If I read in the information as given, only Venus orbits the sun while the rest of the planets fly away vertically.
When I do use arrays for fx and fy in my calculations to find the acceleration, the planets just sling shot around the sun. What's going on here? Nothing I do works.
User 14 said: Make sure your loops are structured properly. You want object to calculate its net force based on the forces between every other body in the system. It might help to go through an example for one of the planets at the beginning, using the debugger. Go through your code step by step and see if the forces are being correctly calculated for every other object.
Having problems with StdDraw.picture
User 270 said: I tried edit the Bouncing Ball program so that it can show the earth picture instead of a black ball (like what Professor did in the class). However, eclipse keep underline the word "earth" with a red line, which preventing from running the program. I already copy and paste the earth.gif file from the NBody zip file the bin and src folder of the project. I also tried to drag the picture file to project on the left side of the eclipse (like what Professor did in the class). I even tried to save the whole NBody zip file in the project folder and add the NBody through libery > property > add external jar. None of these methods worked, eclipse still underline the word earth with a red line saying variable is unreasolved. I don't understand why.
Professor Sullivan said: Without seeing your code it's hard to guess what's wrong, but it sounds like you are using
earth as a variable name (undefined), rather than specifying the file name (of type String), "earth.gif" (with the double quotes) as a parameter to the StdDraw.line function.
starfield.jpg
User 53 said: I've been following the steps in the Help page for Assignment 2. Step 3 says to use StdDraw.picture to plot the background starfield.jpg . I've written the code exactly how prompted to in the book and by eclipse, but I keep getting the same message:
Exception in thread "main"
at StdDraw.getImage(
at StdDraw.picture(
at NBody.main(
I've downloaded the stdlib and NBody zip files into the workspace. The last line of the error message refers to a line of code in my program that sets the x-scale for -R to R, as indicated by the instructions. Do you know what's wrong? Who can I see about this problem before Sunday?
java.lang.RuntimeException: image starfield.jpg not foundStdDraw.java:481)StdDraw.java:496)NBody.java:28)
Lesley said: The picture starfield.jpg is not in the directory where you are running your program (I duplicated your error by doing this at least). You need to UNZIP NBody.zip and put the images and text files in the src and/or bin directory/ies of your project. If you don't know how to unzip a file, there are instructions for how to do this at
#420
Is it possible?
User 52 said: How are the planets suppose to follow the laws of gravitation when we are only calculating the net forces between 4 planets when there are actually 9 planets in the solar system.
Please elaborate on these extremely difficult programs that even 4th years cannot comprehend. (Maybe....)
Lesley said: Please see the "enrichment" section of the checklist for physics details of the NBody prodedure. But here are some more things for you to think about.
The Sun's mass is about 333,000 times Earth's mass.
The mass of Jupiter is 318 times that of Earth.
(On top of that: Sun to Earth: 1AU; Earth to Jupiter: about 4AU)
You should also be bringing up that the orbits of the planets are elliptical, not circular due to the fact that the sun is not at (0,0) like the text files claim but rather at one focus. Though if you've taken any astronomy class you'll know that the orbits are elliptical with very little eccentricity. (Wikipedia says Earth's Eccentricity is 0.016710219)
If you prefer, there's a text file called elliptical-nine.txt... Though I think that's probably a worse example because it over exaggerates the eccentricity (see http://freeutah.net/images/blogspot/planet_orbits1.jpg)
You should also consider in your question that the sun is moving, so how can we calculate anything without including the whole galaxy, universe, etc? We don't take into consideration how the planets are rotating... The model blatantly says it uses constant acceleration... It is just an approximation that works well given certain circumstances.
Program with Home Dir. and Stdlib
User 331 said: I am having trouble loading my home dir to eclipse. My home dir. loads but when eclipse asks for the workspace and i use my home dir, it comes out with an error "j:\workspace\.metadata\.log".
Also when I still had eclipse working, i tried to get stdlib to work and it wouldn't. Now i cant delete it off my desktop because it says its being used in a program but nothing is running. I dont know if this is related.
Dan
User 14 said: I think restarting your computer will get rid of that second problem. And possibly the first too.
Planets really slow
User 270 said: By using dt = 25000 and StdDraw.shoe(dt), the planets are extremely slow. Is it supposed to be like that?
Lesley said: If you use StdDraw.show(25000) that's quite a delay. You only need to do StdDraw.show(20) or StdDraw.show(30) at most. (StdDraw.show() is unrelated to dt)
README Template?
User 52 said: Why do the directions say to upload the README file on Eclipse? When the file to be uploaded must be a txt file? If done on Eclipse, it would be a java file? yes? Just confused...
User 14 said: You can edit txt files in Eclipse. If you want to create a .txt file while in Eclipse, go to New --> File and then type in "readme.txt"
Galaxy Simulation extra credit deadline
User 459 said: Hey, I was wondering if the galaxy sim. extra credit is also due on Wednesday. It would be nice if it were due a couple of days later.
Step 2:Planet not moving on given velocity
User 254 said: I set scale x(-2.5E11,2.5e11) y(-2.5e11,2.5e11). In step 2, my planet does not move on given velocity, but move as discribed when I changed the velocity for 10^4 to 10^9. the FAQ does not help,cause i have not moved to step3, there is no t value to change. and my Std show time is 20.Thanks
User 14 said: I'm not sure what you mean by "there is no t value to change." You need a time variable in order to calculate new positions for each planet. If this time value is larger, the planets will appear to move faster. You shouldn't need to change the velocities.
Professor Sullivan said: It's true that you might not need an explicit representation of time. To do the animation, all you really need to know is the difference in time between two frames: delta-T.
Deluxe Bouncing Ball
User 489 said: I'm trying to set up for the bouncing ball test and by earth starts in the upper right going to the upper right corner. When it hits the wall I get the following errors
Exception in thread "main"
at StdAudio.play(StdAudio.java:147)DeluxeBouncingBall.java:15)
at DeluxeBouncingBall.main(
I'm assuming that the audio files it is calling are not there. And I can't find them in the Nbody Zip. So where are they, and where do I put them in the DeluxeBouncingBall file to get this thing running????
java.lang.RuntimeException: audio pop.wav not found
Professor Sullivan said: Download the .wav files from the book site. Read the chapter/section (online) in which the topics are discussed. Links are there. Put the files in the
bin not the src directory of the project in your workspace.
Student.java Stdin
User 489 said: I tryed to complie the students.java file and got 8 errors about
"Cannot find symbol
Sysmo: varriable StdIn"
The location is every StdIn command given. ??????
Professor Sullivan said: We've talked about this quite a few times by now. You need to have stdlib.jar as part of your project.
HELP
User 124 said: I cannot find a way to run a program using StdIn or StdOut, and I have tried and tried to make it work with the help of others but I can't. I'm using a Mac and I would love it if I could get specific instructions on what to do with downloading the right files and such so I know if I've done everything right or if there's some other problem.
Professor Humphreys said: the procedure for getting stdlib.jar to work in eclipse is IDENTICAL on the Mac to the procedure on windows.
1) Create the java project
2) Project menu --> Properties
3) Choose "Java Build Path" on the left
4) Choose the "Libraries" tab
5) click the "Add External Jars" button
6) navigate to the location of stdlib.jar
That's it.
Another StdIn problem
User 489 said: I'm trying to get the planets.txt as a String planets = StdIn.readString(); And then print them out using a System.out.println(planets);
when I compile I get the error of
Javac :file not found: PlanetsReadIn.java
Usage:Javac <optional><Source Files>
use -help for a list of pissible options
I'm assuming that the external jar file is not doing it's job cause I can see the StdIn.class in my directory....????
Professor Sullivan said: You're not meant to use one statement to read in the names of all the planets. Rather, each line of input includes on planet name as a string. See a TA for more help. Someone will have to look at your code.
Another StdIn problem update
User 489 said: After a Google I seteled on the below code.
public
String planets = StdIn.readString(
System.
}
}
But the compiler still dosnt like my planets.txt as a string read in
unclosed character literal
?????? P.S could it be made so students can add replies to the tech forum so we can update our own postings or possible help others???? THXS
class PlanetsReadIn {public static void main(String[] args){'planets.txt');out.print(planets);
User 14 said: This post is very difficult to read, but you need to use double (") quotes around planets.txt rather than single(') quotes.
Clearing image trails....
User 427 said: When I run my nBody program, the planets leave behind at trail of images everywhere they do. How do I prevent this?
Lesley said: Quoting the assignment page:
After each time step (i) draw the background image starfield.jpg, (ii) redraw all the bodies in their new positions, and (iii) control the animation speed using StdDraw.show().
StdDraw.show()
User 505 said: I am trying to use the StdDraw.show() to control the animation. However, when I type that line of code at the end of my program, i get an error that read "Unreachable code". I have the stdlib jar file isntalled correctly, so i dont know what the problem is.
Thanks.
Professor Sullivan said: The term
unreachable code refers to code that can never be executed. For example, consider this code fragment:
if (false) {
StdOut.println("Hi");
}
The code inside the curly braces is unreachable. There's no way that it will ever be executed.
In your case, there's no problem with your stdlib.jar. Rather, the problem is in the logic of your program. Read through your code very carefully and figure out precisely how it executes. You'll very likely see that there's a problem with the logic.
Kevin Sullivan
I cannot get StdDraw.picture to work
User 320 said: Perhaps it went over my head during lecture, but I cannot get images from NBody. I copied and pasted the NBody folder (unzipped) into my src and bin and wrote the code StdDraw.picture(0.0, 0.0, "earth.gif"); for BluePlanet.java, but I always get an error message.
Is there a StdDraw.getImage involved? If so, where is it, because such a command is not in the standard library.
Could you please go over the steps to getting pictures such as earth.gif and starfield.jpg to work again?
Professor Sullivan said: These files (one way or another) need to be placed into the
bin subdirectory of your project, if you want them to be found when running the program from in Eclipse.
Unsure how to compile and run Assignment 2
User 296 said: I can only compile programs that use StdIn/StdOut in eclipse (I installed Stdlib.jar already). When attempting to compile in command prompt, I get error messages for each usage of StdIn/StdOut. This is not a problem for programs that take command line arguments, or input from the console, but I don't know how to run NBody.java to take input from planets.txt. The only way I know how to do this is through the console, but this does not allow me to use Stdlib. The alternative is compiling in eclipse, but then I don't know how to receive input from a .txt file.
Professor Sullivan said: Best to see the TA's in the Stacks.
Stdlib.jar problems and problem reading files
User 560 said: I have modified the class path on my desktop to include the stdlib.jar file, but i still get error msgs when compiling in the command prompt for every use of stdout/in.
I am also having problems reading input from files in eclipse. I am just trying to read data from planets.txt to test if it works, but when i open the console and run the program, it gives me error msgs when i type < planets.txt. Does the file have to be somewhere specific?
Professor Humphreys said: This has been posted about MANY times on the forums.
You need to copy/paste the input into Eclipse. You cannot redirect input like you can at the command line.
Open the input file in a text editor (like eclipse, notepad, etc), copy the contents, and paste them into the console window.
Blinking Planets
User 531 said: On my N-body program, the planets follow the desired path, but the further their N-value gets from 0, the more the start blinking when they are being drawn. Body 0 is always present, body 1 blinks a little, body 2 more, and so on and so forth until the planets at the outer edge are hard to follow. Im using a for loop to print bodies 0 to N-1, and reprinting the starfield every time to clear my trails. There is sometimes a visible delay when printing the bodies, you can tell what order they are being printed in. Any advice to make it run smoother?
Lesley said: Blinking is usually caused by incorrect use of StdDraw.show() but without seeing your code, it's hard to know exactly what is wrong. There are office hours in the stacks right now that you should consider coming to.
Planets velocity
User 531 said: In my Nbody program, planets start out doing what they are supposed to but it seems like their velocities just go up and up and up. using planets.txt, the orbits stay cirular but increase in radius as the planets pick up speed until they are offscreen. My force IS clearing before every frame. I used the formulas a=f*m, V=a*(t-(t/2), and position = v*(t+t/2) like the assignment help said to. can anyone spot my mistake?
User 14 said: I don't think those are the right formulas for velocity and position. The right formulas are on the assignment page. Velocity should be (
vx + Δ
t ax,
vy + Δ
t ay), and there is a similar looking formula for position below that.
how to play 2001.mid
User 543 said: StdAudio.play() only plays .wav files, right? But the file we want to play is a .mid file. Do we have to convert this .mid file to .wav somehow? And if so, any hints on how we should go about doing that?
Lesley said: Misleadingly the documentation would lead you to believe its capabilities are limited to .wav files. However, it can play .mid files too. Try it. :)
Error message when adding audio
User 223 said: I tried to add sound to my program, so I moved the 2001.mid file to the src folder, and I also added the code you had metioned in the helpsheet at the beginning of my program StdAudio.play("2001.mid"), but for some reason whenever I run the program an error message comes:
Exception in thread "main"
at StdAudio.play(
at NBody.main(
java.lang.RuntimeException: audio 2001.mid not foundStdAudio.java:147)NBody.java:14)I'm not sure what I am doing wrong. A TA in office hours got it to work on the command line, but I still can't run it in eclipse. The other files I moved into the source directory worked just find so what is different about audio? Thanks for the help.
Professor Sullivan said: You should drag and drop the file into your Eclipse project at the top level. What that actually does is to put it in the
bin folder.
Lesley said: She had done that. It was in the bin (and src) folder, I checked. It worked at the command line with no problems, but eclipse refused to recognize the file's existence. ...Any ideas?
User 167 said: If you put a file in a project's src directory, then Eclipse will copy it to the bin directory when it compiles the code.
However, for some reason StdAudio seems to look for the file in the root of the whole project, so you need to put the midi file there instead. I saw this problem several times last night, and I don't know why StdAudio works like this; it seems like it's probably a bug in StdAudio, especially since StdDraw looks for images in the correct place.
--
Dan
Path of the planets
User 323 said: When going around the Sun, are the planets supposed to follow a circular path or an elliptical one?
Lesley said: The data from planets.txt will model planets taking a circular path. The data from planets-elliptical.txt -> elliptical paths.
Path of the planets, again
User 323 said: When I run my NBody program using planets-ellipcital.txt, one of the planets close to the sun actually goes through the sun during its path. Is this a problem?
Lesley said: No, it's not a problem, though that's not actually what's happening. It doesn't go through the sun; its image is improperly scaled which gives the illusion of it going through the sun.
Massive Loop
User 260 said: I've followed steps 1-3 and, based on my successful groupwork assignments, i know i'm calculating the force and acceleration properly. My planets revolve for a short period of time then slingshot off into deep space. I think what is happening is step 1 is accounting for the forces on the originial x and y positions, but not the new, updated positions. I know the help file said you should not use a massive loop to encompass the three steps, but it seems like that is the only way to ensure the forces are updated according to the new positions. How can i make my planets revolve instead of fly off screen?
Lesley said: How are you plotting these new positions? Consider storing the coordinates in a variable, which you can reference when you need to calculate forces.
Your (infinite) loop needs to recalculate the force of each planet on each other planet before plotting the position. There's a difference between the infinite loop to keep it going, and the loops your program uses to do each step in the physics calculations.
Professor Sullivan said: There will be a pretty big loop, right? Within the simulation loop you need to calculate net forces on each planet, and that itself requires a nested loop.
standard audio
User 440 said: my stdaudio.play("2001.mid") messes up my program and it gets stuck. what is wrong? it runs without the music perfectly fine.
Lesley said: How exactly is it "messing up your program"?
Make sure you're not trying to play the file every 20 milliseconds. Using Professor Sullivan's outline:
- ....
- Set up graphical output
- Set up X scale
- Set up Y scale
- PLAY MUSIC HERE
- Run Simulation/Animation Loop -- a while loop
- Update planet positions and velocities -- from group work
- Redraw the universe
- Draw background
- Draw each of N planets -- a for loop
- DON'T PLAY MUSIC HERE
- Wait reasonable number of milliseconds
Professor Sullivan said: That's for sure: you don't want to try to play the tune each time through the simulation loop!
Did Robograde die?
User 146 said: As soon as I upload a new version of a program, it gives me the Compiling (file name here) ... then promptly does nothing. No additional information besides a lovely grade of 1.0. Is this just me?
Professor Humphreys said: This was fixed, robograde is all better now! Sorry!
Audio for NBody wont play
User 66 said: My NBody program works, but when i try to add the audio i get an error....
audio 2001.mid not found
I have downloaded and redownloaded the file. Right now it is in my src with the rest of the images and everything and they dont error, why is the audio file not working?....it plays on my computer when i open it, so its not corrupt.
Lesley said: #465
ie. The conclusion is to put it in the folder one level above bin or src. ie. j:\workspace\NBody\src -> it should go in the NBody folder
Image Errors
User 213 said: I've put the NBody image files into my bin folder, but every time I try to run my program it comes up with the error message
"Exception in thread "main" java.lang.RuntimeException: image starfield.jpg not found
at StdDraw.getImage(StdDraw.java:481)
at StdDraw.picture(StdDraw.java:496)
at NBody.main(NBody.java:74)"
What am I doing wrong?
User 14 said: Try dragging them into the Eclipse project. This will put things in the correct place.
resubmit quiz 2
User 244 said: i have consulted the Zhiheng about this and he suggested that i post this question here.
i went to lab and did quiz 2 last thursday, but i got a zero because i seem to have submitted the program skeleton without my code. is there any possible way for me to redo the quiz and submit it again for a grade?
cast String>Double
User 437 said: What is the code to cast from String to Double from an Array of String?
Lesley said: You'll need to make a new double array with the same length of the String array and then parse and store each element of the String array into an element in the double array.
"Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
User 27 said: I added StdIn.java, StdDraw.java, and StdAudio.java to my project alongside NBody.java. However, when I ran NBody from the command line, my audio is choppy and the planets don't even get the chance to load before the StdDraw window crashes. Apparently java is running out of memory, but I have no idea how to fix it.
Professor Sullivan said: James, We really cannot diagnose program malfunctions on these forums. You may not post code, and without looking at code it's all but impossible to say what's going on. We provide TA and faculty office hours to deal with such issues.
looping an audio file
User 380 said: What is the best way to go about looping an audio file to play again once it finishes playing. For instance, in the NBody program, 2001.mid only plays once and then there is no sound if you want to watch the animation further. Is there an easy way to make the audio file play again when it is over?
Professor Sullivan said: Joseph, You could write a
while loop that would keep playing it again and again, but then the rest of your code would never run! What you really need here is a construct we won't cover this semester,
concurrent threads of control. When you run a program in 101, there is one "thread of control" that snakes it's way through your program executing one line after another. Imagine that you can have several threads executing concurrently. Well, in that case, you could have one running the loop that repeats the music, and another running the loop that does the simulation. If you're interested, search the web for
Java Threads.
Group work robograde
User 240 said: I just want to clarify:
We can run Robograde on group assignments and then change things if we don't get 100%, right?
Thanks!
User 14 said: Correct
StdIn Planets.txt
User 489 said: By following the recommended Procedures for the Gravity Lab, I got the planets read in program to compile and run but it only returns the 5.
String P = StdIn.readString();
System. out .println(P);
Do I need to put the string in an array or something to get the rest of it???
Professor Humphreys said: Hi Grant. readString only gets the *next* string, separated by spaces.
See slide 14 of the Input and Output lecture for a description of how the StdIn functions work. They're also documented in the book in section 1.5, where there are many examples.
groupwork3
User 71 said: I know how to read a parameter, but I've no idea how to not read any parameter. When I leave blank in the brackets of the signature it always said syntax error. What am I supposed to do?
Professor Humphreys said: public static void some_function_that_takes_no_parameters()
{
// Do something fascinating
}
Professor Sullivan said: public static void some_function_that_takes_no_parameters()
{
// Do nothing fascinating
}
groupwork3
User 71 said: When I try to return an array of double I wrote"return arrayname;", just like what they did in the book, but the debugger kept saying:"can't convert double[] to double". I don't know where I did wrong.
Thank you.
User 14 said: Make sure your return type is an array of doubles instead of just a double. For instance:
public double[] foo()
instead of
public double foo()
Extra Credit files won't load
User 226 said: The website refuses to upload by extra credit file, even though I used the correct name. Is there something else I can do to make it upload?
User 14 said: Donna came to me after lab today with this question. She said she put everything in extracredit.zip but the submission system wouldn't accept it. The submission is closed now, so I couldn't help her out, but does anyone know why this might happen?
Submission closed 9:55 p.m
User 234 said: When I was submiting my extracredit.zip and nbody_readme.txt, I've got the message about technical problem. In result extracredit.zip was downloaded, but nbody_readme.txt not(time was 9:55 p.m). After that submission was closed. Could you please help me?
Professor Humphreys said: Can you explain what the "technical problem" was? We got 429 successful submissions.
Click Sound in StdAudio
User 486 said: So I wrote this program that plays the mario theme song tonight that ends up playing a bunch of notes quickly, and the tones and lengths are right, but it doesn't sound very good because it keeps clicking; is this just because because java/eclipse/computers are not supposed to actually play songs this way, or is there a way to make it sound smoother?
-Jamie Johnston
Professor Sullivan said: Jamie,
First,
good work for going above and beyond the required work. It's just great when we hear that people are starting to write real code.
My suspicion is that you're calling
play many times, once for each tone. If you do this, there will be short gaps between tones, and I wouldn't be surprised to hear them as pops. Try creating a single big long array, and see how that works. You might, for example, define a new function like this:
public static double[] append (double[] a, double[] b) { ... }
This function would return a new array of length a.length + b.length, whose first a.length elements are identical to those of a, and the rest of which are identical to those of b. You could then use this function repeatedly to
string together a bunch of separate tone arrays.
KS
sumArrays.java
User 236 said: the goal of this program is to "Write a function
sumArrays that takes as parameters two arrays of doubles of equal length and that returns a new array of doubles of that same length equal to the sum of the two given arrays. (Add elements at index
i in the given arrays to compute the value of the new array at index
i)."
What output should I have if the arrays for two of the tests in Robograder are cases when the two arrays do not have the same dimension?
false?
and I am having the same problem as Jun Wang, and yes, I have what you said to him, Mr. H.
Professor Sullivan said: Your question is a really good one. In general, as a designer of a function, you have to decide whose job it is to make sure the function is used correctly: is it the job of the function to check (and to do something special in case of misuse) or is it the job of the client (who risks a serious malfunction if it uses a function incorrectly -- since the function itself doesn't check)? In this case, we've clearly decided that it's the
client's job to use the function correctly. What that means for you is that
you don't have to check or to do anything: just assume that you get arrays as parameter values that satisfy the requirement: the arrays must be (and are assumed to be) of equal length. Note: if you want to write really robust (dependable, bug-free) code, then you want functions to check that they are being used correctly. If you want to write code that's simple and fast, then you don't want functions to have to do such checks. As in much of engineering, it's really a matter of trade-offs, and there is no answer that's best in all cases.
KS
Professor Humphreys said: These are all excellent points!
However, the assignment said that they can assume they are equal length; my test unintentionally violated this.
I have updated the test to be in line with the spec. Sorry.
Groupwork3 - tone
User 33 said: Can someone explain exactly what this project is? I've been skimming all the functions to write, and this one doesn't make sense. For example, how big is the array that i'm returning? Is it a function of time, or the frequency?
Professor Humphreys said: It was covered in lecture.
Groupwork 3 - Credit Card
User 375 said: Robograder is asking for "validCreditCardNumber.java" and the submission screener is looking for "validateCreditCardNumber.java."
Either I cannot submit the program robograder is looking for, or robograder will not bother to look at "validate..."
thanks,
alan
Professor Humphreys said: Whoops!
I really appreciate the bug reports. I hope it underscores the fact that it's incredibly hard to get software right in ever last detail :)
(It's fixed)
lab today??
User 98 said: do we have to go, or like is there a file we have to submit at the end?
Professor Sullivan said: There is lab today, as there is every Thursday. Your TA will explain when you arrive.
More Mario Help
User 486 said: So I added
public
{
e[f] = c[f];
e[g+c.
}
to the beginning of my code, and it works for a while in the program, but I get a heap space error after about 75 notes; this is even after I thought I reset the note array. Do you know why it would do this?
static double[] append(double[] c, double[] d) double[] e = new double[c.length+d.length];for (int f=0; f<c.length; f++)for (int g=0; g<d.length;g++)length] = d[g];return e;
Professor Sullivan said: Your posting seems to be malformed. The code as posted is syntactically incorrect and I can't tell from it what you're doing. Feel free to send it to me in a separate e-mail.
Assingment 2 after the fact
User 305 said: i know its after the fact but i was wondering if a TA or someone could help me get assingment 2 to function properly, i have everything but getting the planets to rotate, i just want to know why its not working, my physics and initial image is fine, but for some reason inside my while loop positions aren't being regenerated, just wondering if anyone was available on campus today to go through this real quick. Thank you.
Lesley said: I'm not sure what the policy on 101E students attending 101 labs is this semester... I say this because the solution was discussed in labs on Thursday.
Professor Humphreys made sure to go over assignments' solutions in class last semester. I'm not sure if he's planning to do this again this semester, though.
Feel free to come by the stacks Sun, Mon, Tues from 6-10 and a TA will be more than willing to help you then. With ~500 students, it's really impossible to offer help outside of these specified times (even just a few minutes before or after in the stacks), especially for the sake of fairness.
Professor Sullivan said: Jose,
We'd also be glad to see you in our office hours, e.g., on Monday. I'm glad you're determined to debug your program. In the meantime, may I suggest that you try two strategies: (1) read your code super-carefully and mentally simulate what it does; (2) use the debugger to watch it operate. Pay attention to small issues: an x here instead of a y, for example.
KS
TA's at Stacks on the 14th???
User 489 said: Just checking to see if the 101 TA's are suposed to be at Stacks today from 18:00 to 22:00????
Professor Sullivan said: Yes: Sunday - Tuesday.
Groupwork 3, Question 4
User 264 said: I've tried to do #4 by following the relevant example in the book, but it says "the method must return a result of type boolean". What am I doing wrong?
Professor Sullivan said: If you declare a method as returning a value of a given type, then the method must actually return a value of that type. In fact, you have to be sure that on any given execution path, it returns a value of that type. The following is wrong, for example, because there's an execution path on which the method fails to return a value of the declared type.
public static void boolean foo(boolean bar) {
if (bar) return bar;
}
What happens if bar is false? The method fails to return any value. That will give you the error you're seeing.
No 101 TA's at Stacks tonight....
User 489 said: Update on the TA's at Stacks.
I'v been here since 17:55 and have only seen TA's for 201 and 126. No one here has seen any TA's for 101.
I'm giving up.............. Mabe some one can help Tuseday....
User 14 said: TA Office hours for cs101 are Sunday-Tuesday from 6-10 in the stacks. These office hours are made available on the main class page. There are no cs101 TA office hours on Thursdays.
Capitalization in Groupwork #17
User 380 said: Should we discriminate between capital and lowercase letters in this program (i.e. if you search for the char 't' and there is a 'T', should the count include this or no)?
Professor Humphreys said: Just search for the provided character. 't' and 'T' are not the same.
Group Project 3 errors
User 323 said: For the first few programs that I tried for Group Project 3, I get the following errors that extends to more than a 100 lines.
ERROR! COMPILATION FAILED! Compiler error messages below:
identity.java:1: class, interface, or enum expected
{\rtf1\ansi\ansicpg1252\cocoartf949
and
identity.java:14: not a statement
\cf2 int\cf0 a = Integer.parseInt(args[0]);\
^
I'm not sure why I'm getting those errors. Could you help me so I can fix them?
Professor Humphreys said: looks to me like you accidentally saved your java files as "rich text" format. Make sure your files are plain text (e. g. Edit them in eclipse)
Group Project 3 errors (contd)
User 323 said: I checked that but it seems like the file that I submitted is a plain text format. I changed the names to programname.java, and I also checked its property.
One thing that I've noticed is that all of my programs for Group Project 3 gives me an exclamation mark (not an error) and a yellow wavy line under for a particular line, which is the second line where you declare your function. (it's the portion that is underlined)
public static
int boo(int a) {
When I click on the exclamation mark, it gives me the option of 1. Change modifiers to final where possible & 2. Change to Constructor.
Professor Humphreys said: *I* checked your files -- they are RTF, not Java. Please use Eclipse to edit your files, and submit only plain text.
Recursions
User 166 said:
I was wondering how recursions are read. Like for program 2.3.4 (Recursive Graphics), draw is called upon 4 times within the function. So when draw is called the first time does it goes back to the top and restarts the draw(. . .) function, or does it read the rest of the draws and then restarts the function?
public static void draw( . . .)
{
if (base case) return; // Sullivan added this line to the original message
. . .
draw(. . .) --> like does this goes back to the draw function
draw(. . .)
draw(. . .)
draw(. . .) --> or the the rest of the draws get read before it goes back to the function?
}
(Edited by Kevin Sullivan - original submission Saturday, 16 February 2008, 03:02 AM)
Professor Sullivan said: Lynna,
Great question. Let's call the occurrences of draw
top, call1, call2, call3 and
call4. You start off by calling
top. Let's call this the
outer call to top.
This outer call to
top then either returns immediately (in the base case) or goes on to
call1, a
recursive (nested) call to
top. Suppose that the outer call is not a base case, and therefore does not return immediately. Control flows on to the recursive
call1. Top calls itself. Control is now in an
inner (recursive, nested) invocation of
top. This
recursive call now
either returns (in the base case) or it goes on to
call1 (again), which would be another, more deeply nested, recursive call. Suppose that the base case occurs. The inner call to
top returns. Where did that call come from? It came from
call1 in the outer invocation of top. This
call1 call is completed, and so control in the outer invocation of
top now passes on to
call2, and the recursive process starts all over again. Once all the nested invocations that result from
call2 have completed, control passes to
call3, then to
call4, and then finally the outer invocation of top is done. Of course, that outer call could actually have been nested inside a surrounding recursive call! Eventually, though, after getting wound up and unwinding and getting wound up again and unwinding again, etc., etc., the recursion does terminate, with the job done.
A really good way to see how this works is to run a recursive program several times in the
debugger: the first time with the base case, the second time on a problem one step away from the base case, the third time two steps away.
KS
Standard In- reading chars
User 200 said: After working on the nchar part of the groupwork, I tried testing it by using StdIn to read one String and one char as parameters. However, the program read both input values as Strings, and even though I used StdIn readChar on the second parameter, I still had to use another function to convert that value into a char. Is there a problem with the readChar function, or is there a certain way I have to input the char when I run the program?
User 14 said: It looks like StdIn.readChar will try to read in spaces and new line characters. If you want to read in the next non-blank character, you'll have to use something like StdIn.readString().charAt(0). That will read in the next string and parse the first character into a char.
conversion from int to string
User 323 said: how do you convert a int type array into a string type array?
and another related question:
how do you convert an individual element of an int type array into a string?
Lesley said: 1. similar process to #490 aka you need to do it element by element, there's no magic code you should use to convert a whole array at once. Also keep in mind the easiest way to convert an int into a string (see #2 below).
2. strarray[i] = intarray[i] + "";
Referring to the last character in an string
User 323 said: if you have a string of unknown length and you want to refer to the last character of that string, how would you do that?
Lesley said: There is a function charAt() for a String. charAt(0) returns the character at position "0" (if you took the String and made in an array of characters, the 0th element) - for instance
String s = "Test";
System.out.println(s.charAt(0) + "," + s.charAt(1)); // This prints "T,e"
There is also a function s.length(), see if you can figure out how to correctly use these two functions together. Try doing things like
- s.charAt(s.length() + 1)
- s.charAt(s.length() - 1)
- s.charAt(s.length())
and see which ones throw exceptions and which one does what you want.
Groupwork #7
User 124 said: Is there some sort of method/formula to find the greatest common divisor between two integers?
Lesley said: http://en.wikipedia.org/wiki/Greatest_common_divisor#Calculating_the_gcd
There are three different ways I can think to implement it off the top of my head (there are plenty more, I'm sure): the euclidean algorithm (easily done with recursion), a loop where it tests if every number between the minimum of a,b and 1 (in that order) divides a and b (stops upon finding one), and finding the prime power factorization of a and b and then multiplying together common terms. I'm thinking that 3rd one is a bit much though and that one of the first two options would be a better solution to try and implement, but if you are bored and want a challenge...
nchar(#17) problem
User 270 said: I have been thinking about this problem for really long time and still can't figure out a way to attack this problem. I tried to go stacks today to ask TA for help, but i didn't see any TA there. Only operation we can perform on String is concatenate, and we can't perform any operation on char type. Also, we can't even convert them from one to another. After thinking for really long time, I wonder if anyone can give me a clue on how to attack this problem. Thanks.
Lesley said: I was there. There is a list up by the ITC desk which people signed their names on to get help since I was the only one here. This is the procedure for most nights actually.
The key to nchar is probably the function chatAt. I have already posted how this function is used in a previous thread tonight. Think about this process:
How do we know how many 'L''s there are in the string HELLO?
H - not an L
E - not an L
L - that's 1... We had none, we increment by 1
L - 2; we had one, now we have one more, we increment by 1
O - not an L
So after looping through the string, we arrive at the conclusion that there are 2 Ls. See if you can figure out how to make this into a program.
Unsubmitting Group Work
User 179 said: Just curious as to where the "Un-submit" option on the groupwork went.
Professor Humphreys said: The "unsubmit" button was never needed and only caused confusion.
Just submit the work again, it will overwrite the old one.
what is the difference?
User 49 said: what is the difference between carriage return and line feed?
Also, what is the difference between Stdout.print(xxx);
Stdout.println();
and just Stdout.println(xxxx)
thanks
Professor Sullivan said: Carriage return and newline are actually separate characters. New line advances the cursor down the screen one line. Carriage return moves the cursor back to the beginning of the line. When we say "start a new line" that translates into "print a carriage return and a line feed." StdOut.print(xxx) prints xxx without a carriage return or line feed at the end. StdOut.println(xxx) prints xxx with a carriage return and line feed at the end. StdOut.println() prints just a carriage return and line feed.
KS
Using Color
User 166 said: If we wanted to use color in our Art.java program what function would that be? Cause I've tried using StdDraw.setPenColor(CYAN) or something and CYAN doesn't work, but if I take it out it defaults to black. And how would I draw filled shapes with different colors (like StdDraw.filledCircle(...) is a black circle).
Lesley said: StdDraw.setPenColor(StdDraw.CYAN) will work.
Similarly use StdDraw.ANY_STDDRAW_COLOR_CONSTANT_HERE inside any of the functions that take a Color as a parameter.
If you wanna get really spiffy you can do something like this:
import java.awt.Color;
public class Art {
public static void main(String[] args) {
Color mycolor = new Color(120, 92, 133);
StdDraw.setPenColor(mycolor);
}
}
These are RGB (woahhh remember THAT assignment??) values (0-255). You can google java.awt.Color for more details (including things like alpha support).
factorial GroupWork 3
User 393 said:
14. Write a function factorial that takes as a parameter a single value n of type int (which your program can assume is non-negative) and that returns a value of type int equal to n!
I am not sure what this question is asking for, the n! is confusing.
Here is what I understood it to mean, but the test failed.
Verifying the existence of a proper factorial function in factorial.class
Found one! Now I'll go ahead and test it.
According to your software, factorial(1) = 1
According to your software, factorial(5) = 5
But that is not correct.
According to your software, factorial(8) = 8
But that is not correct.
According to your software, factorial(3) = 3
But that is not correct.
According to your software, factorial(10) = 10
But that is not correct.
TEST FAILED: Factorial didn't seem to work. Please see the above messages.
Professor Humphreys said: This will help:
http://en.wikipedia.org/wiki/Factorial
Parameters for sierpinski
User 200 said: I was wondering how it would be possible to get the recursion working for sierpinski by only taking one parameter. I looked at the help page and got it to the point where it works by taking 4 parameters (n, x, y, and size), similar to H-tree, but that seems like the only feasible way to do this.
By only taking n as a parameter, that means that x, y and size have to be functions of n. However, since n could start at any number, yet the initial point and size have to start at the same values no matter what, there's no easy way to do that. Instead, it would make sense to have n start at one, make the other variables functions of n, and count up n to the desired degree of depth, but since we have to recursively call this function that supposedly takes only one parameter, there seems to be no efficient way to keep track of such a counter.
Would we be allowed to write one function that takes n as a parameter, but then recursively call another function that takes 4 variables n, x, y and size as parameters? I keep trying to come up with other ideas, but this seems like the only plausible solution, given what we've learned so far.
Professor Humphreys said: The largest triangle is supposed to be roughly centered and take up the entire window.
That *does* make x, y, and size functions of n, in some sense.
Your recursive function itself should take four parameters.
Your PROGRAM should only take one, on the command line.
Strict comparison in totient
User 449 said: Hey,
When my group ran the totient problem for the first time, it worked except for the case where our program gave:
totient(1) = 0
where the correct answer was:
totient(1) = 1
The program specification is: ...
returns the number of integers less than n that are relatively prime to n. If this comparison is strict, then there are no integers less than 1 relatively prime to it -- however, if integers can be less than
or equal to n, this includes 1 in the set, which is relatively prime to itself. I didn't notice any other posts about this -- did I misinterpret something?
-Joel
Professor Humphreys said: Excellent point. The spec is wrong. It should say "less than or equal to". I will fix this.
Appointment with TA
User 71 said:
|
I need to summit a regrade request this week, so I will appreciate if any of you would have time available tomorrow after noon after 4, or Friday after 3, or at weekends. Thanks a lot.
Jun
|
Lesley said: There are office hours Sun, Mon, Tues. Just bring it by then and it will get taken care of.
Office hour and a maybe not simple question
User 71 said: 1. I'm sorry but I forgot the specific office hours times, and I can't find them anywhere, so could anyone tell me when they are, thanks a lot.
2. I wrote a simple program to randomly pop up a picture of a building to help me prepare for my history exam, but is there a feasible(I mean feasible for somebody like me..) way for me to change the program to an ".exe" or anything like that(or Java runtime or whatever?), so I don't have to use cmd or the Eclipse to run it every time, thank you very much.
Even it's hard, I would love to know if it won't take you too much time to explain it here.
Thank you very much
User 167 said: Office hours: $@RESOURCEVIEWBYID*68@$
This is on the sidebar from the main moodle page (labeled "TA Office Hours").
As for executables, you probably don't want to make your code a .exe. Remember that Java runs inside an interpreter - a standalone .exe would need to contain the entire interpreter to run.
However, you can package your code into an executable .jar file, and I believe you can do this through eclipse.
When trying to figure out how to do something like this, google is an invaluable resource. Here are a few sites I found that might be useful (I googled "executable jar eclipse") :
http://www.cs.uta.fi/pgui/2005/local-uta/tutorials.html
Discusses how to use Eclipse to build Java Applets and executable Jars.
http://java.sun.com/docs/books/tutorial/deployment/jar/
Describes how to build and manipulate jars directly, without needing Eclipse
Professor Sullivan said: Thanks, Dan, that's exactly right: Export as executable jar. --KS
Canvas Color
User 236 said: Is there a way to set the canvas (what we draw on) color for out stddraw window with out declaring a JFrame and such? I want to have a background color that will make the colors of my drawn recursions more visible.
Thank You.
Professor Humphreys said: The method you want is:
public static void clear(Color color)
So StdDraw.clear( StdDraw.BLACK );
will clear the screen to, well, black.
Individual Assignment 3 Question
User 270 said: I wonder if I can use two recursion functions in the part 2 of the Individual Assignment #3. The second recursion function is very simple and has a fixed number of n. I just added it to make it looks more creative. I wonder is that ok.
Professor Humphreys said: absolutely!
For fun, see if you can do something that is *mutually* recursive -- function A calls function B, and function B calls function A.
Canvas scale problems for individual assignment
User 188 said: Hi:
I'm working on my individual assignment, but for some reason when I call the triangle function the triangle doesn't appear on the screen unless I set the X and Y scales. I know we're not supposed to set the size of the canvas, so what's going wrong? Is there any way I can force it to appear in the centre of the canvas?
Thanks,
Becca
Professor Sullivan said: If you don't explicitly set the X and Y scales, then they are (by default) 0.0 to 1.0
Groupwork 3 Robograde
User 71 said: It said there is a compiling problem with my #21, which I didn't encounter when running it on my laptop, and it seemed that what it is looking for ValidateCreditCardNumber, not what is asked in the assignment "Valid"CreditCardNumber.
my error messgae: class validCreditCardNumber is public, should be declared in a file named validCreditCardNumber.java
User 167 said: Ok, here's what's going on behind the scenes:
When you start a file with something like
"public class validCreditCardNumber"
you're creating a new class, and all the functions you're writing are actually static members of that class. You'll learn a lot more about what that means later on in the course, when we get to classes, but for the moment just remember that all of the functions you define in that file are part of the class, and the name of the class is "validCreditCardNumber".
The thing is, Java requires that every public class (again, you'll understand the term "public" better once we've gone over classes) be defined in its own file, and the file needs to have the same name as the class.
Thus, if your file starts with "public class validCreditCardNumber", then the file MUST be named "validCreditCardNumber.java". In your case, it isn't - it's named "ValidateCreditCardNumber.java". Since they don't match, you should expect to get exactly the error above:
class validCreditCardNumber is public, should be declared in a file named validCreditCardNumber.java
There are two ways to fix this error. One is to rename the file to validCreditCardNumber.java, so that the filename matches the class name.
The other is to rename the class to ValidateCreditCardNumber, by changing the appropriate line to read
"public class ValidateCreditCardNumber"
Of course, one of these changes will let you submit the file through Robograde, and one of them won't. In this case the confusion appears to be our fault - the assignment asks you to use a class named after the validCreditCardNumber function, while Robograde expects you to use the name "ValidateCreditCardNumber". We'll fix this shortly and announce which one we actually want, but for now you can use the name ValidateCreditCardNumber - this will let you get feedback from Robograde immediately, and we'll let you know when we get this set what name you should ultimately use.
By the way, a useful Eclipse shortcut: If you want to change a filename AND the name of the class in it at the same time, right-click on the file in Eclipse, and select "Refactor -> Rename" from the menu. This will even automatically change the name if you used it in other java files (again, you'll understand why you'd want to use the name in other files once we do more with classes).
Professor Humphreys said: The submission system will ONLY accept files named "validateCreditCardNumber.java", so the function should have that name.
From the beginning of the assignment:
In each instance, you should include your function inside a class of the same name as the function.
Contrary to Dan's post, none of the functions, class names, or file names should be capitalized.
Assignment 3 - Colors
User 177 said: I'm working on Art.java and I think it's kind of boring now. I was wondering if there is a way to get java to make different color circles.
Thanks - Macie
Lesley said: #550
uninverted triangle outline on assignment page Assign 3
User 305 said: The assignment says "First, make sure that your program draws a single black triangle when
N is set to 1." but i see an outline of an uninverted triangle on the assignment page, do we need to include that outline triangle in our assignment and then draw the solid inverted black ones inside it?
Lesley said: The grey outline triangle was optional last semester. I'm assuming that still holds.
Professor Sullivan said: Folks, I'll step in on this one: No surrounding triangle, please. Just follow the written instructions.
Exam 1
User 305 said: I might have missed the announcement, but when will we get our Exam1 back in 101E?
Professor Humphreys said: tomorrow
Regrades
User 305 said: Regrades are supposed to be written, can they be typed and turned in, in person, or actually hand written?
Professor Humphreys said: Typing is okay. Just so long as there is a paper trail.
Art.java
User 86 said: I added a picture to my Art.java design. Is this going to affect the grading process since there is no way to attach the .jpg file? Thanks!
Professor Humphreys said: Put the picture on the web somewhere, and put a comment at the top of Art.java indicating where we can download the picture.
Sierpinski Triangle
User 166 said: 1. So we can't just draw the Sierpinki Triangle with an imput of 4 parameters? (n, x, y, size), it has to be just 1 parameter?
2. And when writing Art.java does that have the same idea (an imput of just 1 parameter)?
3. And when you grade the program, will the main function be tested too (for both programs)?
Lesley said: Your API will look like this:
class: Sierpinski
- triangle(x, y, size) //draws a triangle
- sierpinski(n, x, y, size) //recursive caller of triangle
- main(args) // N is a command line argument; calls sierpinski
All of those things need to be present (you need a "main"). I'm assuming your Art.java will look very similar in structure. If you look at HTree, it has three methods (drawH, draw, and main) which are comparable to the ones outlined above.
Professor Sullivan said: Lesley is right. If you're lost on Sierpinski, go back and study HTree (which we went over in class in great detail). We're confident that if you download and run and study HTree, and then think about the Sierpinski requirements, you will see that the same basic scheme works for both programs.
Art.java
User 166 said: I didn't read the assignment correctly so I created a sierpinksi function that takes in 4 parameters and calls itself 3 times (n, x, y, size). So I don't have a triangle function, but it still works. But I can't do that right? I have to create the triangle function to be graded and I have to make Sierpinski function take only 1 parameter, but you don't need a triangle function, you could do it in 1 function. Also is that true for the Art.java assignment? I've created a bunch of functions that doens't call on another function, it just calls upon itself a couple of times. So do I need to call on another function or do I not have to? Or does Art.java not matter?
Does that mean the x, y, and size is up to our choosing? (cause that makes life a lot easier).
And then we have to set the scale to fit our triangle?
Professor Sullivan said: Lynna,
> I don't have a triangle function, but it still works
You probably have code that draws a filled triangle embedded in the sierpinski function . All you have to do is to restructure your program, putting that code into a separate function. You should do this in order to get full credit. Prof. H posted a message a day or two ago restating precisely the functions that your program must include.
I don't yet fully understand your other questions.
KS
question
User 440 said: Mr. Sullivan
I did my sierpinski triangle starting from the middle of the first triangle. It made it more difficult but it works the same way....Is that ok?
Color
User 177 said: Where can I get java.awt.Color?
User 14 said: add the line:
import java.awt.Color;
to the top of your file.
Outline of Triangle
User 218 said: The following is on the assignment directions:
"Also, when writing your program, exercise good design: include a (non-recursive) function
triangle() that draws an equilateral triangle of a specified size at a specified location."
However, on a previous forum topic Professor Sullivan said that you don't need to include it.....so which is it?
Professor Humphreys said: Those statements are not contradictory!
The triangle people were asking about was just the faint outline around everything else. *THAT* is not necessary.
Edge lengths of triangle
User 347 said: Is the size of the overall triangle in Sierpinski.java supposed to be a function of n or is it supposed to have edge lengths of 1 as suggested on the help page?
Professor Humphreys said: Do whatever you need to do so that the overall triangle fills up most of the window.
Art.java
User 220 said: I made an Art.java program that looks a lot cooler when N is greater than 7. May we indicate somewhere that we would like this done and where, if we can?
Professor Humphreys said: Probably in the readme.
Alternately, just have your program print an informative message when it starts:
(in main somewhere)
System.out.println( "PLEASE RUN THIS WITH AN ARGUMENT OF 7 OR MORE FOR MAXIMUM EFFECT" );
How many methods?
User 347 said: How many methods should our final Sierpinski.java have?
Should it be:
Class Sierpinski
triangle
Sierpinski
main
or should it just be:
Class Sierpinski
Sierpinski
main
or does it matter?
Professor Humphreys said: The assignment says to write a triangle function
Professor Humphreys said: The assignment says to write a triangle function
Random colours
User 188 said: Is there any way to alternate colours or randomly select colours as part of the recursion? My Art.java looks rather dull in black and white outlines, but if I do filled all in one colour you can't see anything.
I've tried assigning different StdDraw.COLOUR values into an array, then geenrating random numbers to get them out, but that doesn't work.
Anyone know how to do this?
Thanks,
Becca
Professor Sullivan said: For each of the red, green and blue channels you might try "some function of n" mod 256. The mod 256 guarantees that the result is between 0 and 255.
question
User 440 said: I did my program differently than everyone else. Instead of starting at (.5, 0) I started at the middle of the triangle......this made it way more difficult but it works the right way.....is this ok?
Professor Humphreys said: As long as you have a recursive function and a "triangle" function, you're fine.
What does this mean?
User 198 said: What does it mean whenever Eclipse says "This method has a constructor name." with the yellow squiggly line on the method header? hm.
Lesley said: public class MyClass {
public static void MyClass() {
}
}
will give this "error." When you learn about Object Oriented programming later in the course, you'll learn what a constructor is and why it's giving this error. For now, it's not something you need to worry about, but you can discern that it happens when a class has a method with its same name (case sensitive).
art.java
User 266 said: Is there anyway we know if our Art.java is "creative" enough???
Professor Sullivan said: Do your best in the available time to create something interesting, moving, colorful, fun, funny, deep, artsy, whimsical, inspired, aesthetic, or whatever. What more can you do? Oh, and have fun with it! --KS
art.java additions
User 211 said: If we want to add music to our art.java program to accompany our creative recursive program how can we upload the music file?
Professor Humphreys said: I've added an optional upload.
zip
User 266 said: how do you make a zip file to submit the artwork with our Art.java program
Lesley said: Download some shareware called Winzip and then you can right click files to zip them. Dunno if there's a built in function in Windows. No clue about Macs.
#21 -vCCN array length
User 531 said: are we to assume, from the example, that the input data will always be 9 digits long? If not, are we given an input value with which to initialize the aray?
Lesley said: Well you're given an array as your parameter, so you can just use array.length like you've been using all along. Though I think Robograde only tests against 9 digit inputs.
StdDraw.setCanvasSize
User 326 said: I know the help for the assingment says not to use set canvas size, but are we allowed to use StdDraw.setXscale and StdDraw.setYscale? If I don't, I can't get my drawings to show up where they are supposed to.
Lesley said: Those functions are all equivalent. You should be able to write a program which is not dependant upon using any of them.
If you hadn't waited until the last minute, I would have suggested going to office hours so a TA could help you make your code work without them.
I don't know if points are being taken off for using these functions. But your sierpinski and triangle functions shouldn't be dependant upon window size at ALL so you should just be able to modify the original size and x, y you pass to sierpinski in your main routine to make it draw correctly.
Professor Sullivan said: The default X and Y scales are 0.0 to 1.0. The coordinates of your points will (should) all be in this square.
midpoint of a line
User 221 said: is there any java language in the math library that calculates the midpoint of a line when given two endpoints? i was thinking of using this in my sierpinski triangle code...
Professor Sullivan said: You can just calculate it yourself.
If the coordinates of the two end-points are (x0,y0) and (x1,y1), then what are the coordinates of the mid-point? What is the x coordinate of the mid-point? What is the y coordinate? How do you calculate the number halfway between two given numbers?
name of function for Art.java
User 323 said: what should the name of the function be for Art.java?
Lesley said: Whatever you want it to be!
Professor Humphreys said: public static void whatever_you_want_it_to_be( ... )
uploading Art_extra.zip
User 376 said: When I try to upload my Art_extra.zip it only says "Preparing to upload Art_extra.zip..." and then has the continue button. It never says upload complete. I don't know if it is my computer or what, but it never uploads.
Professor Humphreys said: Not sure why that would be happening, but your file has uploaded successfully.
Saving StdDraw as other file type
User 380 said: When I save my StdDraw images as a jpeg, they always come out blurry and nowhere near as crisp as in the stddraw window. Is there a way to save these files in another format, like a bmp?
Lesley said: You can save as .png which might make it clearer.
You can also press the "print screen" button on your keyboard (up near the top usually) and then open a program like Paint and press ctrl+v aka paste and magically your screen will come up. To get just the current window press alt+prntscrn. Then you can save as .bmp
Art.java
User 31 said: Can we implement iterations within our functions to create fractals?
I guess the crux of my question lies in how much of the program must be done in recursion.
Professor Sullivan said: You can certainly include iteration in addition to recursion. But you have to use recursion. --KS
jpg
User 120 said: Did we have to have the 2 additional lines that turned our art into a jpg file when we submitted our art to moodle? I submitted my project earlier this week and didn't have the 2 save lines in it.
Professor Sullivan said: NO
redirect standard input from file to terminal
User 305 said: Is there any way to redirect standard input from file to terminal within the same program? That is, get data from a file then make it interactive with the terminal?
Professor Humphreys said: Not easily. If you want to both read from a file *and* the user, you're better off just using the "In" class (see the book website) and explicitly opening / reading from the file in your program.
You can just pass the name of the file to read as a command line argument.
Eclipse
User 166 said: Is there a reason why Eclipse won't open up any of my programs anymore? Like the src file no longer exists under the java project, but if I open up my J drive, it's all there and I can open up the program in notepad or something. Now all of my projects have that red error x on the project like something's wrong, but the program runs fine out of the command prompt.
User 167 said: That probably means Eclipse is confused about your workspace. This usually means one of three things:
1) Eclipse just got confused. Usually this means something interrupted it while it was loading, with the result that Eclipse has forgotten about some of your folders. To fix this, select all your projects, right-click on one of them, and select 'Refresh'.
2) You changed your workspace. In this case Eclipse will show whatever's in the new workspace. To fix this, go to 'File->Choose Workspace' and reselect your usual workspace.
3) The .metadata folder, or one of the .project files, was moved or corrupted. This is extra information that Eclipse stores in the workspace to help it keep track of all the extra information it has about your projects. To fix this, reimport - In the list of files on the right (where it normally lists your projects, java files, etc.) right-click somewhere empty. In the resulting menu, select "Import..." IN that dialog, expand "General" to find "Existing projects into workspace". Then select your workspace as the root directory - it should give you a list of projects that are in the workspace folder but not registered as part of the Eclipse workspage. Check all of them and hit "import" to load them.
If none of these work, come talk to a TA during office hours.
mergeSort merge function
User 380 said: When I looked at the merge function in the mergeSort groupwork program, it says it takes only one array as a paramter, but if we are merging two arrays together, shouldn't it take 2?
Professor Sullivan said: MergeSort sorts an array of numbers. The function takes one array. Read on: The way that it does is by splitting the given array into two sub-arrays, sorting each of them, and then merging the two sorted halves.
Lesley said: It's not merging as in array "a" has 5 elements and array "b" has 2 and array "c" is array a's 5 elements followed by array b's 2...
It's merging as in the decks of cards analogy given in the file. And really instead of two piles, it is one pile where it is sorted until a midpoint (ie. 1, 7, 2, 4, 9, 6, 8, 22, 18, 3; 9/6 is the mid point and on either side things are sorted between a lower and upper bound) and merge() "merges" these "two (sorted) arrays" together, from lower to upper (around that midpoint). (So after merge worked on that PART it would go 1, 7, 2, 4, 6, 8, 9, 22, 18, 3)
RE: mergeSort merge function
User 380 said: right, i understand the part about breaking the array into halves, until there are just a bunch of 1 number arrays. but then we are supposed to call the merge function to merge the left and right halves. Is this still supposed to be done taking just one array as a paramter?
Lesley said: I replied to your original post. I hope it clarified.
bubblsort
User 71 said: it says: "/*
* Return the value of the largest element in the "suffix" of" for the indexOfSmallestElementInSuffix function, should that be "return the value of the smallest"?
and it seems that (I might be wrong because I just take a brief look at it) it dosen't fulfil its goal(which it should, because the bublesort does anything except sorting the numbers)
Professor Sullivan said: Many teachers teach that code should contain extensive explanatory comments. A problem with this strategy is that comments can be inconsistent with code. You see that here. What I'm trying to say is that
I screwed up when I wrote the comment. Yes, it should say "smallest"! Thanks for pointing out the error. Just go ahead and write the code we've asked you to write. The incorrect comment is confusing, but if you ignore it, you'll be fine.
MergeSort
User 71 said: I now came up with an algorithm that only works if you call the MergeSort passing it the whole array, so I wonder if we have to create an algorithm that works for any kind of calling (which seems not required by the main program)?
Thank you
Lesley said: "passing it the whole array" - That's the correct implementation. :)
Groupwork4
User 71 said: I'm sorry about this, but there seems to be a lot of inconsistency in the comments among which I don't know which specific one to ignore. Are the comments basically the requirement for not only what the functions do but also how they do them , or should I just look at the assignment page and ignore all the comments and write the program in my own way?
One more question, could I create my own sub-functions(I mean functions that would be called by the functions that are already required)?
Thank you very much.
Professor Humphreys said: You can, of course, add your own functions if you think they are helpful.
It's important that you implement the algorithm as specified (on the assignment page); our grading scripts will test that the array is sorted *and* that you used the right number of comparisons.
MergeSort Again
User 380 said: Since the merge function inside the mergeSort class returns void, could we just eliminate the merge function and include the code that would go in that within the mergeSort function?
Professor Humphreys said: You can always write any program in just one function, but why would you want to do that? Good abstractions and functional decomposition are what differentiate well-written working programs from poorly-written working programs.
Professor Sullivan said: Right. The program would still work, but it wouldn't be as easily understood by people who read the code. There are, in general, many different programs that compute the same function, but they're not all equally good with respect to a range of important factors, including ease of understanding and ease of change.
changing output of merge
User 380 said: Can we change the output of merge from void to something else then, such as double[]?
Professor Sullivan said: In general, yes; for this particular exercise, no. --KS
auxilliary arrays
User 380 said: sorry to keep bombarding you with questions, but is there a way to set up an auxilliary array that can be referred two in two separate methods without having to return the array type? i.e. i want mergesort and merge to be able to reference the same array.
Professor Sullivan said: If you declare a variable outside of several functions in a class, then they can all access it. Such a variable is called a "global" variable. Using global variables is a practice that is often best avoided, but sometimes it's just what's needed.
Sorry, but Merge this time...
User 71 said: I might be an idiot, but have we learned how to use private static method? And since all functions seem to be set to static method, I guess we don't have to worry about the instance variables?
Professor Sullivan said: Private simply means "cannot be called by a method in another class." The "API" is the set of *public* methods that a class defines. Additional private methods are "for internal use only."
RoboGrade for Pascal
User 54 said: For the group work will we be able to RoboGrade for the Pascal file? I uploaded my file and there was no Robo grading option for it.
Professor Sullivan said: It will appear "soon" -- sorry for the delay.
RoboGrade for MergeSort, Count??????
User 305 said: Please clarity the RoboGrade parameters for MergeSort, my program puts the elements in order but it doesn't match RoboGrade's count, does my program have to match the count exactly to get all the points? Not clear on what needs to be done to get all the points for this part of the assignment.
Professor Humphreys said: yes, they must match. Please re-read the robograde output.
can we change the function to non-static?
User 71 said: otherwise even if I create varibles outside methods, I couldnt find a way to let Mergesort and merge refer to the same array without any return, because for recurssion I have to constantly change the length of the array
Lesley said: Think about it this way instead:
You have your array that is being passed, called "arr" and as you saw in one of the groupworks, you can modify this array without returning it, ie saying inside the method that arr[0]=27 without returning arr will still change the value of arr[0] to 27 once the function completes. IE:
public static void whatever(double[] myarr) {
myarr[0] = 27.0;
}
public static void main(String[] args) {
double[] arr = new double[5];
System.out.println(arr[0]); //prints 0.0
whatever(arr);
System.out.println(arr[0]); // prints 27.0
}
You shouldn't have to have any variables outside of your methods. You only need those temporary array(s) inside the merge function, right? (you only need one to my knowledge) So you can just declare them there (anew) every time you need them.
(Edited by Daniel Lepage - original submission Sunday, 16 March 2008, 06:04 PM)
further question for Non-static..
User 71 said: then if I created temp varibale inside mergesort, the only way I can make merge() refer to it is to read it as parameter(since both of the two methods have no returns), but since merge can only read one array, it make me confused how to use merge() combine two arrays with only one array as parameter and without reading any public arrays.
Am I getting there? or am I totally in the wrong way?
thank you.
Lesley said: you'd want it to be inside merge() not mergeSort() - mergeSort is only 5 lines.
an outline of my algorithm?
User 71 said: btw, an outline of my algorithm:
recursive mergesort, each call two mergsort to sort left and right half, and using merge to combine two, untill the length of sub-arrays become one. For doing that, two mergesort will call itself twice with different parameters and using merge to combine them. And to achieve that, I have to make merge refer to the sub-arrays sorted by the result of two mergesort just called, but since they are in the same function, and merge can only read one array, and both of the two methods are void method, I have to create two non-static arrays in the class to be constantly changed and refered to in the recurssion.
Am I getting there? or am I totally in the wrong way?
Thank you again for being patient.
Lesley said: There aren't actually two subarrays that need to be declared - they're just part of the big array as referenced by the indices lower and upper. Please see
#670
Professor Sullivan said: Lesley's right. What you pass to merge is a big *sub* array each half of which is sorted. When merge completes that big sub-array is completely sorted, in that the two halves have been merged. According to our instructions, you may use a temporary array the size of the big subarray into which you insert elements in sorted order. You can then copy that sorted array back into the subarray of the original array.
Thanks so much to the previosu reply
User 71 said: I think I got it. The relationship of the two counts looks perfect and reasonable, though it seems that my captain doesnt want a group meet.
Just wanna say thanks.
How could I set an element of an array to be void
User 71 said: and how could I refer to that as an expression of boolean?(say if I didn't set a element of an array to anything, I still don't know how to get a true or false out of that fact with boolean expressions)
Thank you so much.
Professor Sullivan said: If the elements of array A are objects of a reference type, then you can do this:
A[i] = null;
if (A[i] == null) { /* do something */ }
DataCollection
User 77 said: Ok so I've got a working MergeSort program, and I was wondering about using DataCollection.incrementCount(). If we compare values using an if... else statement, should we have DataCollection.incrementCount under the if AND the else, or should we only count it once?
Additionally, I've tried running the AlgorithmComplexity.java file with my working MergeSort program, and it gives me error messages about my MergeSort program. Is this a problem, since the MergeSort Program sorts properly and follows the correct technique?
Professor Sullivan said: Just be sure that you count exactly one comparison each time you do a comparison. If you do an if...else, you might just put a call to increment() immediately before or after.
What error message?
Re: DataCollection
User 77 said: the error message is ArrayIndexOutOfBoundsException.
It doesn't seem to make sense because it seems like I would get the same error if I just ran MergeSort.java on its own, but I don't.
Professor Humphreys said: Sounds like it's time to use the debugger!
Professor Sullivan said: Yup! There's clearly a bug in the code.
Professor Sullivan said: Be sure to call the DataCollection initialization routine properly, otherwise the array for holding values won't be set up properly. That is one thing that could easily result in the error you're seeing (although it's not the only problem that could be causing the error you're getting).
Edit Distance Submission
User 222 said: I went to submit my EditDistance.java into the uploader on the assignment page, but the file requested is EditDistance.Java (captial J in Java). I had to rename my program so the .java was a .Java for it to accept it. You might want to change that for the convenience of everyone else. Also, does my changing of the .java to .Java mess with my program at all? Thanks
Professor Humphreys said: whoopsie! Fixing now.
lab quiz 4
User 77 said: For the averagearray function portion of the quiz, it says to initialize the ith elements of the first row and first column to equal i, however the image provided shows that they are instead initialized to i+1. Which is correct?
Professor Humphreys said: the picture is correct, and the text is meant to start counting at 1, not zero.
Sorry for the confusion, I wish everyone started counting from the same base :(
Professor Sullivan said: I had already corrected the assignment online.
Quiz 4 Grading
User 187 said: Will the Robograde feature be available for quiz 4?
Quiz 4; problem 1
User 437 said:
This question is regarding problem 1 on quiz 4.
How can I print each element of the double array as fractions, like the instruction image, instead of decimals?
Lesley said: public static double[][] averagearray(int n)
Since a fraction is not a double, you don't have to worry about your program doing this. But you can google for some Fraction classes or attempt to write your own should you want to overachieve.
Professor Sullivan said: Right: you don't have to do this. Just use double, and make sure the values are equivalent to those shown in the figure. But if you have time and inclination it would be worth following Lesley's suggestion: write your own Fraction class. A fraction has a numerator and a denominator, each an integer. You should be able to take it from there!
Drawing a rectangle??
User 531 said: Im trying to draw a rectangle for a program I am writing, but none of the StdDraw functions seem to work for me. I have the coordinates of the 4 corners of the rectangles, but when I use StdDraw.FilledPolygon(x[], y[]), it draws little bow-ties instead of rectangles. Is there some other way to draw them??
Lesley said: You have your coordinates out of order in your arrays.
It is going a -> d -> c -> b instead of a -> b -> d -> c
Not able to type in an argument into console window and run program
User 543 said: I'm not able to put in an argument to my console window and get my program to run for some reason.
Under my console window, it says
StdIn[Java Application]C:\Program Files\Java\jre1.6.0_04\bin\javaw.exe
Whenever I hit the play button to run my program, in the console window it says "Type a string:" and then after I put in an argument it says Your string was:
and then says Type an int:
Professor Sullivan said: It sounds like you're inadvertently running the main routine in a class other than the one you mean to run. Be sure the class containing your main routine is selected in Eclipse.
Arithmatic with complex numbers?
User 188 said: I was running through quiz 4 this evening when I realised that I have no idea how to do addition and multiplication with complex numbers. The rest I can play by ear, but what do I do for this? Just add and multiply the real and imaginary components separately, or is there some sort of complex ritual?
Thanks!
Yrs,
Panicking CLAS student
.
Lesley said: http://www.google.com/search?hl=en&q=add+and+multiply+complex+numbers
Individual Assignment Run Time
User 380 said: Is there a way to get the control panel to work with StdOut or a way to use java -Xmx300m EditDistance < input.txt > output.txt in the console in eclipse. Or do I have to go and change all of my StdOuts to System.outs and use the control panel to find the time it takes for the computation?
Lesley said: just for knowledge (since so many people keep asking) running from the command prompt:
j:\cs\editdistance\src\>javac -cp j:\cs\stdlib.jar;. EditDistance.java
j:\cs\editdistance\src\>java -cp j:\cs\stdlib.jar;. -Xmx300m EditDistance < input.txt > output.txt
where your source is in src ALONG with the input.txt file(s)
lastxgap8.txt and lastygap8.txt
User 71 said: My programs ran all very all and got the right answer until I got to these two files, it said array out of bounds, and when I opened them I found that they all just had one string and the only difference between them is that lastxgap8 had an extra "a" at the end.
Is that a problem with my program?
Or is that a prolem with the file?
Thank you so much.
Lesley said: Yeah this is a problem with your program. Logically think through why it is doing that and you will figure out what it is doing wrong. I also think that last semester those files were not tested against your program.
Just ignore the previous post
User 71 said: Now I realize what my problem is, but is there a way to enlarge the memory that will be used when Eclipse run the java, so I will be able to debug with inputs as big as that of the "ecoli3000.txt".
Now it works on that two, but doesn't work on this one.
Thank you.
color transparency.
User 531 said: Say i have a color:
Color sky = new Color(0,0,255);
If i want to make a lighter shade of this color (closer to white), how would I do this? By progressivly adding to the red and green?
Lesley said: There's a difference between transparency and shade. To play around with shade open up something like MSPaint, double click one of those colors at the bottom and then click define custom colors. You can see how changing rgb affects the color.
Should you want TRANSPARENCY, you should use Color sky = new Color(0, 0, 255, 100) or something, play around with that last value (its "alpha" value) - try putting some other object underneath it to see what exactly it is doing.
Quiz 4, AverageArray
User 276 said: Problem 1 for Quiz for has a picture demonstrating what averagearray(5) will look like, with is:
{1.0, 2.0, 3.0, 4.0, 5.0}
{2.0, 2.0, 2.5, 3.25, 4.125}
{3.0, 2.5, 2.5, 2.875, 3.5}
{4.0, 3.25, 2.875, 2.875, 3.1875}
{5.0, 4.125, 3.5, 3.1875, 3.1875}
However, when I run the test script, the robograde is looking for a matrix like this:
{0.0, 1.0, 2.0, 3.0, 4.0}
{1.0, 1.0, 1.5, 2.25, 3.125}
{2.0, 1.5, 1.5, 1.875, 2.5}
{3.0, 2.25, 1.875, 1.875, 2.1875}
{4.0, 3.125, 2.5, 2.1875, 2.1875} This doesn't seem to coincide with the instructions. Maybe the instructions were changed but the program that tests the script was not.
Professor Sullivan said: Oh, man! The instructions are right. The roboscript is stlil wrong. We'll fix it.
ecoli 500000
User 380 said: Is there any way we can actually use the file ecoli500000.txt? When I first tried it, it said it ran out of memory, so i tried to increase the memory to 5000Mb, which was a bad idea in retrospect since I just realized I dont have that much memory, which explains why it says it exceeds the maximum representable size, but when i try 2000Mb or 1500Mb, etc. the command prompt says it could not create the Java Virtual Machine.
Weird!
User 71 said: Before my program won't work with ecoli3000 and 7000, but it runs pretty fast.
Then I changed something that I don't think will really make a different, but it does, only that the program works much slower. And the weird thing happened, I redo the change, the program will now work with ecoli3000 and 7000! But it works slowly as well! What might be a reasonable answer?
I ran the program in Eclipse as well as in cmd, and I am sure I did compile the program in cmd everytime there is a change.
Thank you.
Right Mouse Click
User 380 said: I know the StdDraw.mousePressed method will tell if the left mouse button is pressed, but is there a way to implement certain fucntions when the right mouse button is pressed instead?
Lesley said: Last semester I edited StdDraw for more mouse abilities (they're all deprecated or something) - you'll have to implement your own routine in it for handling right clicks. See
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=571926 (this deals with methods inherited from StdDraw "implementing" MouseListener, something which I do not think is covered in 101).
Professor Sullivan said: Lesley's right: Go read the code in StdDraw.java. Let us know if you can't find it. (It's available on the booksite, and from the
Useful Links page on the class web site. If you're willing to put in the effort, we'll help you to understand the code and how to extend it to do what you need. Doing this sort of thing is one of the things that CS101 is meant to enable you to do!
BubbleSort grading funny?
User 151 said: I, in working with my group have written the necessary code for BubbleSort.java, however when uploading the file to be RoboGraded, it is not working properly. In Eclipse, we added code to the Main function to print out the sorted array, and everything works fine. However, in the RoboGrade, the output looks exactly like the input. I have tried all the inputs from RoboGrade in the Eclipse main routine, and they seem to work. What could be going wrong? We have tried uploading several times, though the same result occurs.
Individual Assignment Output
User 270 said: I not sure what is suppose to be the output for the the example given in the individual assignment. It says it suppose to output the "optimal solution." I m not exactly sure what that is, because the I don't exactly understanding the whole biology thing in the assignment. So, can you give me the output we suppose to get for the example in the individual assingment?
Lesley said: Please see the help page, the section "Input, Output, and Testing"
Professor Humphreys said: I agree with these posts.
There's no way to make progress without understanding the assignment. If you could be more specific about *what* you don't understand, then we can help. Otherwise you will need to go to office hours.
In general it's not possible to complete an assignment without understanding the assignment. The assignment itself requires no knowledge of biology; all the terms and relationships that you need to do the work are defined in the assignment itself.
If you don't understand something, please tell us *what* you don't understand, so we can help you.
Individual Assignment - Problem with Opt Array
User 52 said: When I print out the opt array, I get the answer 7, (and the answer 8 when using text file gene57), but some parts of the array are wrong.
The first two rows of the opt array are correct, as it is with the bottom 2 rows and the last column. But somehow there is a mistake in the middle.
I get this as my result.
7 8 10 12 13 15 16 18 20
6 6 8 10 11 13 14 16 18
4 5 6 8 9 11 12 14 16
6 4 4 6 7 9 11 12 14
7 5 3 4 5 7 9 10 12
9 7 5 3 3 5 7 9 10
8 8 6 4 3 3 5
7 8
10 8 7 5 3 2 3
5 6
12 10 8 6 4
2 1 3 4
14 12 10 8 6 4 2 1 2
16 14 12 10 8 6 4 2 0
the bolded parts are where I think the problem starts. But i don't understand why the first row is correct, if some parts are wrong in the beginning.
Am i just doing the wrong coding?
Lesley said: The formula might just be leading to the first row being correct because of the way incorrect values situate themselves (ie: coincidence). I would suggest coming to office hours for help with debugging what is wrong.
Professor Sullivan said: Lesley's right, but even before coming to office hours you should use the *debugger* to carefully step through and watch what your program is doing. If you haven't been brave enough to use the debugger until now, well, the time is now!
Distance - readme.txt
User 546 said: Hi!
I didn't understand what exactly should be written in the "distance" for each file in readme.txt file. Is it the optimal alignment? or the sum of the penalties?
Thanks a lot!
Lesley said: "The edit-distance is the score of the best possible alignment between the two genetic sequences over all possible alignments"
The edit distance *is* the score of the optimal alignment which *is* the sum of the penalties.
The optimal alignment is an alignment, not a number/distance.
RoboGrade Group Assignment 4 - Sorting
User 151 said: I am not sure, but there could be an issue with the Group Assignment 4 Robograde. My group has submitted the BubbleSort and MergeSort java files, but when we run the RoboGrade routine, the output is totally different from what we get when we run the exact same inputs through Eclipse. What should we do about this?
what does StdIn.readAll().split("\\s+") mean?
User 49 said: In the Program 4.2.4, this is a line String[] a = StdIn.readAll().split("\\s+").
I know StdIn.readAll() means read all the text but what is.split? and what is the String"\\s+"? I did not see it inthe original String"the and was his......him"
Thanks.
Professor Humphreys said: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)
Lesley said: the string inside of split is a regular expression - see http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html#sum
It basically means split on a whitespace character (such as a space, tab, newline...) - split makes an array so in your string
"the and was his.....him" after split the array would be
{"the", "and", "was", "his.....him"}
if you had "the and\nthis is crazy\t woahhh" it would be
{"the", "and", "this", "is", "crazy", "woahhhh"}
eclipse program not working
User 209 said: Every time I start my eclipse program it either doesn't open up the workspace or goes to the workspace and then quits by itself. How do I fix this?
Ignore previous posts about the robograde
User 151 said: I found out what I did wrong. We (by mistake) were uploading the files with blank code, all the while forgetting that we needed to upload the file from the "src" folder, which had the finished file. Sorry for the posts regarding this.
Error in mergeSort
User 347 said: What does the error "Exception in thread "main" java.lang.StackOverflowError" mean? I've never seen this one before and I need to know what it means so I can fix it.
Lesley said: Too much/deep recursion being attempted I think... This has happened when people use the midpoint as a lower bound in mergesort() instead of the midpoint + 1, or otherwise have part of those 5 lines wrong. If that isn't it go by office hours so a TA can look at your code and help you.
Individual Assignment 4 (Std or System)
User 437 said: Should we use "StdOut." function to print or "System.out" for assignment four?
Timing the Edit Distance
User 357 said: I have a mac and am trying to time my Edit Distance assignment, but i cant use terminal because i need to import a java file into my program, which i dont know how to do. Answering one of these questions would be great:
1. can i use eclipse to time the assignment, if so, how do i allocate 300 mb for it to use for running the program?
or
2. how do i make a classpath on a mac so that i can use stdlib.jar because i cannot use the String.StdInreadString() method?
thanks
Lesley said: 1b. #774
dan or greg might be more knowledgable about macs...? i remember the -cp was different on macs instead of ; it was : or something like that (see #719)
Unable to use Windows command line
User 320 said: In the past I've usually used Eclipse to run my programs due to ease of use. Now when I tried using the command line in order to allocate more memory and print to the output.txt file, it won't work because cmd will not recognize the Standard Library files.
I have no idea why this is. Eclipse recognizes them perfectly and I have placed stdlib.jar under Windows environmental variables, but I cannot run programs with Std in the command line.
I can run a .txt file from Eclipse with copy-and-paste, (and my EditDistance.java works as it should) but is there a way to allocate more memory and time from the Eclipse run line?
Professor Sullivan said: You can allocate additional memory to Java (to the "Java Virtual Machine") from
within Eclipse by typing the following arguments in the right window in Eclipse.
Open
Run Dialog the click on
Arguments. You'll see one pane for
program args, which is where you put your commend line arguments. You'll see a second pane for VM args. That's where you want to type the following:
-Xmx1024k
Replace 1024 with a number of kilobytes of memory actually available on your machine. If you have 2GB of RAM, for example, you might use 1500.
KS
Assignment 4-just write a function?
User 515 said: Do we just write a function or write a completed program with a main method? If only write a function, what should the name of the function be? If write a whole program with a main method, do you enter the two strings of genes by command line arguments or by the console? Thank you.
Professor Humphreys said: 1) write a whole program
2) standard input.
The answers to your questions are on the assignment help page: $@RESOURCEVIEWBYID*24@$
MergeSort
User 355 said: When I submit the merge sort program and robograde it, this is what is returned:
Verifying the existence of a proper mergeSort function in MergeSort.class
Found one! Now I'll go ahead and test it.
THE TEST SCRIPT FAILED! PLEASE REPORT THIS AND INCLUDE THE FOLLOWING:
java.lang.reflect.InvocationTargetException
What's wrong?
Professor Humphreys said: Sorry, this error is misleading. Your program caused an exception (like ArrayIndexOutOfBounds or something), but because of the way the test harness calls your code, the details of the exception are kind of getting lost in the shuffle.
I'll see if I can make this better.
Professor Humphreys said: Okay, this is more robust now. The system actually tells you what went wrong instead of just saying "NO!", which was pretty rude.
Run Time Problem
User 161 said: When I run the program, there appears several "run times" at bottom, such as
Flat profile of 25.28 secs (2344 total ticks): main
Flat profile of 6.40 secs (1 total ticks): DestroyJavaVM
Global summary of 31.69 seconds
I don't know what do they mean exactly and which one should I put in the readme file?
Thanks !
Lesley said: Either do the first one (main) or the "global" one - but be consistent - that is more important. The first one is how long it took YOUR code to run, the second one is related to java itself, and the third one is just the sum of the first two, how long it took your program, in all, to run. But really as long as you're consistent with which one you choose to use, your regression line will come out to correct values.
Readme Assignment 4
User 151 said: I am confused about what the readme is asking when it wants me to calculate running time for program in the form of a * N^b. Where do I find these values?
Also, I am not understanding how to find the amount of memory required to run the program in the form of a * N^b. Are these values the same as before?
I guess if I can understand this part, I can figure out the largest N that the program can run in one day, and if it is limited to 1GB of memory.
Professor Humphreys said: You have a table of values for (N, f(N)), right?
So just do a least squares fit to get A and B.
http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
MergeSort 2
User 355 said: What does this error mean?
java.lang.StackOverflowError
Is it with the recursion??
Professor Humphreys said: #750
MergeSort again
User 347 said: I've been struggling with this problem for a few hours now. If I run mergeSort(arr, 0, arr.length), my program works perfectly. When I do mergeSort(arr, 0, arr.length - 1), it sorts everything except whatever is in the last slot of the array. Obviously my upper bound is off by 1, but whenever I try to fix it I get java.lang.StackOverflowError again. Nothing works and I'm getting extremely frustrated. Any nudge in the right direction would be greatly appreciated.
Professor Humphreys said: Test your program with a small input (say, three or four elements), and run it in the debugger.
Lesley said: I've seen this error in office hours multiple times. Guess what, it was because people googled the code and found an incorrect version. Your code is not correct. Do not change the main method. Go to office hours so someone can help you fix it.
I made this very clear last night when I saw the exact same code multiple times (very wrong code at that)........ Don't google code........ Chances are your recursion and/or sorting indices are off by only one.
output.txt
Professor Sullivan said: Right. The file will be in whatever directory you're in when you run the cmd. --KS
Lesley said: In the directory with your EditDistance.class file, where you're running java from....
it should say j:\directory\structure\> java... and it would be at j:\directory\structure\output.txt
MergeSort Datacollection problem
User 451 said: We put our merge sort through robograde, everything looks good except when the sequence is in reversed(i.e. 9.0 to 1.0) our datacollection says 13 count while robograde has about 30.
The output of that sequence is sorted, also everything else in merge sort is right according to robograde. I'm wondering why that one is not right?
I had the datacollection increment count everytime a comparison is made inside while loop
Assignment 4 -- Largest N program can handle.
User 449 said: Hey,
I figured out how to estimate the runtime of my program for my program given unlimited memory, but I'm having difficulty figuring out what exactly to do with the 1 GB restriction.
-Joel
Lesley said: * As a function of the string length N (assume M = N), estimate the
* amount of memory used in bytes. Your answer should have the
* form a * N^b for some constants a and b. Assume char = 2 bytes, and
* int = 4 bytes. Justify your answer.
*
* What is the largest N that your program can handle if it is
* limited to 1GB (billion bytes) of memory.
so memory in bytes = a * N^b
you know memory in bytes = 1gb = 1 billion bytes... = a * N^b
you know and and b
can you find N?
Question regarding Assignment 4 format
User 347 said: Does assignment 4 require a function and a main method? My program only has a main method and I've gotten the correct edit distances for each of the suggested test cases.
Lesley said: no, you don't need a function other than main.
if you're bored try your program against lastxgap8.txt and lastygap8.txt - it might surprise you with its trickiness.
ecoli2500.txt
User 347 said: I've been running my program to fill in the data tables for the readme.txt file and my ecoli####.txt files keep returning times and edit distances that are much lower than they should be. I have tried to allocate more memory to java but I keep getting the same result.
My major concern is that when I open the ecoli2500.txt file, I see a bunch of random symbols instead of letters or numbers. Is this correct, or should I download those files again?
Lesley said: you should see a bunch of [ATCG]s. you might want to redownload.
EditDistance Compiling Error
User 69 said: When I try to compile EditDistance.java I receive the following errors:
"EditDistance.java:4: cannot find symbol
symbol : variable StdIn
location: class EditDistance
String m = StdIn.readString();
^
EditDistance.java:5: cannot find symbol
symbol : variable StdIn
location: class EditDistance
String n = StdIn.readString();
^
2 errors"
I added stdlib.jar to my program already. What should I do to be able to compile the program in order to increase its memory?
Lesley said: this is a problem with stdlib working with your program - try re-adding it.
Question about String length in readme.txt
User 347 said: "As a function of the string length N (assume M = N), estimate the running time of your program in seconds."
So in the case of ecoli2500.txt, would I use the individual string length of 2500 characters, or the combined string length of 5000 characters?
Also, in the equation a*N^b, what exactly do the constants a and b represent? I read that we're supposed to use the least squares method to find them, but I'm not sure what that is. I'm assuming excel can do that, though.
Lesley said: via google: http://www.sdmiramar.edu/faculty/fgarces/ChemComon/Tutorial/Excel/index.htm
You could also do this with your TI-8* as well.
you will use 2500.
You're basically trying to find an equation that holds for all of your N values such that the dots (if you graph your N values) connect and the same a and b for all N values describe this graph of connected dots.
I mean... You all really didn't do this in high school???? What is public education coming to...
Professor Humphreys said: You can also do it... on paper. There are only a very small number of data points.
Individual Assignment 4 - Estimating amount of memory used in bytes
User 215 said: In the last part for the readme file, it asks to estimate the amount of memory used in bytes. I don't know what to do for that. Any suggestions to help get me started?
Lesley said: Well, you're storing 2 strings, which each have N characters (M=N), and an array of NxN ints. char = 2 bytes, int = 4 bytes... See where this is going?
java -Xmx300m EditDistance
Professor Humphreys said: You don't implement it, this is the precise string that you type at the command line to run your program with an increased amount of memory.
So to run your program *normally*, you just type:
java EditDistance < input.txt
for extra memory, type:
java -Xmx300m EditDistance < input.txt
This all happens at the command line.
Professor Sullivan said: You can also type
-Xmx300minto the VM arguments panel under Run>RunDialog>Parameters for the same effect. This "option" tells the system to grab 300 megabytes of RAM for use by your application. If you need more memory, increase the 300. You can go as high as you have physical memory available.
Last part of readme.txt
User 347 said: For the last part of readme.txt where we have to estimate the amount of memory used, are we supposed to use the input file and the array produced in finding the exit distance in our calculations, or is there more? Are we supposed to take the output into account?
Lesley said: You use what your program stores - the strings and the array.
Spaces?
User 52 said: Do we have to include spaces between each of the characters? or can we just print out the characters of the first array as given?
Lesley said: You should format your output like it is formatted on the help page (there are 2 options, you need to choose one and match it exactly just like robograde makes you do).
EditDistance Command Line Compile
User 191 said: So, my EditDistance program runs fine in Eclipse but when I go to run it from the Command Line it won't compile and I get errors for everytime I have StdOut or StdIn in my file. Mine looks just like the other post complaining of this problem and I tried readding the stdlib file as already suggested. Is there something silly that I'm missing?
Lesley said: you need the -cp flag, see
#719
Spaces in IA
User 187 said: When we print out the optimal output of the genes using method number one on the help page, e.g. A A 0 and down the line underneath, how many spaces go between each character? Is it one between the letters and then two between the second letter and the number?
Lesley said: It looks like [letter][space][letter][space][space][number]
initializing opt[i][j]
Lesley said: 0 or 1 refers to the character of x at i and y at j and if they are equal.
Looking at the array given at opt[0][0] you figure it out by min (opt[1][1] + (character at x.0 and y.0, A and T, are different so 1) = 6 + 1, opt[1][0] + 2 = 6 + 2, opt[0][1] + 2 = 8 + 2) = min (7, 8, 10) = 7.
Looking at opt[2][2] = min (opt[3][3] + (A not C so 1) = 6 + 1, opt[3][2] + 2 = 4 + 2, opt[2][3] + 2 = 8 + 2) = min(7, 6, 10) = 6 - now you can see why 0 or 1 is necessary
end of my program
User 440 said: I cant figure out why the backtracking doesnt work. It cuts off the larger sequence to make it the same length as the smaller sequence which then screws up my "edit distance" but the the real edit distance is the correct answer......is there any way i could send someone my file to see what i did wrong?
Lesley said: What kind of loop are you using for backtracking? Since you need to keep track of both i (0...m.length) and j (0...n.length) you might need to reformulate your conditional.
It would have been smarter to start this earlier so you could go to office hours for this kind of thing. It isn't possible for you to send your code to one of us, sorry.
Incorrect Outputs when piping in txt files
User 516 said: When piping in the text files, I get a different edit distance than when manually copy-pasting the sequence. Why?
Lesley said: That shouldn't be happening.
Are you sure you're copying the entire file when you paste it in?
Is it all files or just some? Are they big differences or small ones?
String Out of Bounds Exception
User 196 said: My code produces the correct output, but it also comes along with a "String Out of Bounds Exception".
Lesley said: So you're using some kind of loop to backtrack... When is it supposed to stop? It seems like it keeps going past when it should be (trying to access x[i] for some i greater than x.length for example).
String Out of Bounds Exception - Similar Problem
User 52 said: I'm having a similar problem the person in the previous post, William Nathan Wethington.
I've tried the inputs for gene57, stx1230, and ftsa1272 and I got no errors, and the correct edit distance as well as the correct alignment. However, there is a string out of bounds error for the original two alignments. How is it that it worked for longer strings, when it did not work for the original string.
Lesley said: Each test file tests your program for certain bugs it might have with gaps or what not. So longer does not necessarily mean more complex - the endgap files I think are the trickiest.
Think through (or DEBUG) why your program is giving you an error/exception. You can surely find what is going on.
Time
User 323 said: I have been trying to calculate the time it takes to get the edit distance for each ecoli file, but I keep on getting errors. Looking at the earlier posts are helpful but I still haven't figured it out. Can someone please summarize what I need to do to have it work?
I use a Mac, if that helps clarify anything.
Thanks
Lesley said: Um... Errors? You need to elaborate.
Read me last question
User 577 said: how to calculate the amount of memory used?
amount of memory used = no of char in string*2+no of int in string*4 ?
or it also relates to the matrix?
confused...
Lesley said: #773
Re: Time
User 323 said: Basically I'm trying out the code that you mentioned earlier. After I go to my "Edit Distance" file, and then to src, I type:
>java -cp j:\cs\stdlib.jar;. -Xmx300m EditDistance < ecoli2000.txt > output.txt
But I get the following:
-bash: -cp: command not found
-bash: .: -X: invalid option
.: usage: . filename [arguments]
I have made sure that I include ecoli2500.txt and output.txt in my src folder under "Edit Distance"
Lesley said: On bash-using systems (Mac uses this as well, and Unix obviously) you need to do : instead of ;
MergeSort
User 95 said: If our MergeSort program works in fewer steps than robograde wants it too, is it still wrong?
Professor Humphreys said: Did robograde give you credit for the work? If so, then your program is fine. If not, then probably not.
Re:Re: Time
User 323 said: My error has become a little bit better but I still get this.
-bash: -cp: command not found
when I do (I changed ; to :)
>java -cp Documents\CS101\stdlib.jar:. -Xmx300m EditDistance < ecoli2500.txt > output.txt
I also tried doing it without the ">" in the very front, but that didn't work either.
any idea?
Midpoint
User 343 said: In both my mergesort and merge function I have a variable called "mid" that is supposed to be the midpoint of the lower and upper bounds of the array. When I look at the merge examples in the book and in the notes, I see that sometimes the code has "mid+1" instead of just mid. I was wondering how would I know when to use mid+1 versus mid in my code? This goes for other variables that also relate to a position in the array.
Professor Sullivan said: Our specification is not necessarily precisely the same as for the example in the book. The way to determine which expression to use is to
analyze the situation to determine which one is correct. You'll really have to think through precisely what's happening as your program executes.
Making the StdOut work on macs terminal
User 403 said: Is there any way that I can add the stdlib into the macs terminal like you would in windows for example another help topic said to type in:
j:\cs\editdistance\src\>javac -cp j:\cs\stdlib.jar;. EditDistance.java
j:\cs\editdistance\src\>java -cp j:\cs\stdlib.jar;. -Xmx300m EditDistance < input.txt > output.txt
but this works only for windows what do I type in for macs?
Lesley said: I *believe* the only difference is in the part following -cp you use : instead of ; but it might be more complicated than that... reply back if that doesn't work and maybe someone with a Mac can clarify.
Another option is to use Eclipse as described at #774
Professor Humphreys said: Well, macs don't have anything like j: or anything like that.
Let's say you put stdlib.jar on your desktop.
then, at the terminal, run:
java -cp ~/Desktop/stdlib.jar:. EditDistance < input.txt > output.txt
Professor Sullivan said: It's really easiest simply to add the following in the VM Arguments panel under Run>Run Dialog>Arguments
-XProf -Xmx1000m
The run your program in eclipse, and copy and paste the contents of the ecoli files into the console window.
KS
EditDistance will not compile in command prompt
User 561 said: I am terrible with command prompt and am probably doing something stupid but when I get to my src folder and type:
javac EditDistance.java
It returns an error which says:
'javac' is not recognized as an internal or external command, operable program or batch file.
What am I doing wrong and what should I be doing?
Professor Sullivan said: We dealt with all this at the very beginning of the semester. See the instructions on the web site how to set up Java to run on your computer. Your search PATH isn't properly set up.
Running in Eclipse
User 403 said: I pasted -XProf -Xmx1000m into the VM arguments part but I got a response from eclipse that says
Unrecognized option: -XProf
Could not create the Java virtual machine.
What should I do?
User 167 said: That error means that Java didn't recognize the command line option "-XProf" as something it knew how to handle.
In this case, it's because Java is case-sensitive. Try "-Xprof" instead.
Professor Humphreys said: Java said it doesn't recognize -XProf, so remove -XProf.
Professor Humphreys said: Or this :D
Professor Sullivan said: Sorry, my typo. It's
-Xprof
NOT
-XProf
KS
New Computer set up
User 489 said: I ended up getting a new computer halfway throug the class and can't get it set up right. Eclips runs fine and I downloaded the java but it was a JDK 6 Update 5??? and I get a javac is not recognized as an internal or external command.
I'm guessing i messed up in the c: envoirmental varriables. I had to create a PATH and I coppied the bottom from the help file.
What now????
Professor Sullivan said: Yes, your path is wrong. See the page on the web site that explains how to set up your computer to use Java and Eclipse. Note, however, that you might have to change the JDK name in the search path from something like jdk6.01_04 to jdk6.01_05 if in fact Sun updated the JDK since the semester started. Just look at the name of the directory where your version of Java got installed, and use the correct directory name in the search path.
JDK 6 update 5
User 489 said: In reguards to the below question.
I checked in the control pannel and pasted the updated path to the envoirnmentals "C:\Program Files\Java\jdk1.6.0_05" but still got the "javac is not recognized as an internal or exeternal..." ???? is there a way that I can compile and run the program from Eclips with java not running from the CMD line???
CMD line and lib's??
User 489 said: I resently installed the new JDK to a new computer and got it to accept a javac command and compiled a program. In eclips I added the Std.jar for my Sdt commands but for some reason the CMD will not recognize StdIn as a command. ??? What didn't I do??
Lesley said: Okay. It's a week before the 2nd midterm...
With that said, eclipse has NOTHING to do with the command line accepting stdlib.
You need to do javac -cp j:\whatever\stdlib.jar;. or add it to your classpath.
Import existing Projects?
User 71 said: I now know i can do that with Import/General/existing projects,
but before I remember there is a easier way where you can import an project which you copied from other workspace by checking it in a specific window, which also allow you to import a bunch of projects quickly at a time, but I forgot how to do that, does anyone know what I'm talking about?
Thank you.
Groupwork5
User 71 said: the shoppingcart class has a constructor that will read in a int which the comments have nothing to talk about (I actually think it might be significant), is it true we have to understand how the shoppingcart data type will be used and then we will know what to do with that varible?
Thanks
Lesley said: The way it worked before it was changed a little bit ago was that a random value between 1 and maxLoad was assigned to itemCount but now it says to make it empty, so I'm not sure if you're supposed to use load(maxLoad) in the constructor or not. Maybe Professor Sullivan can clarify.
Professor Sullivan said: My mistake. That parameter is not used. I'll remove it from the file posted on the web site. Thanks for the heads up.
GW 5
User 71 said: Sorry for multiple post.
I am just confused why should maxNewCarts's type be double, which will make it a trouble trying to make it work with Math.random().
Thank you.
Lesley said: I think it is supposed to be int.
Professor Sullivan said: That's a good question. The intention was to allow you to specify that on average fewer than 1 new carts show up per second. However, for purposes of this assignment, leave it as
double but you should only pass integer values.
delayinMSdelayinMS
User 71 said: I'm totally confused by all the time steps and time period per second stuff
just wonder if the required number of millisecond is a dependent variable of the timesteps per second and the numberoftimesteps, or is it a independent one that you can just set it to what you want?
Thanks
Professor Sullivan said: First read the API for the StdDraw.show function.
You need to specify a number of milliseconds to achieve a desired number of "display updates per second."
KS
runtime of factorial,fib and matrix
User 254 said: what is the runtime for factorial using recursion? n?
Fibobacci using dynamic programming? also n?
and matrix multiplication? n^3?
Thanks
Professor Sullivan said: It's best not just to memorize answers to these questions, but rather to analyze the algorithms to really understand what their runtimes are any why. So my best advice is that you should study the algorithms to figure out the answers. --Kevin S
API's
User 99 said: What is the difference between a library and an API? Thanks.
Professor Sullivan said: A library is a pre-packaged set of (one or more) general-purpose classes (where each class has an API and an implementation). An API is the
interface or the set of interfaces by which you interact with a class or set of classes.
GuitarHeros
User 71 said: I just wonder how StdDraw.hasNextKeyTyped() works.
When I run the program it doesn't play any sound and when I try to debug it, it will automatically skip the entire "if" structure (which I assume it automatically thought it's false, or no next key typed), and then two guitarstrings were created and initialized to zeros, but neither of which has been plucked.
It seems to me that my program doesn't reponse to my typing, but I am not sure if I did something else wrong.
Thank you.
Lesley said: There are a few ways you could test this.
Try manually editing your guitarstrings (ie, instead of having the if after the initialized zeros, just make it make them). If you can then get sound, then it's not hasnextkeytyped(), which in likelyhood it's some minor bug with your program that is the issue, not stddraw (I've gone through and programmed this assignment and it works on my computer). also check and make sure your comp is not on mute!!! check all of the volume bars (midi/synth, wav, all volume, etc).
I'm sure TAs would be glad to point you in the right direction at office hours if you're unable to further debug yourself.
Groupwork #5
User 124 said: I've tried to submit some of the group work on two different computers and both, at the the bottom of the group work page, say, "You cannot submit files from this computer. Please make sure you are working at an approved computer for this assignment." Any ideas??
Professor Sullivan said: Sorry, probably my fault. We're working on it. --Kevin S
Professor Humphreys said: Sorry, it was incorrectly marked as a lab. This is fixed.
The number of comparisons in Quicksort
User 49 said: How many comparisons are made in a random case in Quicksort?
I think it is NlgN but the slides said the the number of comparisons is 2NlnN (page 23 of the Algorithms)
If it is the latter, then why?
Professor Humphreys said: 2N lg N is technically correct, since on average the tree will not be perfectly balanced. The analysis of average case quicksort is very, very complicated, and requires pretty sophisticated mathematics. If you're interested in the details, you might try reading some of the writings of a man named Donald Knuth, who is one of the most brilliant and prolific computer scientists to ever live.
Remember that we always leave off constants when doing algorithm analysis. The goal of the analysis is not to predict PRECISE performance, but rather to characterize how the running time will change as the size of the input changes.
a function that is N and a function that is 100N will both take twice as long if N doubles. Of course, you should probably prefer the first one (but not always!), but that's not relevant to the algorithm analysis.
question regarding order of growth
User 49 said: public static void f(int N) {
if (N == 0) return;
f(N-1);
f(N-1);
...
}
according to the slide(# 25) of the 08 algorithms, the order of growth of this program is exponential(two to the power of N).
Why? It is different from the fibonacci, isn't it? I think it is linear.
Professor Sullivan said: Well, fib differs only by a difference that makes no real difference when it comes to characterizing the runtime complexity. Fib(n) doesn't compute Fib(n-1) twice. Rather it computes and adds Fib(n-1) and Fib(n-2). The details differ but the end result is still an exponential growth in the time to run the algorithm, as a function of n.
Note: Moodle is doing something weird with my notation
fib followed by a left parenthesis followed by an
n followed by a right parenthesis. Sorry about that. It's substituting some kind of "emoticon".
pluck
User 77 said: For the pluck() method in the guitar assignment, the assignment page says to "replace the
N elements in the buffer with
N random values between -0.5 and +0.5" and the help page says to use dequeue(), enqueue(), and size(). It's clear that enqueue() is needed, but since you are filling the array and not removing anything, why is dequeue() needed? and is size() really necessary, since size tells how many elements in the buffer are filled, not how many elements the buffer has? Thanks.
User 353 said: In order to
replace the N elements in the buffer, the buffer must first be cleared of the current values. Adding N elements to the buffer without first clearing its contents would result in an exception thrown from trying to add to a full buffer (enqueue() does not replace a current item, it merely add a new item). Therefore, dequeue() will be necessary to remove all of the items in the buffer, and the size() method may be useful in doing this (but there are other ways I can think of to perform pluck without explicitly using the size() method).
Lesley said: You need to remove all the current values and replace them with random ones between -.5 and .5 - hence you need all 3 methods
does the constructor name have to be identical to the class name?
User 49 said: When I create my own data types, do I have to keep the class name the same as the constructor name?
For example, public class Charge{
public Charge(double x0, double y0)
}
Can the second Charge be changed to other names?
If not, why not?
Thanks.
Professor Sullivan said: The name of the class and the name of the constructor (as well as the name of the File containing the class) have to be the same. If you want to change a class name, select the class name, right click, select Refactor>Rename, and type in the new name. Eclipse will update the name in all of the right places.
Lesley said: You should also read up at
http://www.cs.princeton.edu/introcs/32class/ and you could also read at
http://www.ccnyddm.com/AdvJava/java_constructor_tutorial.htm too (especially the use of "this()" should help you see why it has to be the same name).
GuitarHero-Visualizer
User 71 said: When I tried to visualize the string, the problem that I ran into is that, since each string has different frequency, which results in different lengths of the buffer arrays, I really dont know how to combine them together as a single array ( only when all the arrays have identical length will I be able to do this), and then I reach to the point where I can use StdDraw.line() to graph it.
Am I using the wrong method?
Or are we supposed to visualize each string separately in the first place?
Thank you
Lesley said: Since this is extra credit I don't think we can give you any help.
totalItems
User 282 said: Are we supposed to use Iteration to complete this function? If so, do we have to add a whole bunch of code to the Queue class in order to enable it to use iterator() method?
Lesley said: You can keep track of totalitems by doing what is asked in the comments: ie this one before enqueue: "Add a new cart to the line and update the total number of items accordingly." Don't forget in scanitem: "Decrement the totalItems count."
StdDraw & StdAudio
User 71 said: I found out once I put StdDraw in a while loop, StdAudio will only play a very segment of sound once in a long time, and what I assumed is StdDraw might take a long time to process which interrupt the instant continuity of the loop, am I right, or is there another issue causing this?
Thank you
(Hope this doesn't sounds like a extra-credit-particularly question)
Lesley said: This is a problem that will be better solved by showing your code to a TA during office hours, though you might want to search the forums for "threading" as this has been somewhat discussed before.
Groupwork #5
User 124 said: Is there no Robograde for this assignment?
Lesley said: This has been asked in the past: Exactly how would one robograde an assignment with random numbers?
Professor Sullivan said: Well, one could do statistical tests! That said, we're not doing that, so, no, there is no robograde option.
Public vs private vs nothing
User 320 said: What is the difference between using public or private, or using no prefix at all. If I write
public Charge(double a, double b){}
private Charge(double a, double b){}
Charge(double a, double b){}
What is the primary difference between these three types?
Professor Sullivan said: Public means that any object can directly access an instance variable or method
Private means that only methods in the same class have access
There are two other "visibility" keywords that we haven't studied: package, and protected.
Package means that all classes in the same "package" (something we haven't studied yet) have access. That is, variables or methods marked this way are directly accessible to multiple classes in general, those in the same package.
Protected means that a variable or method is directly accessible to "subclasses" of the given class. This is a topic that you won't see until 201.
IF YOU LEAVE OFF THE VISIBILITY SPECIFIER, YOU GET
PACKAGE VISIBILITY. For our purposes, that's the moral equivalent of public.
Good question.
StdDraw & StdAudio(further discussion)
User 71 said: I opened the StdDraw class and found inside the show(int t) method a line "Thread.currentThread().sleep(t);", is that the threading thing you talked about (sorry I did search but found nothing in the forum), I guess that might be the reason why the drawing cause the delay.
But another question of my is if I delete the show() and remain the clear(), it will draw even slower, which to me is a little bit confusing.
Thank you
Lesley said: search for 'thread' revealed: #492
please... it's impossible to help you without seeing your code. you should go to office hours.
the total memory requirements for a 2D double array
User 49 said: what is the total memory requirements for a 2D double array?
Is it 8N^2+20N+16(p.494) or 16N^2+20N+16(p.493)..
I just found two answers from the textbook.
Thanks.
Professor Sullivan said: We won't ask you for such detailed formulae. Just as with runtime complexity, what we're mainly interested in is the dominant term, without constants. So, in this case, it's N
2 Why? Ignore the lower order terms (20N and 16), and ignore the constant. What's left is N
2
questions about memory requirements
User 49 said: In the first line of page 491, it says that we need 4 bytes for each double instance variable in an object. Is that wrong? i think a double variable should take up 8 bytes.
Professor Sullivan said: Double is 8 bytes. I don't have the book before me. If it says 4, it's wrong. Check on the book site, under errata (when you have time). If you've found a new bug in the book (and there are some), you should report it to the authors. You'll be famous. (Ok, well, not really, but you will get your name on the list of people who found bugs!)
KS
static vs Non-static
User 320 said: I'm still a bit fuzzy on what "static" means. Someone gave me this program to test:
public class Athing {
static int counter;
private int personalCounter;
public Athing() {
counter++;
personalCounter++;
}
public int getCounter() {
return( counter ) ;
}
public int getPersonalCounter() {
return( personalCounter ) ;
}
public static void main(String[] argv) {
Athing[] things = new Athing[5];
for (int i = 0; i < things.length; i++) {
things[i] = new Athing();
System.out.println("counter: "+things[i].getCounter()
+"\tpersonalCount: "+things[i].getPersonalCounter());
}
}
}
The results are:
counter: 1 personalCount: 1
counter: 2 personalCount: 1
counter: 3 personalCount: 1
counter: 4 personalCount: 1
counter: 5 personalCount: 1
The static integer counts while the private integer does not. Why does this happen?
Lesley said: static means: tied to the class, not to an object (those are your two choices).
each time you create a new "Athing" a new instance of personalCounter is created just for that object. however, the counter variable is static, tied to the ENTIRE class not just one Athing object, so it is NOT recreated just for each new Athing and thus continues to get incremented every time a new object is created instead.
as far as methods go, you could do thing.getCounter() but not thing.main() because main is tied to the class. make another method, public static int getCount(), where you return counter, and you'll see you can call it as getCount() but not thing.getCount()
User 167 said:
Lesley said:
"as far as methods go, you could do thing.getCounter() but not thing.main() because main is tied to the class. make another method, public static int getCount(), where you return counter, and you'll see you can call it as getCount() but not thing.getCount()"
That's actually not true - you can call thing.main() or thing.getCount(), and Java will recognize that since both are static functions of Athing, it should call Athing.main() or Athing.getCount(). Eclipse will give you warning that you're calling a static function in a non-static way.
Lesley said: my bad. usually i try things before i assert their accuracy but i was being lazy. i won't do that again obviously.
Factorial - runtime
User 546 said: I got confused when estimating the run time for the factorial using recursion. When using a for loop, we can see that it will take N, but when using recursion I was not sure if it would take N or exponential (since it will pile N, N-1, N-2...). How should I think about that?
Thanks!
Professor Sullivan said: Just trace the execution for, say, 3!, 4!, 5! You're on the right track with your "piling up" analogy. --KS
Wrap around - queue
User 546 said: I didn't understand the meaning of the "wrap-around" that the book talks about when implementing an array of queue.
Thanks!
Lesley said: Okay, so suppose your queue has capacity 3 and you're using an array (of...ints) to represent it. So it starts off:
first=0, last=0, size=0, array (initialized to) = {0, 0, 0} queue is empty
So now suppose you add 3 elements, 1, 2, 3. Then it becomes
first=0, last=2, size=3, array={1, 2, 3} (ie. array[first] is the first element in the queue and array[last] is the last) queue = 1, 2, 3
Now if you dequeue 1, your array is now
first=1, last=2, size=2, array = {(1), 2, 3} queue = 2, 3
If you want to enqueue 4, you CAN do it, because your queue is only of size 2 and it has capacity 3. But you don't want to move everything over so it's {2, 3, 4} because that's inefficient. Instead, implement a wrap around so that
first=1, last=0, size=3, array = {4, 2, 3} queue order = 2, 3, 4
Professor Sullivan said: Camila,
Note, however, that this "wrap around" implementation is NOT the same as the "basic" implementation of a queue, using an array, that we discussed in class. See your class slides and/or the book for a "basic" queue implementation using arrays.
KS
About the Exam
User 71 said: Just wonder if we are allowed to talk about the problems in it after 4:00 pm today
Thank you.
Professor Sullivan said: Thanks for asking. You may discuss the exam but only if you confirm that you are not near or in the presence of someone who has not yet taken it. There are a small number of people who legitimately need an extension for one reason or another (e.g., University travel, broken bones, etc)
Is the lab tomorow graded?
User 98 said: Do we have a quiz tommorow in the lab on exam material?
GuitarHeroLite
User 343 said: I have created and tested both RingBuffer and GuitarString, and they both seem to work fine (produce the same output as the examples given). However, when I run GuitarHeroLite, the StdDraw window pops up but they keystrokes A and C don't make any sound. Upon further inspection, i'm getting a "RingBuffer underflow" error. This makes me think that the array for CONCERT_A either isn't recognized or just isn't working. Are there any files (such as txt files) that I was supposed to download that may contain this, or is there another possible explanation for this error?
Also, the help section says to download the directory "guitar", but the link doesn't work.
Exam Grade
User 218 said: Are the exam grades supposed to be posted as of now?... because mine is not on my grade sheet...
Thanks
-Matt
Professor Sullivan said: Should be by now
Exam Grade REPLY TO SELF
User 218 said: I found my grade, please ignore my previous post.
-Matt
exam grade
User 100 said: I recieved an email saying my exam grade had been posted but it doesnt show up under my grades section and it didnt appear on the link that the email included
Guitar Directory
User 170 said: I'm starting the Assignment 5 and under possible progress steps, the first one is download the guitar directory however when you click on the link it comes up as an error.
Is there anywhere else we can get the guitar directory from?
Thanks,
Matt
Professor Humphreys said: whoops, typo! This is fixed.
Lab Quiz #4 grade
User 284 said: When I took the lab quiz in class I robograded it and received a grade of 100. Now it says that I have a grade of 50 and it says this for my average arrays...
java.lang.reflect.InvocationTargetException
Can you explain what this means and if my grade of 50 is correct if I had a 100 when I robograded it originally.
Thank you.
Professor Humphreys said: Sorry, I fixed that error message for teamwork4, and the fix didn't propagate back. Your error message is now much more informative.
Problem with GuitarString
User 347 said: My GuitarString keeps returning a java.lang.NullPointerException error. I saw where there were tips for dealing with that error when it arises in RingBuffer, but none of those seem to be the problem.
If it helps, I already wrote my GuitarHero program but I'm only able to get about 4 of the 37 notes and in no logical order. Any help would be amazing.
Professor Sullivan said: Josh, I strongly recommend that you use the debugger to see what's happening as your program actually runs. --KS
guitar readme
User 77 said: Is a readme file supposed to be submitted for the guitarhero project, as it is not mentioned under the file submission area, and the link to a readme template on the help page does not work.
Professor Humphreys said: Whoops!
Both the broken link and the missing file upload name are fixed. Thank you!
past year exam
User 235 said: Is that possible if we can get any past year exams and solution so that we may study them and prepare for our exam?
Lesley said: The CS101 course at UVA this year is modeled after the COS 126 course at Princeton. Thus there aren't any past exams that can be provided for this year, but feel free to look at the old Princeton tests at:
http://www.cs.princeton.edu/courses/archive/spring08/cos126/exams.html It should be noted that these are not UVA's tests though so some things they test on might not be (and won't be) tested on at UVA, and UVA may test on things Princeton does not.
CheckoutArea (Group Work)
User 124 said: How do call on the function scanItem(), created in the Server class, from the CheckoutArea class? Thanks.
Lesley said: You can do the function scanItem() on any Server object. So if your Server object were named serv, you would do serv.scanItem()
Calling Other Classes/Functions
User 52 said: How do you call other functions from other classes? I've tried lots of possibilities. And looked in the book. But some how there is always an error in whatever i put.
How can i use the removeItem() function (from the ShoppingCart class) in the scanItem() function (in the Server class)?
Lesley said: You can only use removeItem() on a ShoppingCart OBJECT and same with scanItem() on a Server object. But as long as one of these objects exists (ie. Server s = new Server(); s.scanItem();) then you can use those methods (and create new Server/ShoppingCart objects) in a different class within this project (they're all in the same folder and public classes so they'll be able to interact with eachother).
Should you have more questions please come to office hours and a TA will help explain it to you.
RingBuffer
User 124 said: public void enqueue(double x) {
if (isFull()) { throw new RuntimeException("Ring buffer overflow"); }
// YOUR CODE HERE
buffer[last +1] = x;
An error always pops up about the function enqueue()... any ideas?
User 167 said: In general, we will never be able to help you when you say something like "An error always pops up", because there are a thousand things that could be wrong, depending on the rest of your code. If you can tell us what the specific error message is, then we might be able to give you advice.
Look in the "Problems" tab or hold your mouse over the error in Eclipse to find out what the error message is.
Sample
User 343 said: My guitarherolite works perfectly, however my GuitarHero does not. When I type a key, all I hear is a single static "pop" sound. For debugging, I set my "sample" variable equal to a single GuitarString.sample() that I stored in my array, keyboard[24] (which is 'g', and at 440 Hz). If I just type g, this works fine and sounds exactly like the A in GuitarHeroLite. This leads me to believe that i'm calculating my sample value wrong. Isn't it just the sum of all the GuitarString.sample()'s? Or could something else be wrong?
Lesley said: It is just the sum. But are you resetting it to zero before resumming every time in the loop?? If that's not it I'd suggest coming to office hours so we can look at your code. I don't know what would make it pop.
Groupwork: Is this supposed to happen?
User 320 said: My group got our Store simulation working, but I'm concerned because the carts really stack up after a while in the sim. Is this supposed to happen? Are the carts supposed to stack up when the sim is ran for a while or have I made some kind of error?
Also, my group is confused about the "1/2 the number of milliseconds required to achieve the 'frames per second'" in the Store.java. What does this mean? We just choose 500 for a number; does that work?
Professor Sullivan said:
> the carts really stack up after a while in the sim. Is this supposed to happen?
There are arrival and departure rates you can specify that will result in queues growing without bound. What's more interesting is that there are situations in which you'd think that wouldn't happen, but it does.
> My group is confused about the "1/2 the number of milliseconds
Suppose you want to see 24 frames a second go by, each one involving both an arrival step and a departure step. That's 1000/24 milliseconds per frame, right? Now, if you update the frame after an arrival and wait half that time, then also update the frame after a departure, and wait half that time, then you'll achieve the desired frame rate.
You want to get to the point where you just start to work these things out.
Ignore my last question
User 320 said: Found out that we are supposed to use StdIn to find a value that works. Sorry about that.
Groupwork 5
User 194 said: My group members and I are having trouble with Store.. We're not sure how to initialize the display. Also, when we run the main program it says "Exception in thread "main" java.lang.NullPointerException".
Lesley said: NullPointerExceptions come up when you do something like this
Server[] servers = new Server[10];
for (int i = 0; i < servers.length; i++) {
servers[i].scanItem();
}
Because you didn't do servers[i] = new Server() for each servers[i]. You probably did this for the Queue<ShoppingCart> line and maybe for an array of ShoppingCarts.
The display can be initialized in a similar manner:in the constructor, use "new" and then use the method initializeGraphics() where appropriate.
Null Pointer Exception -- RingBuffer
User 170 said: I'm working on RingBuffer and I believe my problem to be how i initialized the instance variable buffer[].
I want length of buffer[] to equal capacity, but if i create a new array i shadow this variable creating my null pointer exception.
I know the problem but don't have any ideas on the answer
Thoughts?
Lesley said: The length of buffer[] is capacity. How does creating a new array cause a NPE?
Extra Credit
User 151 said: This is really directed toward the professors than TAs, but I am wondering what I would need to find in order to adjust the formulas to replicate another instrument for the extra credit assignment. I am willing to search for what I need to know, but would like to know what to look for.
Professor Sullivan said: A good place to start searching would be on
Karplus-Strong algorithm. There's a nice Wikipedia article on it, for example. Also be aware that some composition faculty in UVa''s Music department are particularly active in the area of physically based synthesis of instruments (including some that have never been physically instantiated).
String keyboard
User 276 said: On the Guitar Hero assignment page, the page states that we should make GuitarHero.java with a String keyboard with a value of:
"1234567890qwertyuiopasdfghjklzxcbnm,"
However, on the help page, we are told to test GuitarHero.java by typing the following letters:
"E Y P G J P Y J K P Y K S I E S P Y E Y P Y E Q E E"
Are we supposed to write the String keyboard using capital letters or lowercase letters?
User 167 said: I think the specification calls for lowercase letters, i.e. you should be hitting characters without holding down shift.
However, if you wanted to support both, just to be safe, you could use Character.toLowerCase. See
the Character javadoc to learn how.
Question about Guitar Hero
User 347 said: My Guitar Hero programs works, but if I start typing in keys very quickly I hear static instead of notes. This ONLY happens when I type quickly. Is this normal?
Professor Sullivan said: Think about the physics. How are you simulating "energization" of a string?
RingBuffer
User 546 said: I am trying to do
buffer
in the dequeue, but Java doesn't let me. It says "cannot convert from null to double". Why is that?
Thanks!
[first] = null;
Lesley said: You don't actually have to change the value of buffer[first] when you dequeue it; just properly change first to refer to the "next" element in the buffer array.
Question on guitar string
User 427 said: I keep getting an error when I try and perform operation on my buffer array in GuitarString. It says "cannot invoke (size, enqueue, dequeue, etc) on array type RingBuffer. Any idea what I'm doing wrong?
User 167 said: Unfortunately, we can't help you without more information about the problem. But some general tips for solving this sort of problem:
1) Google.
Any time you get an exception or a compile-time error that you don't understand, google for it. Chances are somebody else has had the same problem, asked about it on some Java forum, and gotten a good answer that you can now read to figure out what's wrong. For example, I googled "cannot invoke" "array type" and found this page that seems to describe a problem similar to yours, which might help you solve your problem:
http://forum.java.sun.com/thread.jspa?threadID=653924&messageID=3843978
2) The book. See, specifically,
http://www.cs.princeton.edu/introcs/11cheatsheet/errors.pdf
from the book website, which is a PDF listing various kinds of errors you may encounter and what causes them.
3) If it happens when you run, go in with the debugger. Some references (found by googling "Eclipse Debugger") are:
http://www.fsl.cs.sunysb.edu/~dquigley/cse219/index.php?it=eclipse&tt=debug&pf=y
http://www.eclipse.org/resources/resource.php?id=405
http://www.ibm.com/developerworks/java/library/os-ecbug/
http://www.developer.com/java/other/article.php/2221711
GuitarString Output
User 355 said: My guitar string has the wrong output...what are the likely reasons for this??
(Note: the first nine outputs are correct)
Professor Sullivan said: There is an infinity of possible explanations. Use the debugger to figure it which one is the proper explanation.
Please Ignore my 'Guitar String' Post
User 355 said: Please ignore my post about getting the wrong output for guitar string...i fixed the problem!
Random Instance Variable.
User 560 said: If I create an instance variable:
Private double rndm = Math.random();
will it call the random function every time it is referenced? Or only once in the beginning?
Lesley said: Just that once.
Professor Sullivan said: Lesley's right. Here's how to prove that what she said is correct. The question is, how does the assignment operator work? (1) evaluate the expression on the right to produce a value, (2) store that value in the variable named on the left. You also need to understand what happens when the variable subsequently appears in an expression. When the expression is evaluated, the value that is stored in that variable is used in the place where the variable name appears. So, you can see that there would be no subsequent invocation of the function that generates random numbers.
Professor Humphreys said: another way to prove that Lesley is right would be to write a program and see what it does.
Professor Sullivan said: Good, so now we have three approaches:
1. Ask the TA
2. Reason from first principles
3. Run experiments
Of these three, I like 2 and 3 very much better than 1!
KS
Deletion of Sample
User 560 said: Does deleting the item in RingBuffer mean that we should initialize that value at the front back to 0? or is just incrementing front enough?
Lesley said: #932
Error with StandardDraw in Guitar Hero
User 403 said: My Guitar Hero program wont work because
in this part:
if (StdDraw.hasNextKeyTyped()) {
char key = StdDraw.nextKeyTyped();
I get an error that says
the method hasNextKeyTyped() is Undefined for the type StdDraw
User 14 said: The StdDraw given in the Guitar directory for some reason doesn't have the key typing methods. You can delete that StdDraw from your project and import stdlib.jar. Your code should then compile correctly because the StdDraw in stdlib.jar does have those methods defined.
Professor Sullivan said: Eric, Where is the deficient StdDraw.java file coming from? This is a problem we'll want to fix once for everyone. Thanks, --KS
User 14 said: It's in the Guitar directory that the students are downloading from the GuitarHero help page
Error: Class not found Exception
User 531 said: I was writing a brief java program just to test my guitar string class. I had a main routine that created a
GuitarString test = new GuitarString(440);
just to test the code. All of the java files (queue, ringbuffer, guitarstring, and the main test routine) are in the same directory, my Guitar Hero project/src.
I set a breakpoint in the main routine before it executes the line to make the new guitar string, and hit debug. Whether I step over the code(F6) or step into it (F5), it gives me "Source not found: (ClassNotFoundException:Throwable), and terminates my code. How can i fix this? It's acting like my GuitarString Class doesnt exist.
Groupwork 5
User 516 said: When we run main, the StdDraw does not display anything. We added mains to many of the classes and they seem to work. Any ideas where the problem might be?
Professor Sullivan said: Roshni,
If you haven't yet learned to use the debugger, now would be a great time. Set a break point at the first line of main, and then step through the execution of your program. It's a great way to see what's going on.
KS
Ring Buffer enqueue
User 323 said: For the instance method enqueue(double x), what are you supposed to do when the array is completely filled up? do you have to create a new array with size capacity+1?
Lesley said: You should just throw an exception; see the downloadable code on the syntax for that.
GuitarHeroLite
User 124 said: When running GuitarHeroLite using my GuitarString and RingBuffer, a blank screen pops up but with no instruction... I know this is wrong, but I have no idea why.
Any ideas?
Lesley said: Did you try pressing shift+a (A) or shift+c (C) to see if it plays a sound??
Group Work: never used server.totalItems?
User 273 said: I noticed that a group member of mine made an error in calculating the total items in the queue of a server, and was wondering how it didn't effect our results. Low and behold our program never used server.totalItems. In the instructions it says to ignore the fact that people mentally add up the items in carts, so my question is, does this part of the server class serve a purpose? Should we have implemented it at any point?
Professor Sullivan said: Good question. It's not actually used. You could however easily use it by having new arrivals choose lines based not on the number of carts in each line but on the total number of items. That's more like what people do, right? The look at the carts in each line and do some kind of quick mental sum, and they try to choose the line with the fewest items (not just the fewest carts).
GuitarHeroLite running sample before key entry.
User 176 said: Hello,
I am having a problem where when I run guitarherolite. When I try to run it, it gives me an error at the computation of the double sample because peek has an error because isEmpty is true. This happens before I enter a key into the display. This doesn't make sense because the computation of the sample shouldn't occur before I enter a key. If it does happen before the key is entered, pluck has not been called to fill the buffer. Since the size will always be zero, because nothing is enqueued into the buffer, isEmpty will always be true. This is the problem, as I see it. If you could help me figure out what needs to be fixed, I would greatly appreciate it.
Thank you,
Justin Toothman
Lesley said: Both constructors in GuitarString should enqueue the buffer up to the capacity. Make sure you're doing this (read: loop to enqueue many things is needed).
Professor Sullivan said: I strongly recommend using (and if necessary learning to use) the debugger to see what's actually happening. Set a break point at the first line in main, and just step through your program execution. I bet you'll find the problem pretty fast.
keyboard interaction
User 546 said: I am trying to run the GuitarHeroLite and it is not working. I tried to debug to see what was happening and I realized that it is giving false for the StdDraw.hasNextKeyTyped(). So it is not entering in the "if statement". How should I interact with the keyboard? How will it receive the things I type in the keyboard? Is there a special place to type it?
Thanks!!!
Lesley said: When you run GuitarHeroLite, make sure you try pressing shift+a (A) not just 'a'.
GuitarHeroLite running sample before key entry Response.
User 176 said: Hello,
I have been using the debugger extensively. My problem is that I don't have a size when I initialize string A or B, because I am not actually enqueueing anything into the GuitarString because it is zero by default. I tried to correct this by filling each one manually with zero, to get a size, but then pluck doesn't work because buffer is constantly full, and I don't have a good way to iterate over the values of the buffer. How should I go about getting the new randomized values in buffer, i.e. I need some help on how to make pluck work with the enqueueing of the buffer.
Thank you.
Lesley said: So your buffer is full. How do you add an item? In order to add something (enqueue something), you need to remove something first (dequeue something).
GuitarHeroLite
User 546 said: The problem is:
- I've initialized all values of the buffer array to zero (by doing enqueue), but then it gives me an error (because it is Full) when doing the stringA.pluck() or the stringC.pluck().
- Then I tried to initialize to 0 and then dequeue everything so it would be empty. But like this it gives me an error when executing the sample because one of them (stringA or stringC) is empty since it was not pressed and therefore not "plucked".
What should I do? Is there a more efficient way to initialize to guarantee that these errors don't occur?
Thanks!
Lesley said: The buffer should be filled to capacity at ALL times.
This means, since pluck() wants to enqueue something, it needs to dequeue something first. Did you read the other posts that have been posted about this recently?
NullPointerException in Group Work 5
User 67 said: I continue to receive this error chain when trying to run my Store simulator...
Exception in thread "main" java.lang.NullPointerException
at CheckoutArea.indexOfAShortestQueue(CheckoutArea.java:70)
at CheckoutArea.enqueue(CheckoutArea.java:38)
at Store.simulate(Store.java:48)
at Main.main(Main.java:33)
I understand that the error means that I've asked either nothing or the wrong data type to perform some method, but I've spent many futile hours trying to find exactly where I've forgotten to declare the correct data type. Does anybody have any suggestions on how to efficiently find this?
Kyle
Extra Credit Font
User 179 said: I found a font online that looks very similar to the font used in the Guitar Hero game. How can I import it/include it as the extra credit for my StdDraw?
Lesley said: The entire point of extra credit is that you don't get help from anyone on it.
With that said you'll have to know how to try-catch file reading because http://www.cs.princeton.edu/introcs/stdlib/In.java.html doesn't support direct FileInputStream which is the easiest way to do it. I mean... This is extra credit and there are ALWAYS trickier ways, but either way you're going to have to learn something about reading in files with java and possibly concepts that aren't covered until cs201. Extra credit is a great way to explore these concepts, though!
Should you figure out how to change the font for StdDraw (the function is there once you have your font created) you can of course just include it in your .zip, assuming your .ttf isn't too big to be included in the .zip (last semester there were upload limits that my zips sometimes exceeded). If it is, just put a note somewhere that it needs to be downloaded and put it in the public_html folder on your j: drive and then link to it as people.virginia.edu/~msk3k/font.ttf with your id of course.
Also, once the assignment is no longer due (after midnight next Sunday) we'd be glad to show you how to do it should you still be interested in finding out. :)
Sound
User 179 said: I checked all my values for RingBuffer and GuitarString and they are correct, but when I run GuitarHero and try and play Stairway to Heaven, it doesn't sound like it at all. The pitches are really close and it sounds more like someone is tuning a guitar string than playing different notes. Would my error be in the frequency used to define the array values, or something else?
Lesley said: If you copy and pasted that formula from the assignment page, you'll be unpleasantly surprised when Java does its favorite integer division on it. If the notes are all the same for many consecutive keys, this would be your problem.
Otherwise make sure your RingBuffer and GuitarString output matches that on the help page.
If that's still not it, make sure you're calculating everything the SAME way GuitarHeroLite did for the 2 notes A and C.
Lab Quiz 4/10
User 336 said: For Self-Test #3, I understand how to print out the whole linked list from front to back, but I dont understand how to print it from back to front. Because then you cannot use front.next and back.next does not work and you cannot go the other direction. Help?
Lesley said: Okay, unless I'm having a brain freeze, the test asked for front-to-back. I can think of a nice recursive way to do it by passing the length of the queue decrementing... I'm not sure what Professor Sullivan wants here; I'm sure he'll clarify.
Continued problems with StdDraw
User 542 said: As was posted earlier, when using the StdDraw provided by guitar.zip, nextKeyTyped doesn't work. I took the advice and deleted StdDraw.java and imported stdlib.jar to get the project to work. But when I do that, StdDraw has an error where it cannot be resolved.
No matter what I do, nothing works, and I always have an error with either StdDraw or nextKeyTyped. I have been working trying to fix this since late last night, doing everything I could. Nothing works. I just don't know what to do.
Lesley said: I'm sorry you're so frustrated. Here is what I can offer as advice:
- Don't wait until the last minute to do assignments.
- If you add stdlib.jar to the project correctly then StdDraw shouldn't be unresolved. If you're really in the mood to be creative, make a new java class in your project called StdDraw and then copy and paste the source code from Princeton's site: http://www.cs.princeton.edu/introcs/15inout/StdDraw.java.html
Error happen when submit the file
User 518 said: I have one file that can't submit that happen before the deadline time.
It shows error in store file in database. How can I submit that one?
Xiang
Quiz Grade Discrepency
User 91 said: For lab Quiz 4, I tested my programs with robograde before I left the lab session, and it said that they were both correct. I am fairly certain that my grade indicated by robograde was a 100. However, I just checked my grades and this is not the case. My Average Array function was working, as indicated by robograde, because this is the first file that I submitted and I know that I was awarded the points before I moved on to Complex. Could this be an error?
Lesley said: Attn all: Please post these kinds of questions in "administrative help"
Problems with SETs
User 347 said: I've been working for the past few hours on building a working SET class, but I've had no luck. I just can't figure out how to do anything with it. I think if I could figure out how to add something to the SET, I could work my way through the rest. I've been working at this for way too long and I could really use some advice.
Lesley said: Please see $@FILEPHP@$/Lecture_Notes/Lecture_Notes_PDF/16_symbol_tables.pdf
I'm on page 10 of 16 looking at the slide in the bottom right where it says "implement set efficiently the same way as st but ignore value"
SET issue
User 247 said: When i go to create a set, exactly as shown in the book and on the slideshow and book site, it gives me an error... saying that "SET cannot be resolved to a type"
I understand the API for SETs, but with the inability to create one, I am having trouble practicing my code
Here is what I wrote:
public
SET<String> distinct=
With both "SET" underlined in red.
Any advice would be appreciated
class Set {public static void main(String[] args){new SET<String>();
Professor Sullivan said: SET and
Set are different identifiers
RE: Problems with SETs
User 347 said: Thanks so much. I did what you said and it worked perfectly.
Will we need to memorize how to build the different data types? I'm assuming the quiz will be closed book so I've already started committing them to memory but I just thought I'd check.
Unsafe?
User 200 said: While I compiled a program for the Lab Quiz on command prompt today, it gave me two notes:
" <program>.java uses unchecked or unsafe operations"
" Recompile with -Xlint: unchecked for details"
This was the first time I had ever tried to compile a program of this sort on command prompt. It still ran fine on the command prompt and Eclipse, and Eclipse gave me no messages at all when I compiled, but those two notes on the command prompt are somewhat worrisome. What do they mean?
Professor Sullivan said: When instantiating generic types, be sure to specify the type parameters.
E.g., not
new Set() but
new Set<String>()
KS
Art Forum Posting
User 423 said: Is this an absolute requirement because i dont use my j drive nor do i even have it on my pc plus i am also having trouble ressurecting my art.java is this posting a graded assignment
Professor Sullivan said: It's worth a little something. Visit http://itc.virginia.edu for an easy procedure to set up your home directory.
Art - Forbidden Error
User 100 said: I created the public_html folder in my J: drive and placed my star.jpg image inside this folder. When I try to go to the website, this is the error I recieve...
Forbidden
You don't have permission to access /~cen2s/star.jpg on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.8b mod_fastcgi/2.4.2 DAV/2 PHP/4.4.2 mod_pubcookie/3.3.0a Server at people.virginia.edu Port 80
Professor Sullivan said: Catelyn,
The problem is that your public_html directory is set not to allow outside access. Go to this URL and click on the link that indicates that you want to make your public_html directory accessible. Then test the accessibility of your picture from the web again. If it still doesn't work then in addition to public_html having been inaccessible, the picture (JPG) file itself is inaccessible. On this same web page, click on the link for your public_html directory. In the next box down you will then see the files
inside this directory listed. Click on the radio button that makes your JPG file visible, then click on the button to submit your changes.
http://www.people.virginia.edu/homedirKS
Lesley said: This has worked at office hours tonight:
- Go to public_html on J:
- Copy the image by pressing ctrl+c and then ctrl+v (it will make a new image called "Copy of..."
- Delete the old image
- Rename the "Copy of..." image to what you want it to be called (mst3k0.jpg or whatever)
- Magic it works! (Oh, ITC)
Alternatively if you run your Art.java and then go to File-save and name it whatever.jpg there instead of the way Professor Sullivan described, and then copy and paste this image to J:, it doesn't seem to be doing the forbidden thing.
SortedList Question
User 320 said: The first matter is the for-loop which prints your list. At first I used Nodes as parameters like you guys suggested, but in the end I found it less cumbersome to just make an int "count" (which recorded the number of Strings in the list) and used that to give my for-loop integer parameters. Is this alright or are you guys going to fail me when the quiz comes around?
Secondly, my code seems to print out of order. For example, instead of printing: "One: Hello" my code prints:
"HelloOne: "
I think I know why this is, but I don't see any way to correct the problem without changing the main routine.
Thirdly, how do I know if I'm printing in the right order. The last section of the main routine enqueues "Good" "Morning" "Vietnam" and my code prints "Morning" "Vietnam" "Good", which I believe is correct based on the info in the quiz section.
Professor Sullivan said: David,
No, we'd like you to write the for loop properly. Here's are some hints: start off the for loop with temp = head. Use a boolean value that's false when you enter the loop to indicate that you haven't yet started to process the list (executedthe loop). Set it to true inside the loop to indicate that you have started traversing the list. Terminate the for loop when (a) you've already started travering it, and (b) temp == head, that is, when you've gotten back to the beginning.
As for your output it's clearly not correct: the words must be output in ascending alphabetical order. I suspect that your words are not being inserted in the list in the correct order. Consider using the debugger.
KS
Lesley said: Isn't it easier just to use a do...while loop since you check to make sure first is not equal to null anyways?
Professor Sullivan said: Do you mean like this?
do {
// something
} while (temp != head);

Kevin S
Professor Sullivan said: Or in more detail something like this?
temp = head;
do {
// something
temp = temp.next;
} while (temp != head);
KS
Lesley said: I mean, it's just less complicated to do it that way, and this situation is kind of the entire purpose of even having do..while...right?
Also, don't forget to encase it with if (head != null) {...}
Professor Sullivan said: Well these are pretty good hints for anyone who's monitoring this forum! --KS
Saving Graphics As JPG File
User 282 said: In the command prompt, I'm typing "java Art > picture.jpg" but the JPG file created has nothing in it. How do I save my graphics as a JPG?
Professor Sullivan said: Please search the forums for instructions. In a nutshell, add a few lines of code to your Art.java program to tell it to save whatever image you produce to a JPG file. Thanks!
Node references in a linked list
User 200 said: I'm a little confused about how references to Nodes work in a linked list. Say you have Node A and Node B, and A.next = B. So A becomes linked to B. What if you created another Node called C and set C equal to B? Would A.next also equal C by default, or do you have to specifically type that line of code?
Lesley said: You know, the easiest way to get an answer to your question would be for you to write a Java class and test it out. :)
Do we have to use a "for" loop for toString()?
User 71 said: (of course for Labquiz6)
if we want to use a for loop, I argue that we may need to create another instance variable to store the amount of the string inserted, or I can use a while loop and stop when the next node is smaller than the present one?
Thank you
Professor Sullivan said: You do need a loop.
You may use any looping construct that you want.
You will know that you have reached the last node in a non-null circular list when the next field of the node you're looking at is equal to the head of the list.
KS
Problem with SortList Program in the class
User 270 said: I tried to test the program with this code in the main:
SortedList A = new SortedList();
A.insert("e");
A.insert("g");
A.insert("t");
A.insert("b");
A.insert("a");
A.insert("s");
StdOut.println("A: " + A);
The output in the console is:
A: a b s
which is wrong.
I think there is a problem in the part of the code dealing inserting before the head.
Professor Sullivan said: We hung around and debugged the code. Try debugging it. Where's the error? Go ahead and fix it. Great way to learn. The program is less than 20 lines of code. Don't be afraid to analyze it. A big part of programming learning how to reason about the behavior of a given program.
Adding
User 215 said: Are we allowed to add a Tail node?
Professor Sullivan said: Try to do without for this exercise.
SortList "Hello There Friend" Problem
User 191 said: I don't have a laptop so even though I stayed until the end to debug the program today in class something was still not working in it when I typed it in at home but I can't figure out why. I debugged and for some reason when it's inserting Hello, There, and Friend in that order it's skipping over There. I don't see why that would be any different than just entering Hello, There which it has already done in that order. Any ideas?
Professor Sullivan said: What do you mean by "skipping over"?
Fixed it
User 191 said: I figured out a way to fix it, but thank you.
Professor Sullivan said: Great! It's fun to get independent.
What should be printed out for lab quiz 6?
User 516 said: What are we supposed to print out? Is this enough?
Two Inserted Out of Order: Hello There
Three, Last Added at Head: Friend Hello
Three, Last Added in Middle: Hello Over There
Three, Last Added at End: Good Morning Vietnam
Professor Sullivan said: The main routine inserts strings into lists then prints out the lists (which should be in sorted order).
Head
User 343 said: I'm confused about where the "Head" is located in lab quiz 6. In the diagram, Head looks like just a node that points to the first item in the list, but i'm not sure if Head itself IS the first item in the list. For example, should the last item in the list (using something like last.next) point to Head or should it point to the first item in the list, with head just being some node off to the side that isn't part of the circular list?
This also comes up when printing out the list of items. Would you print out Head and then all of the items after it, or would you print out the first item (which head is pointing to) and then all the subsequent items?
Sorry, i'm having trouble wording this. Basically, is Head part of the circular linked list or just a reference to the start of the list?
Professor Sullivan said: Head is a variable that holds a
reference to the first node in the list (or null if the list is empty). The last node in a non-empty list also holds a
reference to the first node in the list.
SortedList output
User 259 said: My output is--
Empty:
One: Hello
Two Inserted in Order: Hello There
Two Inserted Out of Order: Hello There
Three, Last Added at Head: Friend Hello
Three, Last Added in Middle: Hello Over There
Three, Last Added at End: Good Morning Vietnam
Clearly, my "Three, Last Added at Head: Friend Hello" is wrong. What could possibly be wrong with my code?
Professor Sullivan said: There's an infinite set of possible answers to your question. Use the debugger to figure out which one is the right explanation.
SortedLinkList value ThreeA
User 176 said: Hello,
I'm studying for the lab quiz, and I am having a problem with the output for threeA. You are inputing hello, there, and friend in that order. It should print "friend hello there", but it prints "friend there hello". I've used the debugger extensivley and worked through the logic on paper, and I can't get it to work out. How can I have this problem when twoA and twoB both work, since they correctly sort hello, there in order and out of order?
Thank you
Professor Sullivan said: There are two distinct possibilities: (1) your decision logic is subtly wrong, (2) the actions that you're taking after making a decision (i.e., the way that you are changing the links around) is subtly wrong. The first thing to do is to make sure that your code is working correctly for the first two insertions. That should be relatively easy to check using the debugger, and "opening up" the nodes to see what they contain, as we did in class. The next thing to check is that you code is correctly deciding which case to handle on the third insert. Finally, once you have confirmed that the right case is being handled, you need to check to see that it is being handled correctly.
NullPointerException
User 404 said: I keep getting a NullPointerException when I try to insert a node into the linked list. For some reason my temp node = n.next is null. I can't understand why my list is not circular, because I think i've done most everything correctly.
Professor Sullivan said: Use the debugger to figure it out, please.
JPG file
User 240 said: How do you convert the recursive picture to a JPG file so that it can be submitted?
Lesley said:
- Run your recursion program
- You'll see a File menu with an option to save when the StdDraw window comes up
- save it as "whatever.jpg" with the quotes (the whatever can be your id with a number after it or whatever the requested convention is)
I know there was another way Professor Sullivan mentioned somewhere on this forum but this works just as well.
debugger problems
User 77 said: I've been trying to use the debugger to find problems in my various programs, but it doesn't seem to be working. When I run the debugger on fully functional programs (i.e. no errors when regularly running it), the debugger reaches certain parts where it will just say "Source not found" and it gives me a button to "Edit source lookup path." If I use f6 at the previous point, it doesn't give me this error, but pressing f5 (step into) gives me this, and it tends to be at points inside a constructor. If I just press f5 again, it (eventually) steps out of it, only to give me the same error later. Am I using the debugger incorrectly, or is my debugger somehow corrupted? Thanks.
Ascending order
User 41 said: Perhaps this is a stupid question, but i'd rather be sure...
Does 'ascending' mean:
'A'->'B'->'C'-'D'
or
'D'->'C'->'B'->'A'
Professor Sullivan said: Going up. A, B, C, D. --KS
Lab Quiz 6
User 489 said: I am a 101E student and whishing I wasn't
After reading Chapter 4 in the book and going over the class slides for Stacks.Linked List and Queues I still have no Idea What i am doing .
Is there any other Material that I can go over to try and understand this
ie. Java for dummies????
Professor Sullivan said: Hey Grant,
Figuring out linked structures is a
really important step on the way to knowing about programming. It's not easy, but once you get past this step you'll be well on your way to understanding not only linked lists but a whole lot more (e.g., binary search trees).
A great resource for learning more is Google search. I just typed in "tutorial linked list java" and came up with many pages. Here's one that was near the top of the list. At first glance it looks pretty good.
http://www.mycsresource.net/articles/programming/data_structures/linkedlists
Type in the code and study it and run it. Just like you can't learn to play piano by reading piano music, so you can't learn to program by reading code. You have to
play (with) it. Don't be afraid to roll up your sleeves and
write code. Oh, you
must also learn to use the debugger. If you can't and there's something wrong with your code you'll never figure it out. But with the debugger it will often be quite clear quite quickly where things are going wrong.
Posting Artwork
User 404 said: I have done everything I can to post my JPG recursive artwork file. My file is a JPG in the public_html subdirectory of my Home Directory (J:), but when I try to access it on the internet it says that it is Forbidden. What do I do?
Lesley said: #1013
Assignment6 neareastInsert
User 71 said: When I try to test it with the test file, it won't stop running.
And when I debugged it, I cant move beyond after it the while loop found out there is no input, and the program will stop at that line, the debugger said "Thread [main] (Stepping)" instead of normally (Suspended).I am totally confused.
I know that my code for point is right, for Tour is right, and the algorithm part is might be right because there is one time (only one time) after I terminated the program it gave me the right result (I don't know why).
Is it because my distance method is still running and I never wait long enough for it to finish?
Thank you.
Lesley said: This is a problem we encountered at stacks tonight. I'm not sure why it worked last semester for me and not this semester for you all (maybe it is an Eclipse thing - I use the command prompt; maybe it is a stdlib update thing).
Professor Sullivan said: Cut and paste the input file into the Console window then be sure you hit "Enter" and then hit ^Z or ^D to signal end of file. The input procedure needs to see that new line at the end of the file or else it doesn't recognize end of file. Please let me know if this works for you.
might be a stupid question
User 71 said: I think that for loop and while loop both check before they run, is there a loop that run before check?
is do while one of them?
Thank you.
Lesley said: Yes, do..while is a loop that will run and then check.
reply to Lesley
User 71 said: So I guess what you suggested to do is to run the program in CMD instead of Eclipse?
Thank you.
Smallest Insertion
User 375 said: I have nearest insertion working great. However, I am having trouble with smallest insertion.
Given points A, B, and N. A and B being linked and N going between them.
Is it enough to minimize a distance (A -> N -> B) for all possible A->B combinations for Smallest Insertion? Or do I need to calculate the the distance for each possible tour combination and minimize that.
Basically, will these two methods produce the same results. (I would test it, but I have having considerable difficulty convincing myself that the code I have for the second approach works like I want it to.)
Thanks,
alan
Lesley said: The tour distance is equal to the sum of the distances between all the points
dist = 1->2, 2->3.... m->1 where m is the last Node of course
now consider a->n->b... If n is inserted, the old distance is 1->2....a->b, b->b.next.... m->1 and the new distance is 1->2....a->n, n->b, b->b.next...m->1
dist + increase = new distance = 1->2...a->n, n->b, b->b.next...m->1 but you can cancel out all the terms that are in dist, so
(a->b) + increase = a->n, n->b (because a->b isn't in the new distance)
so the smallest increase will be the smallest a->n + n->b - (a->b) thus it is not necessary to calculate the entire tour distance every time.
As you can see, minimizing just a->n, n->b is not the same as the smallest increase.
Hope this helps.
smallest insertion
User 71 said: my smallest insertion works fine for tsp10 and 100, but fast enough for above, and it takes forever for the germany one and the usa one. Is that normal or is there something wrong with my algorithm?
I guess that go over the tour and remember each distance of them and then compare is a nightmare for large N, but I just cant think otherwise.
Thank you.
sorry for the previous unthoughtful post
User 71 said: now when dealing with N as big as 10 thousands, my smallest insertion needs about 20secs, is that fast enough?
Exam 3
User 71 said: " ○ how can you win $1,000,000 (by doing something we've talked about in CS101)?
○ how can you win $30,000 (by doing something we've talked about in CS101)?
" they are in the study list for exam.
I am just wondering
are those thing also mentioned in another class?
Thank you.
Lesley said: Did you even read this? #1067 If you go to that article the answer is there. At least the $1-mil one. Which if you had just googled you also would have found.
Did you know finding the solution to any given Freecell game is also NP-complete?
Professor Sullivan said: Hi Jun, These prizes are mentioned in the class slides. --KS
Professor Sullivan said: Sudoku generalized to arbitrary-size grids is also NP-complete. That's to say, the time it takes to solve a Sudoku game on a grid of size NxN exponential in N and moreover if an efficient solution is found then one has found an efficient solution for any problem in NP!
[1] 0 1 0
User 449 said: Hey,
Why is the [1] in brackets in the sample addition problem for Binary Adder?
-Joel
State machine starting point
User 449 said: Hey,
Does a Turing machine begin in the lower left state by convention, or how can you tell where it begins in general?
-Joel
Professor Sullivan said: The starting state is specified as part of the TM definition. In graphical notations, you'll often see an arrow "coming from nowhere" into one of the states. That's the starting state.
assignment 6
User 235 said: after testing the show method, I got the following result. What is the last line about? How can I erase that?
(100.0, 100.0)
(500.0, 100.0)
(500.0, 500.0)
(100.0, 100.0)
Tour@14318bb
Lesley said: Tour t = new Tour();
System.out.println(t);
that should replicate your error.
Also try int[] a = new int[5]; System.out.println(a) or similar with any other object....... Remember how objects are references? That should help you figure out what exactly it is doing.
Turing machine jar file
User 200 said: I'm a little confused about how to get the turing machine started on my computer. Either that or my computer's corrupted. I've downloaded the turing.jar file twice, and both times when I try to open it on Eclipse, it opens up a notepad file with a bunch of garbage. I then tried adding it as an external library like we do with stdlib.jar, but all of the files give me a message that says "the jar file turing.jar has no source attachment." What am I supposed to do?
User 14 said: This particular .jar file is an executable jar. Save it somewhere on your machine and then double-click it to run it like you would a .exe file.
usa13509 with insert smallest
User 305 said: my insert smallest and insert nearest work fine for all the standard data sets except insert smallest won't output anything for usa13509, but insert nearest does, i've run it for about 5mins and still nothing. I'm not doing anything elaborate just inserting the new point after going through the existing list and finding the shortest distance, can someone point me in the right direction.
nevermind on "usa13509 with insert smallest"
User 305 said: answer to my problem is already posted
TSP in the Command Prompt
User 375 said: I think that I have my TSP solutions correct but I cannot get my program to run from the command prompt.
I have no trouble compiling Point.java but when I try to compile Tour.java it complains that it cant figure out what a Point is.
thanks,
alan
Lesley said: Are Point.java and Tour.java in the same folder?
Did it work in Eclipse?
You can always come by office hours if neither of these two questions help you find your answer.
Weird Problem: InsertNearest
User 320 said: For some reason, in the InsertNearest.java file, the problem stops after the while loop.
while
Point p =
tour.insertNearest(p);// print results
System.
tour.show();
Is what the code you give us looks like. For some reason, the code never reaches the println and tour.show portion.
Just for experiment, I changed the loop to this:
int
Point p =
tour.insertNearest(p);
i++;
}
The while loop ends after this and I get the correct output. So I believe the while loop has some problem with StdIn.isEmpty() on my computer. Obviously, I cannot use this code because it only works for 10 cities.
Any idea what the problem might be?
i = 0;while (i!=10) {double x = StdIn.readDouble();double y = StdIn.readDouble();new Point(x, y);out.println("Tour distance = " + tour.distance());
}
(!StdIn.isEmpty()) {double x = StdIn.readDouble();double y = StdIn.readDouble();new Point(x, y);
Lesley said: #1085
Basically I have no idea why Eclipse hates this so. I think it works fine in the cmd prompt.
Why is mergesort a poly-time algorithm?
User 49 said: Mergesort is defined as a poly-time algorithm in one slide. However, it is actually in the form of NlgN as opposed to aN^b.
I was wondering if the poly-time algorithm here was defined in a broad sense, which means as long as the algorithm is efficient (since NlgN is smaller than N^2), it is called poly-time?
Professor Sullivan said: Yes, that's right. P is the set of problems for which there are algorithms for which growth runtime as a function of input size is
bounded (not necessarily tightly) by some polynomial.
"ILP is not likely to be in P"- dont understand how to prove
User 516 said: I partly understand that ILP involves maximizatio problems and it is because of this fact that this is a hard problem and therefore NP complete. But isnt more explanation needed?
Professor Sullivan said: (1) ILP is in NP -- how do you know this?
(2) An efficient solution to ILP would give and efficient solution to 3-SAT, insofar as there is an
efficient (polynomial time) reduction from 3-SAT to ILP. That is, any given instance of 3-SAT can be translated into an equivalent problem in ILP, such that a solution to that ILP problem provides an answer to that particular 3-SAT problem. So if there exists an efficient solution to ILP then there exists an efficient solution to 3-SAT. But there is no efficient solution to 3-SAT unless P=NP so there's not likely to be an efficient solution to ILP.
Does "accepting state" in a FSM mean "Yes"?
User 254 said: Does "accepting state" in FSM mean "Yes"?
And how can I distinguish if a given string can be recognized by a FSM?
Professor Sullivan said: You can tell if an FSM accepts a string by determining whether the FSM is in an accepting state after the string has been processed.
draw() in Point.java
User 276 said: In the list of the API for Point.java, it says that we need to create a function called draw() that will draw the points with StdDraw. Is this even necessary? I don't end up calling draw() at all in Tour.java; I only use drawTo().
Or would you like it if we plotted all of the points on StdDraw first,\ and then plotted the path connecting the dots, even though this would slow down the runtime?
Sub-directory on J-drive
User 240 said: How do you add the sub-directory: J:\public_html (in which we're supposed to save our JPG file)?
Lesley said: ...This subdirectory already exists. I know because I went to
http://people.virginia.edu/~jch2t/ which means that it exists and there's a file called home.html there.
Halting Problem
User 49 said: Is the halting problem incomputable because we cannot write a function that can be used universally to all given functions and inputs to determine whether f(x) results in an infinite loop?
I mean for one particular function and input, we may be able to write a function to determine if f(x) will halt. Rite?
Professor Sullivan said: Correct. There is no algorithm that can correctly distinguish strings that encode programs that halt from strings that encode programs that do not halt.
Intractable=No poly-time solution? Or=in NPC?
User 161 said: There is a problem in the review guidance.
how does one prove that a given problem is intractable (unless P=NP)
Does "intractable" mean "no polynomial time solution"? If it does, we could not prove a given problem is intractable, right? Otherwise, we could prove NP!=P.
Or does intractable mean that this problem is in NPC set? Then we need to prove 3-sat could be reduced to this problem.
Thanks a lot!!
Professor Sullivan said: There's no problem in the review guidance. A problem is intractable if there's no known polynomial-time solution. All of the problems in NPC are intractable in this sense. They are inherently intractable unless P=NP.
Partition problem:)
User 161 said: Q: what is the problem known as PARTITION? is it in P?
Is this the right answer?
A: Partition is in NPC, but we don't know whether it is in P.
Thank you!
Professor Sullivan said: There are lots of problems in NPC that might or might not be in P -- though all the evidence suggests that they're not in P. Do a little research. There's lots of information about PARTITION out there.
Problems in NP but not in P or NPC
User 49 said: In the study guide, there is a question asking if there are important problems known to be in NP but not known to be in P or in NPC.
I am confused about how I should understand it.
Does it ask if I know the problems belonging to NP but not yet proved to be in P or NPC or if there exist problems truly lie outside P or NPC(which we know no one has proved...)
Professor Sullivan said: The question asks whether there are problems known to be in NP but not known to be either in P or in NPC. There definitely are problems outside of NPC -- i.e., harder than those in NPC. You actually know of at least one such problem: It is *much* harder than 3-SAT. In fact, it's so hard it can't be solved!
optimal 1000?
User 442 said: just for reference, I was wondering what the optimal tour was for the 1000 cities
DFA's and Turing Machines
User 543 said: What's the difference between DFA's and Turing Machines?
Is it that DFA's mainly recognize patterns and do pattern matching whereas Turing machines actually compute sums, products, etc.?
And I know that it is possible for a Turing Machine to run forever without ever reaching one of the terminating states. Does this hold true for a DFA? Can it run forever?
User 167 said: A DFA is a state machine - it has a number of states, and for each symbol that it gets as input it chooses a new state based on the current state.
A Turing Machine consists of a state machine AND a read/write tape. It reads the current symbol from the tape, and based on that symbol and the current state it's in, it chooses a new state, a new symbol to write on the tape, and a direction in which to move the tape head.
Thus, you can think of a DFA as a Turing Machine that can't change what's written on the tape, always moves the head to the right, and stops when it reaches a blank.
A DFA can't run forever because it will always reach the end of the input and stop. By contrast, a Turing Machine can CHANGE the input tape, and can also move the tape head backwards, so there is no guarantee that it will stop.
Please read the book for details:
http://www.cs.princeton.edu/introcs/73fsa/
http://www.cs.princeton.edu/introcs/74turing/
Also, you might look at wikipedia:
http://en.wikipedia.org/wiki/Deterministic_finite_state_machine
http://en.wikipedia.org/wiki/Turing_machine
Or just use google.
tsp answer files
User 200 said: What do we use to open the .ans files (the ones with the answers to tsp 10 for nearest, smallest, and the optimal solution) in the tsp directory?
User 14 said: They are just text files, so you can use your favorite text editor to open them. Or if it makes you feel better, you can just rename them from whatever.ans to whatever.txt
Lesley said: Please take initiative before asking us these kinds of questions. Trying to open this file with [word|notepad|eclipse|internet explorer|etc] would have yielded positive results.
The NP-Complete problem
User 320 said: All problems in NP-Complete are supposedly different variations of one universal problem which is the hardest in NP. Has anyone ever been able to isolate and put into words what this "universal problem" is? Or do we have to just infer it from the variations in NP-Complete?
Professor Sullivan said: We know the problem through its many equivalent formulations (3-SAT, partition, etc). Informally it's the problem of finding a solution in cases where (1) it's easy to recognize a solution, (2) there is a super-polynomial number of candidate solutions, and (3) there's no way in general to narrow down the search
enough to get a polynomial time solution.
Professor Sullivan said: Oh, and that any other NPC problem is reducible to the given problem.
But of course I'm not saying anything more than you already know.
Examples of NP problems not in P nor in NPC
User 323 said: Can someone give me examples of search problems in NP, but not in P or NPC? I'm using the Internet for this but can't find anything. Thanks.
Tomu
Replication Operator
User 148 said: The book says "
Replication: the replication operator enables us to specify infinitely many possibilities. For example, the regular expression
ab*a matches
a,
aba,
abba,
abbba, and so forth. Note that 0 replications of
b are permitted. " But does it mean it matches aa, not just a? Or does it include both?
Professor Sullivan said: ab*a does not match a. I would read this as follows: "a followed by zero or more b's followed by a" If the book says that that RE matches a, it's wrong.
TSP Checking
User 375 said: Under "Help:"
For
usa13509.txt we get distances of
77449.97941714071 and
45074.77692017051 for nearest insertion and smallest insertion, respectively. For
circuit1290.txt we get
25029.790452731024 and
14596.097124575306.
for circuit1290.txt I get the expected answer in both cases. For usa13509.txt, my results are off by a few units (Slightly better for nearest, slightly worse for smallest). Will this be a problem? Are these solutions simple guidelines or do we need to reproduce them exactly?
thanks,
alan
User 167 said: A number of people seem to have this problem.
The issue is that apparently Eclipse has a limit to how much you can paste into the console. You get seemingly random numbers because Eclipse truncates the data at apparently random points; if it ever happens to truncate between an x and a y, then you'll get an InputMismatchException from StdIn.
The only solution that we know of is to run from the command line - if you read input directly from a file, then you don't have to worry about it getting cut off early.
Error when running Tour
User 323 said: When I run my Tour program with usa23509.txt, I sometimes get an error saying the following:
Exception in thread "main" java.util.NoSuchElementException
I've noticed that this doesn't happen when I run the circuit1290.txt or any of the other text files. They work perfectly. Can someone tell me what this error means and how to solve it?
Checking TSP
User 316 said: I am having a problem similar to Alan's: #1185 . All of my answer match the given values except when I run usa13509. With the usa13509 text file, sometimes I get the given answers, sometimes a "NoSuchElement" exception, and sometimes wildly varying results. Thanks in advance for your help.
Matt
Pre made aspect of TSP
User 423 said: I am having a subtle error when running some of the premade programs that we were able to download. I am certain that my heuristics are correct because i solved them by drawing them but when i run the program that should just output the distance gets stuck at the end of the while loop. As soon as there isnt any data in stdin the loop should end but instead it says [toString() unavailable - no suspended threads] but this is only when i debug it and y is it even calling to string before it outprints the distance, because that takes place afterwards.
Lesley said: Did you try pressing ctrl+z at the end of the input like Professor Sullivan suggested?
User 167 said: Hit ctrl-z (ctrl-d if you're on a Mac, and I think ctrl-c if you're running from the command prompt) to send an End-Of-File (EOF) signal. Otherwise, it doesn't know that it's reached the end of standard input, because you could write more.
individual assignment 6
User 207 said: for this assignment, we have 2 java programs to submit. I am wondering for the Point.java, should we write one by ourselves or just use the one provided in the help?
thanks
Lesley said: The one provided in the Help does not compile properly unless you remove some of the extraneous functions. I think.
Zip file wrong
User 120 said: I just wanted to say that for my extra credit on the TSP problem, I didn't zip the right files, so it doesn't work. But the results are in my readme file. Whoever grades it can just skip that part. Sorry.
Readme
User 154 said: Ooops, I seem to have submitted the wrong readme.txt at the last minute. My fault. Is there anything I can do about that? If not, that's fine, my mistake submitting at the last minute... :(
Ungraded Quizzes
User 423 said: I was wondering when we were going to receive grades for our quiz 6, our art, and our quiz 7.
Big Integers
User 531 said: I am fooling around with some java programs of mine, and I want to see how they work with very large integers. They work ok for anything I can fit into an Int or a Long, but I was wondering if there was a data type i could import or implement to examine REALLY big integers.
Lesley said: http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html
Posting the artwork
User 323 said: I use a mac, and I don't really understand the instructions given by Professor Sullivan. Can someone help me with this?