Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
JulianD
Dec 4, 2005
I'm working on a small project, and I've hit a wall. I'm supposed to write my own class (named Student), whose constructor has a number of parameters: a first and last name, three regular test grades, three homework grades, and a grade on a semester final. Using the graded information, I'm supposed to calculate the semester average for that student, then use that average to determine the letter grade.

Now, I have to read all the information for each student from a file (their names and graded information), store the information for each student in its own instance of the class (which I think means I'd have to store it in my constructor), call the method I use to calculate the semester average and letter grade, and then take all of that information for each student(the original attributes, the semester average, and letter grade) and store it as its own element in an array of instances of my class Student.

From there, I have to call another method to display the attributes of each element of that array - that is, I have to call a print method for each instance of Student that I stored in the array.

I'm having a couple of problems with this. I've never had to read data from a file into an instance of a class, so I don't know where to begin using FileReader to read all that data into my constructor. I also don't know how I would make sure that once it reaches the end of a line in my data file, it would proceed to put the next line's data into a new instance of my Student class.

I have no problem writing the methods to compute the semester average and to display the data from my constructor, but I'm confused about the array. I'm computing the average and letter grade separately from the constructor, but I still have to take that information, on top of what's in my constructor, and wrap it all together so it can be just one element in my array. I had thought to start like this:

code:
public static void main(String[] args)
  {    
    Scanner console = new Scanner(System.in);
    
    int classSize, i;
    
    System.out.println("How many students would you like to display data for?");
    classSize = console.nextInt();
    
    System.out.println("Please type the precise file name containing your student data as a .dat location.");
    dataLoc = console.next();
    
    Student[] studentArray = new Student[classSize];
    
    Scanner inFile = new Scanner(new FileReader(dataLoc));
    
    // Start while loop
    while (inFile.hasNext())
    {
      for (i = 0; i < classSize; i++)
      {
        studentArray[i] = inFile.nextStudent();
      }
    } // End while loop
  } // End main method
However, I know that's going to present a problem; the information in the file I'm reading from is of type String and Int, so I know I can't use inFile.nextStudent(). However, I can't figure out a way to use the FileReader to read differing data types (String and Int, in this case) and store them to an instance of Student, then make sure that a new instance of Student is created to take the next line of information, and so on until I reach the end of the file. This also won't solve the problem I'm having of how to take the computed semester average and letter grade and combine that information with the appropriate instance of my Student class so that I can put it into the array.

I'm really lost here. Any light you all could shine on this would be greatly appreciated. If there's anything I should clarify, let me know and I'll do my best.

Adbot
ADBOT LOVES YOU

Outlaw Programmer
Jan 1, 2008
Will Code For Food

JulianD posted:

I'm working on a small project, and I've hit a wall...

The first step is to write the constructor for your Student class by following the spec provided:

code:
public Student(String first, String last, int test1, int test2, int test3, int hw1, int hw2, int hw3, int final) { /* */ }
Assuming your file format looks something like:

code:
John,Smith,70,80,90,70,80,90,100
What you want to do is read this file 1 whole line at a time. Each line represents as student "record." Once you have the whole record, you can do something like:

code:
String[] data = record.split(","); // split on commas


That will cut the record into individual pieces. So, that data array be of size 9, with data[0] being the first name, data[1] being the last, etc. You can convert Strings to ints with the Integer.parseInt(String) method.

Hopefully that will put you on the right track.

Ghotli
Dec 31, 2005

what am art?
art am what?
what.
I wrote a ton of Java in high school and college, and moved into PHP and Ruby on Rails when I took the Webmaster position at the university. I'm looking to start interviewing for developer positions soon and I want to brush up on some enterprise java technologies. Thus far I've been reading the documentation for Spring and Hibernate. Should I also look into frameworks such as Struts or Tapestry or are they going out of style?

I'd also like to start playing around with a full blown application server. Tomcat is just for servlets, right? Are there any other free app servers worth fooling around with? Is glassfish worth using yet?

covener
Jan 10, 2004

You know, for kids!

Ghotli posted:

Tomcat is just for servlets, right?

Geronimo is the attempt at a full-fledged application server by assembling the various OSS components.

zootm
Aug 8, 2006

We used to be better friends.

covener posted:

Geronimo is the attempt at a full-fledged application server by assembling the various OSS components.
Also Sun's GlassFish is a full open source app server, using a servlet container based on Tomcat (they added a component called Grizzly for network handling which is apparently pretty good).

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost
Struts and Tapestry are still wanted but are unlikely to be used in projects getting off the ground these days. Weblogic, JBoss, and Tomcat are still kings for "enterprise" application servers IMO. Never got a request for anything else besides Apache from my customers. For educational purposes, Stripes is certainly worth a shot - it looks quite fun, which is frankly a bit rare in the Java world to me.

Is there any professional value besides educational ones in messing with Glassfish? I don't know of any prominent organization that's used GlassFish to serve their applications, but maybe I'm missing someone huge that's used it. It may turn out like Django in the Python world though and take off after another year or so.

As far as jobs, it looks like few give a crap about your Java skills until you've spent 3+ years with Spring, Hibernate, Jboss, Tomcat, J2EE-specific frameworks, and a major DB or two. Otherwise, it's purely entry level it seems.

zootm
Aug 8, 2006

We used to be better friends.

necrobobsledder posted:

Is there any professional value besides educational ones in messing with Glassfish? I don't know of any prominent organization that's used GlassFish to serve their applications, but maybe I'm missing someone huge that's used it. It may turn out like Django in the Python world though and take off after another year or so.
Sun are pushing it, basically. It's still kinda early days but its capabilities and quality look to make it a really good one. I've never worked in a shop which uses "full" Java EE, though, mostly just servlet containers suffice (and to be fair, out-of-the-box Tomcat isn't the greatest servlet container on earth). It's got a lot of nice features for development as well (probably the best on-the-fly code reloading I've seen in v3, with hooks into Eclipse and NetBeans).

Version 3 isn't out yet (it's being timed to coincide with the new servlet spec etc. I think) but I imagine they'll start pushing it harder with that one. Having used JBoss and all that sort of thing I'm of the opinion that things can only get better with app servers for people who use them though.

necrobobsledder posted:

As far as jobs, it looks like few give a crap about your Java skills until you've spent 3+ years with Spring, Hibernate, Jboss, Tomcat, J2EE-specific frameworks, and a major DB or two. Otherwise, it's purely entry level it seems.
A lot of people say that but I would urge anyone who's looking and has any experience whatsoever with these things to just go ahead. In any job worth having people are looking for general skills rather than tech experience. Those technologies are all pretty trivial to learn and really requiring experience in them is probably a point against the employer.

That said most people looking for that specific skillset might not have an interesting jobs going...

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
There are also a large number of non-web-related Java programming jobs out there — right now, I'd say it's probably the major cross-platform language for large projects (do not read this as an endorsement of Java over your pet language). Whether there are open non-web-related Java programming positions is, of course, a question about the economy and not languages.

Lord Wexia
Sep 27, 2005

Boo zombie apocalypse.
Hooray beer!
Not a CS major but in a CS class that is currently kicking my rear end. My latest set of assignments has been to create our own scanner and iterator classes. Unfortunately each one builds on the next one and we haven't gotten any feedback on our older stuff so I think I've hit a wall with this project.

We've been designing classes that scan a string and isolate words and numbers within the string. The trick is, every token was separated by exactly one space. So to do this, I've been finding the spaces and just storing what's between the spaces. Now we have to scan a string that can contain "double quote characters". It also says that these characters are preceded by a backwards slash. So for example, if the input was:

code:
"assign 50 \"?<>&hq \" to x y "
Then the output would be:

code:
assign
50
"?<>$&hq "
to
x
y
So my question is, how should I think about this double quote character and can my space-character oriented method still work? Or am I going to have to re-write this?

I don't mean for this to be a "help me with my homework" post but if anyone has any tips on where I should move from here, I'd really appreciate it.

ynef
Jun 12, 2002

Lord Wexia posted:

So my question is, how should I think about this double quote character and can my space-character oriented method still work? Or am I going to have to re-write this?

I don't mean for this to be a "help me with my homework" post but if anyone has any tips on where I should move from here, I'd really appreciate it.

I'm going to assume that you have to do all this stuff on your own and not just rely on some smart other tool or library. Your space-based approach may be rewritten to handle this case as well.

There are at least two solutions. One which is more simple but specific to your current problem, and one which is more general. A really simple, but hard to modify and adapt solution would be as follows: simply keep track of whether you are within quotes or not using a Boolean variable. If you are, then all characters you read (until you encounter the closing "-character) should be appended to your current partial result. If you are not within quotes, then continue like you have before with your space-based parser.

A nicer approach would look as follows in pseudo code.

code:
String readUntil(Datasource source, Character[] stopCharacters) {
  String result = ""
  done = false
  while (!done and source.hasNext()) {
    Character c = source.nextCharacter()
    if (c in stopCharacters) {
      done = true
    } else {
      result.append(c)
    }
  }
  return result
}
Then just change what the array of stopCharacter contains based on context (within quotes or not). Keep calling the method until the data source is depleted, and store the strings it gives you somewhere (like in a List<String>, I suppose).

If you would implement the second solution, you obviously need to perform more error checking and stuff. In particular, you might want to throw the empty string away. ;)

ynef fucked around with this message at 18:15 on Feb 11, 2009

Boo This Man
Mar 25, 2008

I need to do a basic loop that will read a list of exam scores given as integer precentages in the range 0 to 100. I need to display the total number of grades and the number of grades in each letter-grade category.

Mill Town
Apr 17, 2006

Logostomp posted:

I need to do a basic loop that will read a list of exam scores given as integer precentages in the range 0 to 100. I need to display the total number of grades and the number of grades in each letter-grade category.

That's a great homework assignment. You got a question to go with that?

Boo This Man
Mar 25, 2008

Mill Town posted:

That's a great homework assignment. You got a question to go with that?

I've got the input working. Here's the question.

Write a program to read a list of exam scores given as integer percentages in the range 0 to 100. Display the total number of grades and the number of grades in each letter-grade category as follows: 90 to 100 is an A, 80 to 89 is an B, 70 to 79 is an C, 60 to 69 is an D, 0 to 59 is an F. Use a negative score as a sentinel value to indicate the end of the input. (The negative value is only used to end the loop, so do not use it in the calculations.). For example, if the input is

98, 87, 86, 85, 78, 73, 72, 72, 70, 66, 63, 50, -1

the output would be:

Total number of grades = 14
Number of A's = 1
Number of B's = 4
Number of C's = 6
Number of D's = 2
Number of F's = 1

Mill Town
Apr 17, 2006

Logostomp posted:

I've got the input working. Here's the question.

Write a program to read a list of exam scores given as integer percentages in the range 0 to 100. Display the total number of grades and the number of grades in each letter-grade category as follows: 90 to 100 is an A, 80 to 89 is an B, 70 to 79 is an C, 60 to 69 is an D, 0 to 59 is an F. Use a negative score as a sentinel value to indicate the end of the input. (The negative value is only used to end the loop, so do not use it in the calculations.). For example, if the input is

98, 87, 86, 85, 78, 73, 72, 72, 70, 66, 63, 50, -1

the output would be:

Total number of grades = 14
Number of A's = 1
Number of B's = 4
Number of C's = 6
Number of D's = 2
Number of F's = 1

I should have been more specific. I mean, what is your question? What, specifically, are you having trouble with in this assignment and what would you like advice on?

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

Logostomp posted:

I've got the input working. Here's the question.

Write a program to read a list of exam scores given as integer percentages in the range 0 to 100. Display the total number of grades and the number of grades in each letter-grade category as follows: 90 to 100 is an A, 80 to 89 is an B, 70 to 79 is an C, 60 to 69 is an D, 0 to 59 is an F. Use a negative score as a sentinel value to indicate the end of the input. (The negative value is only used to end the loop, so do not use it in the calculations.). For example, if the input is

98, 87, 86, 85, 78, 73, 72, 72, 70, 66, 63, 50, -1

the output would be:

Total number of grades = 14
Number of A's = 1
Number of B's = 4
Number of C's = 6
Number of D's = 2
Number of F's = 1

Not really seeing a question (or why this is even hard) here but make 5 stacks or something. Push the input into the correct stack when read in. Count the data structure for the output.

Boo This Man
Mar 25, 2008

Mill Town posted:

I should have been more specific. I mean, what is your question? What, specifically, are you having trouble with in this assignment and what would you like advice on?

Putting the numbers in their correct grades.

Mill Town
Apr 17, 2006

Logostomp posted:

Putting the numbers in their correct grades.

Do you know how to compare two numbers? Do you know how if works?

Edit: Interestingly, the sample output given by your professor is wrong. Here's the right output:

Total number of grades = 12
Total number of A's = 1
Total number of B's = 3
Total number of C's = 5
Total number of D's = 2
Total number of F's = 1

Mill Town fucked around with this message at 14:24 on Feb 12, 2009

spiritual bypass
Feb 19, 2008

Grimey Drawer

Logostomp posted:

Putting the numbers in their correct grades.

This isn't the first time you've asked for help with your homework in this very thread. Don't you have some classmates to talk to? Any kind of collaborative spirit in the computer lab?

:dogout:

Mill Town
Apr 17, 2006

royallthefourth posted:

This isn't the first time you've asked for help with your homework in this very thread. Don't you have some classmates to talk to? Any kind of collaborative spirit in the computer lab?

:dogout:

I don't mind helping him if he can formulate his question as an actual QUESTION about JAVA like the thread title says. Previously he's been better about it, I don't know why he's having so much trouble now. Three posts about this assignment and none of them contain an actual specific question... :sigh:

Edit: Also, I was bored so I actually did his homework. I'm not gonna show him the answer, though :laugh:

Mill Town fucked around with this message at 14:24 on Feb 12, 2009

Boo This Man
Mar 25, 2008

royallthefourth posted:

This isn't the first time you've asked for help with your homework in this very thread. Don't you have some classmates to talk to? Any kind of collaborative spirit in the computer lab?

:dogout:

Am I really hurting anybody by asking a question? I'm not asking for the answer. Just asking for some help.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Logostomp posted:

Am I really hurting anybody by asking a question? I'm not asking for the answer. Just asking for some help.

But you are not asking for help, you are asking for us to do your homework. An example of asking for help would be, "How should I store all the numbers as they come in?". Your so called question can be answered by a 1 second google search, you already know how to compare 2 numbers.

spiritual bypass
Feb 19, 2008

Grimey Drawer

Logostomp posted:

Am I really hurting anybody by asking a question?

No, but I was in the mood to use :dogout: and you were a prime target

Mill Town
Apr 17, 2006

Logostomp posted:

Am I really hurting anybody by asking a question? I'm not asking for the answer. Just asking for some help.

Dude, I'm trying to tell you, you need to be very specific with your questions. Your "question" right now, and I use quotes because you didn't actually ask a question, consists of "How do I do this homework assignment?" We don't do that here.

Make it more specific, like "how do I count a number of different parameters?" and you'll get useful answers.

Summit
Mar 6, 2004

David wanted you to have this.
Anyone know a simple way to send some POST data to a web page using Java? I have a PHP page I want to ping with a single value of data, similar to how a web browser would access the page. Found a few (more complicated) solutions thus far, but I thought someone might have done this before.

covener
Jan 10, 2004

You know, for kids!

Cloud Dog posted:

Anyone know a simple way to send some POST data to a web page using Java? I have a PHP page I want to ping with a single value of data, similar to how a web browser would access the page. Found a few (more complicated) solutions thus far, but I thought someone might have done this before.

simple one here: http://apache.pastebin.ca/1337704

(you may want to change to HTTP/1.1 and add a proper Host: header)

1337JiveTurkey
Feb 17, 2005

If you create a HttpURLConnection from a URL (cast the regular URLConnection), that's a bit more high level and has convenience methods for HTTP-specific functionality.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

Logostomp posted:

Am I really hurting anybody by asking a question? I'm not asking for the answer. Just asking for some help.
This is the first appearance of a question mark in your posts in this conversation.

Dire Penguin
Jun 17, 2006

How do I tell how many elements are in an String array that I've created? If I read in a bunch of stuff to a String foo, then do foo.split() it gives me a String[] but if I want to loop through the elements I don't know how many there are.

e: it's foo.split().length.

e2: Different question. Is there any way to parse a line by quotes? I can't do foo.split(""");

e3: foo.split("\"");

Dire Penguin fucked around with this message at 07:32 on Feb 16, 2009

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Dire Penguin posted:

How do I tell how many elements are in an String array that I've created? If I read in a bunch of stuff to a String foo, then do foo.split() it gives me a String[] but if I want to loop through the elements I don't know how many there are.

e: it's foo.split().length.

e2: Different question. Is there any way to parse a line by quotes? I can't do foo.split(""");

e3: foo.split("\"");

You can also for-each over arrays if you're using JRE5+:
code:
for(String s:foo.split("\"")) {
//code
}

Captain Pike
Jul 29, 2003

I am very new to Java, and I am attempting to compile a project found on Source Forge:https://sourceforge.net/projects/opensmus/

Problem: The source code I downloaded seems to require third-party classes/libraries. I know this due to compile errors. I am downloading classes one by one, as the compiler complains. Some of the packages I download then complain about other required third party packages. I have no idea if I will have to download hundreds of packages.

This seems horribly inefficient. Is there a way to get a list of all required packages, perhaps via Netbeans or other IDE?

Example third-party packages: javax, junit, hamcrest.

Dire Penguin
Jun 17, 2006

Why doesn't the regular expression \\Q.\\E\\w\\w\\w/?[\\s$] trigger a match with the line
code:
http://www.somethingawful.com/globalcss/globalmenu.css
?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Because '$' inside square brackets means a literal dollar sign.

sd6
Jan 14, 2008

This has all been posted before, and it will all be posted again
Trying to learn basic socket programming in Java, and I'm having a problem.

I have a simple client program:
code:
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class TestClient{
    public static void main(String[] args) throws IOException{
        Socket socket = null;
	PrintWriter out = null;
	BufferedReader in = null;

	try {
	    socket = new Socket("localhost",55555);		
	    out = new PrintWriter(socket.getOutputStream(),true);
	    in = new BufferedReader(new InputStreamReader(
								socket.getInputStream()));
		}

		catch (UnknownHostException e) {
			System.err.println("Bad host");
			System.exit(1);
		}
	
		catch (IOException e) {
			System.err.println("Couldn't get I/O for connection");
			System.exit(1);
		}

		BufferedReader stdIn = new BufferedReader(
                                   new InputStreamReader(System.in));

		
		String input = stdIn.readLine();

		while (true) {
			out.println(input);
		}
	}
}
And then the server:
code:
import java.io.*;
import java.net.*;

public class TestServer {
	public static void main (String[] args) throws IOException {
		
		ServerSocket server = null;
		try {
			server = new ServerSocket(55555);
		}
		
		catch (IOException e) {
			System.err.println("Could not listen on port");
			System.exit(1);	
		}

		Socket client = null;
		
		try {
			client = server.accept();
		}

		catch (IOException e) {
			System.err.println("Accept failed");
			System.exit(1);
		}
		
	
		BufferedReader in = new BufferedReader(new InputStreamReader(
							client.getInputStream()));
		
		System.out.println(in.readLine());
	}
}
How can I modify the server so it prints each line of input from the client to the console? Everything I've tried ends up with the server printing the first line sent to it repeatedly in an endless loop.

Pooball
Sep 21, 2005
Warm and squishy.
The client code is the bit that's repeating the first line.

In the server you just want,
code:
                while (true) {
                        System.out.println(in.readLine());
                }
And in the client,
code:
                while (true) {
                        String input = stdIn.readLine();
                        out.println(input);
                }

sd6
Jan 14, 2008

This has all been posted before, and it will all be posted again
Yep that did it, thank you.

ynef
Jun 12, 2002

Captain Pike posted:

I am very new to Java, and I am attempting to compile a project found on Source Forge:https://sourceforge.net/projects/opensmus/

Problem: The source code I downloaded seems to require third-party classes/libraries. I know this due to compile errors. I am downloading classes one by one, as the compiler complains. Some of the packages I download then complain about other required third party packages. I have no idea if I will have to download hundreds of packages.

This seems horribly inefficient. Is there a way to get a list of all required packages, perhaps via Netbeans or other IDE?

Example third-party packages: javax, junit, hamcrest.

Absolutely. Check out Maven.

[edit] Maven requires that there is a Maven-specific file, but serious projects use it. If this one doesn't, suggest it!

ynef fucked around with this message at 07:38 on Feb 19, 2009

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Ant is another alternative to Maven and a lot of projects still use ant.

Slimy
Jun 13, 2001
I'm primarily a C++ guy, but I'm working on a Java project, and this reference problem has me stumped.

code:
private static ArrayList<Message> foo = new ArrayList<Message>;
private static ArrayList<Message> bar = new ArrayList<Message>;

/* fill foo and bar with Messages */

private ArrayList<Message> getArrayListByType(int type) {
   ArrayList<Message> messageArray = null;
   switch(type) {
     case (1):
        messageArray = foo;
        break;
     case (2):
        messageArray = bar;
        break;
   }
   return messageArray;
}

public void clearMessageArray(int type) {
   // Eclipse complains that the left hand side needs to be a variable!
   getArrayListByType(type) = new ArrayList<Messages>;
}
The problem is in clearMessageArray() (check the comment). What I'm really looking for is an implementation of getArrayListByType() that will actually return me something that can be used to modify foo and bar.

In C++, I'd just have the implementation of getArrayListByType() return a pointer to foo and bar, which I could dereference.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
There is no way to directly achieve that in Java short of storing these references in different objects.

Adbot
ADBOT LOVES YOU

rileylolz
Apr 27, 2008
For class, we've been assigned to make an 8x8 board for various pieces to move around on. I've run into a problem with user input, specifically dealing with how to handle tokens. I'm using Scanner to break up the input, but the problem is the largest command will have 5 tokens and the shortest will only have one. The way it's set up now is that it needs a command that will use all 5 tokens or else it crashes.

code:
		while (sc.hasNext())
		{
			cmd = sc.next();
			i = sc.nextInt();
			j = sc.nextInt();
			token4 = sc.next();
			token5 = sc.next();
			break;
		}
How can I break this up so it checks to see if there are any more tokens in the string before crashing? I tried if(sc.hasNext()) after each one, but it didn't work.

I'm still fairly new to java, any help would be appreciated.

And just an example of what the user input would look like:
"create 4 3 fast flexible" with fast and flexible being different types of pieces. It works fine with a command like that, but crashes with a command like "print"

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply