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
Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Can anyone explain to me why an individual 'scanner' has trouble moving from scanning doubles and strings?

This, for example, did not work.

code:
System.out.print("What's yo name? ");
name = input.nextLine();
System.out.print("Please input your gross income: ");
gross = input.nextDouble();
System.out.print("Do you have a dependant (Y or N): ");
child = input.nextLine();

Newf fucked around with this message at 22:36 on May 24, 2011

Adbot
ADBOT LOVES YOU

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm trying to write a class of objects that has ArrayLists as fields. It isn't going so well.

code:
import java.util.ArrayList;
public class GradeList{
	private ArrayList<double> tests;
}
When I try to compile this, it gives an error on line 3: Unexpected Type. What's the deal?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Well I've done that and it works, but I'm completely confused. Isn't the "thing" that you put in theses <> doodads the 'type' of object that the arraylist will store/retrieve?

aren't 'double's a thing in java, while 'Double's aren't a thing?

Anyway thanks :)


If I wanted an ArrayList of integers, would it be ArrayList<Integer> or ...?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Jeez, be more helpful guys.

Thanks both.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I was laying on the floor just now thinking about the line of text that I'd been instructed to enter at the beginning of every program:

public static void main(String[] args)

THIS IS BECAUSE the main method (is the method that runs without getting called?) (potentially) takes any number of string arguments, which are in fact (this is my guess) command line arguments?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Internet Janitor posted:

This may have helped, or it may have made you more confused.

A little of both. Thanks very much :)

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
OK, so more trouble from the resident java noob.

I'm trying to make a program that uses scanner to take a positive integer as keyboard input, but instead of crashing at faulty input (like a string, for example) it asks for the input again.

When I run the following:

code:
import java.util.Scanner;
public class Temp{
	public static void main(String[] biff){
		Scanner input = new Scanner(System.in);
		int i = input.nextInt();
	}
}
with input "fred", this gets shot back at me:

code:
fred
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:840)
	at java.util.Scanner.next(Scanner.java:1461)
	at java.util.Scanner.nextInt(Scanner.java:2091)
	at java.util.Scanner.nextInt(Scanner.java:2050)
	at Temp.main(Temp.java:5)

Process completed.
So I figured I could use the nextInt() method in a try block with a catch (InputMismatchException x) block to deal with non-integer inputs. But when I complie this:

code:
Scanner uInput = new Scanner(System.in);
int temp = 0;
while (temp <= 0){
	System.out.print("How many students are there? ");
	try{
		temp = uInput.nextInt();
		if (temp <= 0)
			System.out.println("Please enter a positive number!");
	} catch (InputMismatchException x){    // compile error here
		System.out.println("Please enter a positive number!");
	}
}
I get "cannot find symbol class InputMismatchException" as a compile error. It's probably obvious to you now that I don't know how to work exceptions at all, but what do I do to make this work?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I certainly haven't, but wouldn't it be covered by importing java.util.Scanner? How else would the first example program there have thrown the error?

e: well this seems unanimous, and thank yous, it worked, but my-oh-my I have no idea how java works at all.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I don't think I know how to use BufferedReader.

code:
// method which creates a bufferedreader only if it finds the file
// referenced by the user
	public static BufferedReader mkReader(){
		Scanner input = new Scanner(System.in);
		System.out.print("What is the name of the input file? ");
		try{
			return new BufferedReader(new FileReader(input.next()));
		} catch (Exception x){
			System.out.println("File not found!");
			return mkReader();
		}
	}
This is a method in the main class, to be called in the main method. I think maybe it won't work because the main method is outside the scope of the FileReader created in the class? Is this right? Can I rewrite the method to return both the FileReader and the BufferedReader?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I eventually got my original code to work. The problem was that in my main method header I didn't have "throws IOException". I have no idea what that does or why it needs to be there.

Why would it be a bad idea for a method like that to call itself recursively? It just works until it's been given a legitimate input file.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
from http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html:

toString() - Returns a String object representing this Integer's value.

toString(int i) - Returns a String object representing the specified integer.

The Integer class has a no arg toString method. But doing something like this
code:
int i = 4;
String s = i.toString();
returns an error in compilation that says "int cannot be dereferenced", while doing this
code:
int i = 4;
String s = Integer.toString(i);
works just fine.


What am I misunderstanding about the no-arg method?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm not sure I understand exactly what's going on with 'int' not being the same as 'Integer', but thanks for the discussion. Things to think about!

Another question, this one purely debugging:

code:
public static ArrayList<Integer> qSort(ArrayList<Integer> a){
	if (a.size() <= 1)
		return a;

	int pivot = a.get(0);
	ArrayList<Integer> lesser = new ArrayList<Integer>();
	ArrayList<Integer> greater = new ArrayList<Integer>();

	for (int i=0; i<a.size(); i++){
		if (a.get(i) < pivot)
			lesser.add(a.get(i));
		else
			greater.add(a.get(i));
	}
	return qSort(lesser).addAll(qSort(greater));
}
I'm getting an 'incompatible types' error on the last return statement, even though qSort seems to me to consistently return ArrayList<Integer> objects.

Any suggestions on how I'm misreading this?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I see!

Thanks.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I've been reading the Newbie Interview thread and a while back someone suggested:

code:
 1   ...   10
             
 .
 .
 .

 91  ...  100 
As a suitable interview question, so I decided to go ahead and put it together. First pass had me write this:

code:
public static void grid(int a, int b){
	for (int i=0; i<a; i++){
		for (int j=0; j<b; j++){
				System.out.print(count);
				count++;
			}
			System.out.println();
		}
Which works well enough but has the 'ugly' problem of a condensed first line (assuming that a*b gets into double digits), and any number of condensed early lines when a*b has several digits.

So I wanted to rewrite my print function using the printf command and HOLY LORD I don't know how printf works. I could get around this using another value to keep track of the number of digits in count, and then a loop to print the appropriate number of spaces, but printf seems pretty powerful and useful so I'd like to learn how it works!

tl;dr

Given an int 'digits', how can I use printf to print the int 'count' inside a 'space' that's 'digits' long? ex:

code:
digits = 5; count = 143;

printf( MAGIC ) should produce  "  143".  That's two spaces and then 143.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JOptionPane.html

May be what you're looking for.

ex:

code:
Show a dialog asking the user to type in a String:
    String inputValue = JOptionPane.showInputDialog("Please input a value");

Or likewise

int inputValue = JOptionPane.showInputDialog("Please input a value");

if the user is to input an int.
edit: don't forget your import. import javax.swing.JOptionPane;

Newf fucked around with this message at 16:19 on Dec 16, 2011

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Internet Janitor posted:

Newf: Have you read the documentation for the Formatter? It contains some examples of doing similar things.

Yeah, that's where I'm at. So

%[argument_index$][flags][width][.precision]conversion

is the format for a number in a 'formatted string'. So given that (most) of those arguments are optional, I'm not sure how to make an entry where it recognizes that the argument I'm inputting is for the width option?

I had tried something like:

printf("%digits", count);

which prints (if count=7 for example) "7igits".

I believe I see now that this is printing count as a decimal integer, and then going on to print "igits", but I guess I'm restuck now.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

baquerd posted:

Well it's right there in the specification.

printf("%1$5d", count); //5 space padded number

Edit: forgot the required conversion value

OK, so part of my problem was that I hadn't payed enough attention to the format there to see that inputs aren't ambiguous. For example, flags are specified with a character set that's disjoint from the ints that specify ints, and an int without being followed by a $ will be interpreted as width instead of as an index.

The thing is that I can't put that 5 in there for width. The width was meant to correspond to a variable "digits", which is input-dependent.

I got it now though: printf("%"+digits+"d", count);

Thanks for the pointers.

Newf fucked around with this message at 16:38 on Dec 16, 2011

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm gonna apologize in advance because I expect to be making GBS threads this thread up a lot over the next few days. I'm trying to use my Christmas break to get as much programming in as possible, and my biggest current goals are to build on my understanding of how OO programming and Java in particular work, and also to get a better understanding of some basic data structures and associated algos by writing them myself.

I figure I can do these things in combination. My plan is to start from this Node class:
code:
public class Node<E>{
	protected E value;

	public Node(){
		value = null;
	}

	public Node(E e){
		value = e;
	}

	public E getValue(){
		return value;
	}

	public void setValue(E e){
		value = e;
	}
}
And extend it into Node classes suitable for implementations in Singly, Doubly, and circularly linked lists, and then into trees and more general graphs. Finally, my end-goal for this endeavour is to extend my Graph class into a Finite State Automata class for reading RegExpressions, and also maybe write some code to output a graphical representation of a graph (or even FSA if I'm still rolling confidently at that point).

By the time I go back to class in January, I'd like to make my own 'package' that I can use in the future for my own academic type things, which includes all of my homemade classes.

I guess my only question for the moment is whether what I'm doing is totally misguided, or if I'm going about it in a fundamentally stupid way. Thoughts?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Yeah, to clarify, I understand and expect that pretty well all of this will exist entirely as an exercise, but I mean to say that I'd like to continue on updating and refining my own library of code as I learn new things.


I'm in trouble already though, and it's with a dumb thing that's going to betray my total lack of understanding:

code:

SLinkNode.java:


public class SLinkNode<E> extends Node{
	protected SLinkNode<E> next;

	public SLinkNode(E e){
>>>		super(e);
		next = null;
	}

	public void setNext(SLinkNode<E> n){
		next = n;
	}

	public SLinkNode getNext(){
		return next;
	}
}
I'm getting "uses unchecked or unsafe operations." on the arrowed line. The superclass is included in my previous post. Instead of super(e) I also tried

super.Node(e); --> cannot find symbol method Node(E)

and some other stupider things. Is there some special way to use a constructor with generics? Or some particularly good reading on how to work generics?


Should I, before getting into any of this, make myself understand Interfaces and use them throughout my adventures?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Aleksei Vasiliev posted:

public class SLinkNode<E> extends Node<E>, I think

Correcto. Thanks.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Understand that I am a Java/programming child, and my answers to these and any questions are almost certainly not the best answers available. That said, I think they can 'work'.

Dr. Gitmo Moneyson posted:

1.) How do I create a new .txt file in Java?
2.) How do I write values into a newly-created .txt file in Java? (Apparently I forgot how to do this awhile back and need some help jogging my memory :shobon:)
3.) How do I set up an option enabling a user to save a .txt file into a destination folder, and how do I enable the user to edit the "Save As" name that the file is saved under?
4.) How do I get my program to recognize the contents of one of the JOptionPane fields as a default "Save As" name for Question #3 above?
5.) If the user decides to open a previously saved file, how do I get the program to open the destination folder so the user can Browse it for the file they want?

1), 2), and 4) can all be accomplished with the FileWriter and PrintWriter objects. To write, for example, to a file whose name is input by a user, you can do something like:
code:
import javax.swing.JOptionPane;
import java.io.*;

public class Box{
	public static void main(String[] args){
		try{
			PrintWriter out = new PrintWriter(new FileWriter(JOptionPane.showInputDialog("Please input a filename:")));

			out.println("wtf");
			out.print(JOptionPane.showInputDialog("heyo"));
			out.close();
		}
		catch (Exception x){}
	}
}
edit: The initialization of the PrintWriter is a little dense in that code, but read it carefully and it'll make sense if you look at the constructors for PrintWriter and FileWriter. The code below expands that one line out a bit to make it more readable:
code:
PrintWriter out = new PrintWriter(new FileWriter(JOptionPane.showInputDialog("Please input a filename:")));

is the same as:

String file = JOptionPane.showInputDialog("Please input a filename:");
FileWriter fw = new FileWriter(file);
PrintWriter out = new PrintWriter(fw);
Note that the printing to the file and such is all done in the same try block. As far as I can tell it has to be this way. I do not really understand why. Also note that you have to 'close' the printwriter, or else nothing will actually be written to the file.

I don't really have any immediate ideas about questions 3) and 5).

Newf fucked around with this message at 16:17 on Dec 21, 2011

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm trying to write some basic server/client functionality using sockets, but I'm not able to get any communication to between the server and client to occur until the socket between them is closed.

http://pastebin.com/89T5tfkY is my server, and
http://pastebin.com/PC9pVTq6 is my client.

The client does print "Hello World", but only when the line sock.close() is reached at the server side, so the info transfer only happens at the point of disconnection, as far as I can see.

I need my client to receive information from the server and then be able to return requested information to the server, though. (You know, in general). Any pointers?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm building a little something for school where a system has a number of different types of accounts (eg: admins, mods, shmoes) and my wish is to create a default 'Account' class and then to extend it to the various other classes, but I think I may be cornering myself by being too eager to use inheritance.


Question: If my Account class implements serializable so that I can write Account files, would my read/write methods in the parent class be properly inherited by the subclasses? ie, reading an Account object from its file in the parent method would require typing the object as an Account - so would typing a Shmoe as an Account destroy his attributes which are distinct to Shmoes?

eg, from the 'Account' class,
code:
	public Account open(String l){
		try{
		  	ObjectInputStream load =
		  		new ObjectInputStream(
		  		new FileInputStream("accounts/"+l));
		  	Account a = (Account) load.readObject();
		  	load.close();
		  	return a;
		  } catch(Exception e){
		  	System.out.println("There is no account with this username.");
		  	return null;
		  }
	}
would this method work for subclasses?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Luminous posted:

You may want to consider an account as, well, just an account that has f.ex, a username and a role or a list of roles, where a role is an admin, a mod, or a schmoe (use inheritance here).

Then serializing an account and determining which actual role objects need to be instantiated is more straightforward.

Yes, I think you're right. Thanks.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
It's likely that this is under my nose and I'm an idiot, but am I able to download the whole java API documentation so that I can reference it sans internet? In a simple way? (javadocs.zip?)

I mean this website: http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Thanks!

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I very nearly posted the stupidest question in the history of the thread but I've just figured it out.


Now I have to post it anyway because I've had a good laugh at the situation and I'm on a real streak of INCREDIBLY DUMB programming errors (an hour where corresponding files weren't in the same directory, an hour shouting at a program that wouldn't run because it didn't have a main method, and now this):

Me, last night posted:

Why won't eclipse auto-import this? Even trying the imports manually I can't get it to work???

None of java.util.WeightedGraph, java.WeightedGraph, java.DataStructures.WeightedGraph seem to be found and I can't figure out the proper import from the documentation for some reason?

Does day-to-day programming ever get over this kind of boneheadedness? I'm sure that I spend half of my 'coding time' on these types of errors.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

TRex EaterofCars posted:

Usually the solution is to stop using eclipse.

But I just started last night! AHHHHHH!

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

I am in posted:

The one marked with red

Oh god thanks for that.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm still lovely at java/programming, but I think I've nailed down a question concerning a particular situation which, if clarified, might make me a little less lovely.

I'm trying to learn about file system management in java so I've been writing a small test class to experiment with the java.io.File object's methods.

This is how far I've gotten:

code:
import java.io.File;

public class FileTester{
	public static void main(String[] args){
		System.out.println(new File("FileTester.java").exists());
		System.out.println(new File("sdfsdfsdf").exists());
		System.out.println(new File("users").exists());
		System.out.println(new File("users").isFile());
		new File("produced").mkdir();
	**	new File("alsoProduced/test.txt").createNewFile();
	}
}
This code compiles / runs as expected when the ** line is omitted, but compiling with ** included produces the following error:

code:
FileTester.java:10: unreported exception java.io.IOException; must be caught or declared to be thrown
		new File("alsoProduced/test.txt").createNewFile();
		                                               ^
1 error
I've investigated the methods exists(), isFile(), createNewFile(), etc, and found that all of these methods throw exceptions under particular circumstances. My question is why the compiler insists on try/catch error handling for the createNewFile() line when it didn't for any of the others?

Newf fucked around with this message at 18:52 on Mar 22, 2012

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I feel less lovely already! Thanks!

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I need some help with java sockets and BufferedReaders/BufferedWriters.

I'm trying to set up a server/client so that after connecting, input entered by the client will be displayed server side, until the client inputs a null string. After the null input, the roles reverse, until the server inputs a null string, at which point the connection terminates and the server readies itself for another client.

My problem is getting my BufferedWriter to 'flush' the user's input. Upon establishing a connection, both the Server and Client create BufferedReader/BufferedWriter as follows:

code:
BufferedWriter clientOut = new BufferedWriter(
			   new OutputStreamWriter(
			   clientSocket.getOutputStream() ));


BufferedReader serverIn =  new BufferedReader(
			   new InputStreamReader(
			   clientSocket.getInputStream() ));
(This is the clientside, but serverside is similar). Client then enters a loop:

code:
String line = null;
	while( (line = userIn.readLine()) != null ){
		clientOut.write( line , 0, line.length() );
		clientOut.flush();
*		clientOut.close();
	}
Where userIn is a BufferedReader made from System.in.

At this point the server is in its own loop:

code:
while( (clientLine=clientIn.readLine()) != null){
	System.out.println(clientLine);
}
Which is supposed to read the flushed line from clientOut and print it locally.

My first attempt didn't have the line marked *, and the result was that the server never ever printed anything until the client process was violently killed, at which point it prints everything that the client has input.

When I include the line *, the server will print the first input from the client, but when the client makes their second input, an error is returned since clientOut is destroyed.

When I include the construction of clientOut inside the while loop (this seems excessive to me but may, for all I know, be standard practice), the server again successfully prints the first input from the client, but the second client input produces an error since (much to my surprise) clientOut.close() seems to close clientSocket (since clientOut invokes clientSocket in its construction I guess?)



Really could use some pointers. Thanks.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Ahhh, drat, thanks. I essentially replaced clientOut.write( line ) with clientOut.write( line + "\n" ) (probably poor form) and things smoothed out from there.

Thanks again.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
How much have you played around with this? Try some smaller values for your input 'k' and see what you get. Something like

code:
for (int k=1; k<= 15; k++){
   System.out.println(k + " recursions :  " + cosineTaylor(3.14,k));
}
may be illuminating for you.

Newf fucked around with this message at 20:28 on Sep 18, 2012

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
This is less a java question than an Eclipse question. How do I get the Eclipse intellisense to find/read/display the documentation on regular java language features? For example, mousing over the 'println' token in System.out.println("Hi"); produces

quote:

Open Declaration void java.io.PrintStream.println(String arg0)

Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found.

I'm failing at google with this problem (getting instructions on how to use Eclipse's javadoc generation instead of what I want), so I figured I'd just ask some humans who are sure to know the answer.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

rhag posted:

Shift+Left Click on println and click Attach Source on the page that appears. Then select src.zip from the JDK home (you have a JDK installed, right?, not only a jre).
You'll get both the javadoc and the source.

Thanks!

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
return aCollection.contains(anObject) && aCollection.size() == 1; ?

Newf fucked around with this message at 14:43 on Jul 2, 2014

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

FateFree posted:

Its funny but I can't help look at this and say the size check should be first for performance reasons to short out the contains. Do you guys consider stuff like this to be premature optimization? In my view, as long as you aren't doing 'extra' work under the pretense of optimization, then I would just consider swapping to be the objectively correct action.

All work is extra work!

As for whether this is premature optimization - it's a little bit contextual. Is there a possibility in this system of this collection being terribly large? It's likely that even the five seconds of typing to swap the order of those checks is longer than the cumulative performance hit of the inefficiency over the entire lifetime of the system.

In general, I tend to build first and optimize when I'm given some indication that there would be a derived benefit.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm looking to run javadoc on this file: https://github.com/ankidroid/Anki-Android/blob/master/api/src/main/java/com/ichi2/anki/FlashCardsContract.java

I haven't used java in five years or more so I'm not sure whether I can run something like javadoc.exe myFile.java and have it spit out an myFile.html. The windows examples link on the Javadoc FAQ is a 404.

I'm not even sure how to tell if I have the java sdk installed on my machine. java.exe, javaw.exe, and javaws.exe are available in my command prompt, but javac isn't.

Any directions to give?

(A generous person could also feel free to generate the doc and pastebin it or something if it's a one-step procedure).

Adbot
ADBOT LOVES YOU

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I figured it out. Noticing the long-unclicked Eclipse icon on my taskbar, I guessed that some version of the java sdk must exist on the machine. I had earlier tried using windows explorer and the start menu to find javac.exe, but they failed. Of course, it was in the first place I looked (program files (x86)/java/sdk/bin). Eclipse's export javadoc worked out for me.

Such pangs of nostalgia at running Eclipse...

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