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
Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
Our programming teacher is offering extra credit if we can add data validation to our program to ensure that the correct form of data was entered. I have a couple questions about the ideal way to do this...

The user is required to enter two dates (the current date and their birth date) as well as whether they are male or female. Ideally, what I'd like to prompt them to enter the year/month/day one at a time and store these in temporary integer variables. My question is this:

Is it possible to set up a method outside of the main that will check if the numeric data is within a set range, and terminate the program if it's not? This is what i've got going so far, this particular method is for checking if the entry for the "day" is valid...

code:
public static int dayCheck (int a)
	{
		Scanner kb = new Scanner(System.in);
		if (a < 0 || a > 31)
		{
			
		System.out.println("Invalid entry. Program now terminating");
		System.exit(0);
		
		}
		else//
	}
Is it possible to make a method to do this?

Adbot
ADBOT LOVES YOU

HFX
Nov 29, 2004

Harold Ramis Drugs posted:

Our programming teacher is offering extra credit if we can add data validation to our program to ensure that the correct form of data was entered. I have a couple questions about the ideal way to do this...

The user is required to enter two dates (the current date and their birth date) as well as whether they are male or female. Ideally, what I'd like to prompt them to enter the year/month/day one at a time and store these in temporary integer variables. My question is this:

Is it possible to set up a method outside of the main that will check if the numeric data is within a set range, and terminate the program if it's not? This is what i've got going so far, this particular method is for checking if the entry for the "day" is valid...

code:
public static int dayCheck (int a)
	{
		Scanner kb = new Scanner(System.in);
		if (a < 0 || a > 31)
		{
			
		System.out.println("Invalid entry. Program now terminating");
		System.exit(0);
		
		}
		else//
	}
Is it possible to make a method to do this?

You can make as many methods as you want. You can call them from inside the main and have them return a value. Your above code would be called like so:

code:
public static void main(String args) {
    dayCheck(0);
}
A couple notes, if you already have a scanner working on System.in, why not pass it as a parameter. Furthermore, what is the purpose of a? I mean you are reading input into kb, so a doesn't really make sense. A nice thing to do, is to read in the string using scanner, then send it to a function to be validated.

However, since you are dealing with days, while the class set is terrible and mystifies even long term programmers, look into how to create a Calendar date from a string in Java. You should be able to leverage the class to validate your data for you. Bonus is that it validates things like January have 31 days, but February having 28 (or 29 on leap years).


Anyone have a recommendation on a remote profiler that will work with Java 6 and maybe even Java 7 that works in Eclipse? I tried to get one working, but all the instructions for it were pre change in instrumentation of Java 6.

Blacknose
Jul 28, 2006

Meet frustration face to face
A point of view creates more waves
So lose some sleep and say you tried

tripwire posted:

Use intellij :D

I upgraded to eclipse indigo this morning for an ATG project (gently caress ATG, hybris all the way) and it crashed 10 times before lunch so I had to roll back to helios.

I really, really wish I could afford intellij currently :smith:

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
Allright, i'm stuck again. I ask for a user input of gender at the beginning of the program and I'm trying to display the user age and gender before proceeding. I acquire the user's gender using the following code:

code:
System.out.println("Please enter your gender. Type 'm' for male and 'f' for female");
		String sex = kb.nextLine();
and later I'm trying to display a message using the following 'if' statement:

code:

if (sex == "f")
	{
	sex = "female";
	}
else if (sex != "f" || sex != "female")
	{
	sex = "male";
	}
System.out.println("You are a " + age + " year old " + sex);
The problem is, no matter what the user inputs it always displays the gender as 'Male'

What am I doing wrong here?

Sedro
Dec 31, 2008
You're comparing strings with the == operator which in Java compares object reference. You need to use equals instead:
code:
String str1 = "f";
String str2 = "f";
str1 == str2 // false
str1.equals(str2) // true

Contra Duck
Nov 4, 2004

#1 DAD

Sedro posted:

You're comparing strings with the == operator which in Java compares object reference. You need to use equals instead:
code:
String str1 = "f";
String str2 = "f";
str1 == str2 // false
str1.equals(str2) // true

I hope he doesn't try to run that example because that will just confuse him more :ohdear:

Sedro
Dec 31, 2008
That's why I didn't bring up the indentation or redundant if clause ;)

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
To clarify what Contra Duck said, the Java compiler interns String constants, making equal String constants resolve to the same object, which means reference comparisons actually work. In. That. Case.

You should never compare Strings with ==. Ever.

Use String.equals().

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
Ok, I've got my program working and modular and I'm stuck on one last thing: Creating a method that will take intigers as arguments and combine them all into a string, and then output that in a way that can be printed. This is what my code looks like so far for the methods:

code:
public static String fTotal(int age, int week, int day)
	{
		String hhh = new String("Renting a car will cost $" + day + " per day and $" + week +" per week for a female of age");
		return hhh;
	}
	public static String mTotal(int age, int week, int day)
	{
		String hhh = new String("Renting a car will cost $" + day + " per day and $" + week +" per week for a male of age");
		return hhh;
	}

And this is how I call on them in the main:

code:
if (sex.equals(male))
		{
			dr = mDay(age);
			wr = mWeek(age);
			hhh = mTotal(age, wr, dr);
			System.out.println(hhh);
		}
		else if (sex.equals(female))
		{
			dr = fDay(age);
			wr = fWeek(age);
			hhh = fTotal(age, wr, dr);
			System.out.println(hhh);
		}
The problem now is that running this program doesn't print anything. Is there a way I can just get a method to print a statement whenever it's run?

Sedro
Dec 31, 2008
Your problem is that neither of these statements are true:
code:
sex.equals(male)
sex.equals(female)
So your program happily does nothing. What are the values of those variables? Did you instead mean to write this?
code:
sex.equals("m")
sex.equals("f")

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

Hey folks,

I'm set to leave grad school this term and I've accepted a position at Amazon, where I'm given to understand that I'll be doing most of my development in Java. I've not touched the language since my undergraduate days (the last two or so years have been spent living in C and Python), and this was the era of Java 1.5, so I've not touched generics and whatever other goodies Java 6 and 7 have provided.

Does anyone have a recommendation for a book that'll get me up to speed? All the books I thumbed through in my department's reading room seem to be geared towards newbie programmers or are just flat-out outdated.

Thanks!

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Java 5 added the modern Collections framework, generics and the foreach loop, among other more minor details. Honestly, Java 6 and Java 7 haven't added many critical features that significantly change how things are done.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Internet Janitor posted:

Java 5 added the modern Collections framework, generics and the foreach loop, among other more minor details. Honestly, Java 6 and Java 7 haven't added many critical features that significantly change how things are done.

I would say that Java 6 didn't change anything, but Java 7 certainly added new syntax.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Yeah, Java7 did add a few new minor things. Basically:

  • you can switch on Strings
  • generic decalarations now feature type inference so instead of List<Integer> stuff = new ArrayList<Integer>() you can just say List<Integer> stuff = new ArrayList<>();
  • try statements can be used to control object lifetimes ala C#'s using statements. See here.

I guess I meant there hasn't been anything new that totally changes how you go about writing code, like when LINQ was introduced in C#. It's just a little new sugar.

Internet Janitor fucked around with this message at 01:51 on Oct 9, 2011

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Using Eclipse. How do I export a JAR of a library I've written so that it has its dependencies contained in it?

My project depends on BouncyCastle and redistributing its JAR in mine seems easier than making users download it themselves.

Is this possible/good?

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

Aleksei Vasiliev posted:

Using Eclipse. How do I export a JAR of a library I've written so that it has its dependencies contained in it?

My project depends on BouncyCastle and redistributing its JAR in mine seems easier than making users download it themselves.

Is this possible/good?

There are ways to put jars inside your jar and then programmatically add them to your classpath. I've never done it because it sucks.

Something I've done a few times, and isn't too bad is to unzip the 3rd party jars, put their classfiles and other resources in your jar and just seal it back up with your code in there as well.

The easiest thing to do though, is you make a distributable that has a lib directory and your runner script calls java with the jars in the classpath.

Volguus
Mar 3, 2009

Aleksei Vasiliev posted:

Using Eclipse. How do I export a JAR of a library I've written so that it has its dependencies contained in it?

My project depends on BouncyCastle and redistributing its JAR in mine seems easier than making users download it themselves.

Is this possible/good?

The easiest way (and independent of IDEs) is to use ant to make the jar. And you can embed your jar's in it.
Example:
<jar destfile="build/main/checksites.jar">
<fileset dir="build/main/classes"/>
<zipfileset includes="**/*.class" src="lib/main/some.jar"/>
<manifest>
<attribute name="Main-Class"
value="com.acme.checksites.Main"/>
</manifest>
</jar>


Taken from http://ant.apache.org/manual/Tasks/jar.html (where you can find even more examples and information).

Lagg
Nov 10, 2005

The wilder the hat, the wilder the man.
I've recently started to mess around with EE 6 (Web profile - jsf + ejb +jpa) mostly just for curiosity.

The last time I messed with Java was for a "object oriented programming" class and we never touched jsp, web stuff, etc (would have just been JSP at that time).

So far I'm pleasantly surprised. Mostly doing PHP for the last few years, I heard nothing but horror stories about doing Java. Maybe I'm not deep enough into it yet...:tinfoil:


Anyhow, I'm messing around with some "SessionBeans" (@stateless "facades" beans that Netbeans makes for when you do "make jsf from entity class" like a lazy noob) and they use the @PersistenceContext(unitName="fooPU") to manage persistence.

At work we have a different database server for production than for testing. I realized I would need two persistence units, one for development and one for production.

Coming from PHP I would want to do something horrible like this



code:
public class FooFacade extends AbstractFacade<Message> {
    @PersistenceContext(unitName = someclass.getPu())
    private EntityManager em;
    ...
where the someclass.getPu() would look at the current server, and then return the persistent unit (as a String) I need.

It should come as no surprise that this doesn't work. UnitName has to be a constant and blah blah blah (I'm sure there are several reasons why this doesn't work and they all go back to the fact that I'm really just watching youtube and hacking at this point)

I've Googled around a bunch and the only solution I can find is using Maven to swap out persistence.xml based on the build command.

I know even less about Maven than I do about Java, so I'm hoping that I'm just overlooking a way to do this.

Any ideas? (or maybe links that could shed some light on the topic at large)

EDIT:

N/M I figured this out (I think? Please correct me in my ignorance!)


Since I'm cheating my way through this by using Netbeans and Glassfish, it turns out that the "jta-data-source" tag in persistence.xml is all I need.

As long as Glassfish is setup with the same jdbc information between servers, you should be able to move between stages...I think...

I doubt anybody will care, but maybe sometime in the future, some scraper will return this in a search result for some poor lost noob.

Lagg fucked around with this message at 19:35 on Oct 12, 2011

HFX
Nov 29, 2004

rhag posted:

The easiest way (and independent of IDEs) is to use ant to make the jar. And you can embed your jar's in it.
Example:
<jar destfile="build/main/checksites.jar">
<fileset dir="build/main/classes"/>
<zipfileset includes="**/*.class" src="lib/main/some.jar"/>
<manifest>
<attribute name="Main-Class"
value="com.acme.checksites.Main"/>
</manifest>
</jar>


Taken from http://ant.apache.org/manual/Tasks/jar.html (where you can find even more examples and information).

There is a Maven archetype for doing this also that works wonderfully.

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
This thread is amazing, thanks for all the help.

I have some extra credit available on one of my assignments for coding the Sieve of Eratosthenes for a given positive integer (taken from Scanner). The kicker on this assignment is that it has to be done without using any arrays. I don't even know where or how to do this without arrays, so I'm starting to think this might have been a typo on the assignment sheet. (there were other parts of the assignment where using arrays would have drastically simplified things)

Is it even possible to code this without arrays?

Sereri
Sep 30, 2008

awwwrigami

Harold Ramis Drugs posted:

This thread is amazing, thanks for all the help.

I have some extra credit available on one of my assignments for coding the Sieve of Eratosthenes for a given positive integer (taken from Scanner). The kicker on this assignment is that it has to be done without using any arrays. I don't even know where or how to do this without arrays, so I'm starting to think this might have been a typo on the assignment sheet. (there were other parts of the assignment where using arrays would have drastically simplified things)

Is it even possible to code this without arrays?

If arrays are off the table I guess lists and sets are too so maybe a string with comma separated integers.Use stringbuilder to write all the numbers one after another then remove them from the string if you match them. That's pretty ugly though, not sure why you'd want people to code that without arrays.

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
ugh, i'm just going to write that little detail off as a typo then. Thanks

aleph1
Apr 16, 2004

Harold Ramis Drugs posted:

ugh, i'm just going to write that little detail off as a typo then. Thanks

What was meant was probably: don't use raw arrays, instead use the Collections framework (List/Set/etc), which is good advice for people just starting out with Java.

baquerd
Jul 2, 2007

by FactsAreUseless
I made this thing, no lists.

code:
import java.util.concurrent.CyclicBarrier;

public class ConcurrentSieve {
  private Integer currNum;
  private final Integer targetNum;

  private boolean primeFlag;
  private CyclicBarrier primeBarrier;
  private CyclicBarrier holdingBarrier;

  public ConcurrentSieve(Integer num) {
    targetNum = num;
  }

  private class NonPrimeGenerator implements Runnable {
    private final int baseThreadNum;
    private int threadNum;

    public NonPrimeGenerator(int num) {
      baseThreadNum = num;
      threadNum = num;
    }

    public void run() {
      try {
        while (threadNum < targetNum) {
          if (threadNum == currNum) {
            primeFlag = false;
            primeBarrier.await();
            holdingBarrier.await();
          } else if (threadNum > currNum) {
            primeBarrier.await();
            holdingBarrier.await();
          } else {
            threadNum += baseThreadNum;
          }
        }
        while (currNum < targetNum) {
          try {
            primeBarrier.await();
            holdingBarrier.await();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public void generatePrimes() {
    try {
      int numGenerators = 2; // also include this thread
      primeFlag = true; // first number is a prime
      primeBarrier = new CyclicBarrier(numGenerators);
      holdingBarrier = new CyclicBarrier(numGenerators);

      currNum = 2;
			
      //stupid hack but I don't want to clean this up
      System.out.println("Found a prime: " + currNum); 
      (new Thread(new NonPrimeGenerator(currNum))).start();

      while (currNum < targetNum) {
        primeBarrier.await();
        if (primeFlag) {
          System.out.println("Found a prime: " + currNum);
          numGenerators++;
          primeBarrier = new CyclicBarrier(numGenerators);
          (new Thread(new NonPrimeGenerator(currNum))).start();
        }

        primeFlag = true;
        currNum++;

        holdingBarrier.await();
        holdingBarrier = new CyclicBarrier(numGenerators);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    ConcurrentSieve sieve = new ConcurrentSieve(50);
    sieve.generatePrimes();
  }
}

code:
Found a prime: 2
Found a prime: 3
Found a prime: 5
Found a prime: 7
Found a prime: 11
Found a prime: 13
Found a prime: 17
Found a prime: 19
Found a prime: 23
Found a prime: 29
Found a prime: 31
Found a prime: 37
Found a prime: 41
Found a prime: 43
Found a prime: 47

Ochowie
Nov 9, 2007

Aleksei Vasiliev posted:

Using Eclipse. How do I export a JAR of a library I've written so that it has its dependencies contained in it?

My project depends on BouncyCastle and redistributing its JAR in mine seems easier than making users download it themselves.

Is this possible/good?

In my version of eclipse there is a tab in the build path settings to "Order and Export". Am I incorrect in the assumption that exporting a JAR there would lead to it being bundled in your JAR?

Polidoro
Jan 5, 2011


Huevo se dice argidia. Argidia!
How can I invoke a WebService method without generating the stubs using wsimport?

I need to parse a wsdl to show the user the methods, the user will select one and a form will be dynamically generated to input the parameters manually, then I have to invoke the method and show the response to the user. I won't know anything about the service because the user can provide any wsdl url they want.

This is for a school project if you need to know.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
You just need to do an HTTP POST to the URL. The body of the message is an XML with the fields that are defined in the wsdl.

Polidoro
Jan 5, 2011


Huevo se dice argidia. Argidia!
Oh, I thought it was more complicated than that because Googling for a while got me pretty confused. I'm sorry and thanks.

Hidden Under a Hat
May 21, 2003
I designed a program on my Mac in Netbeans, however when I transferred the program to a Windows machine, some of the components weren't correctly spaced, so I decided to try and fix the visual components by loading the program in Netbeans on the Windows machine that was going to run the program. But when I tried to load a class that had a visual components, I got the following error message:

quote:

Error in loading components property: [JPanel]->size
No such property exists in the component

It then goes on the tell me I should enter view only mode because trying to edit the component might cause it to be lost. Sure enough, I tried to edit some of the components in the Jpanel to correct the spacing issues, but when I loaded my program the JPanel didn't appear. Anyone know how to fix this issue?

Partyworm
Jul 8, 2004

Tired of partying
I've just been attempting to create my first game in java with the aid of a tutorial. It's been a real blast, and generally going a lot more smoothly than i expected - especially as I'm a pretty terrible programmer in general. I've just hit a bit of a roadblock though with the following code, which is a bit baffling as it's part that was lifted straight from the book.

According to Netbeans this:

code:

//get full screen graphics context so I can draw gui elements over existing game elements
  JFrame frame = super.screen.getFullScreenWindow();
//other stuff
is incompatible with this:

code:
public Window getFullScreenWindow() {
        return device.getFullScreenWindow();
    }
Seems fairly obvious - Window isn't compatible types with a JFrame object. But what's the workaround for getting the full screen context on a JFrame? Have I implemented the code samples incorrectly? Or is this a genuine oversight on the author's part? Could it be some sort of legacy issue, seeing as the tutorial was written for Java 2?

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Partyworm: You can just do something like this:

code:
JFrame window = new JFrame();
window.setUndecorated(true);
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(window);
You have to jump through a couple more hoops if you want a specific display resolution, etc.

edit: And since I typed it up anyway to make sure everything works, here's a program demonstrating that in context.

Internet Janitor fucked around with this message at 14:51 on Oct 22, 2011

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
So I'm using a method with a try/catch loop for validating the entry of integers, and it's perfectly functional. I have it set up to display an error message if the integer they enter is out of range, but I would also like to make it display a different error message for non-integers. Here's my code so far...

code:
public static int starterChecker()
{
Scanner kb = new Scanner(System.in);
int myInt;
while (true)
     {
     try
         {
	 System.out.print("Please enter a positive integer --> ");
         myInt = kb.nextInt();
	 if (myInt < 0)
		{
		System.out.println("Invalid Entry: Please Try Again");
		throw new Exception("Not positive");
		}
	 break;
         }
         catch (Exception e)
         {
          kb.nextLine();
          }
     }	
return myInt;

}// end starterChecker method

If possible, I'd like to do this with another if-loop so I can display a unique error message for non-integer entries.

edit: VVV thanks VVV

Harold Ramis Drugs fucked around with this message at 01:46 on Oct 23, 2011

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Scanner will throw an InputMismatchException if the input the user gives is not an integer. Make sure you put the catch for that ahead of the one for Exception, since all Exceptions are a subclass of Exception, and the InputMismatchException would just get caught as an exception.

http://download.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right
I've been trying to get into Android development using Eclipse, and it always starts nice, but in the end my lack of Java and object-orientated programming shows.

However, I bet there are a million books about Java out there. Is there a particular good one and/or one that uses Eclipse as a GUI?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Grawl posted:

I've been trying to get into Android development using Eclipse, and it always starts nice, but in the end my lack of Java and object-orientated programming shows.

However, I bet there are a million books about Java out there. Is there a particular good one and/or one that uses Eclipse as a GUI?

I was in the exact same situation (well I didn't know Java...I was fine with OO) whe I decided to get into Android dev. I just picked up Head First Java on a whim and it worked out just fine for me.

Hidden Under a Hat
May 21, 2003
I'm having trouble with JDialog window sizing. In Netbeans, I size the dialog the way I want it to fit my components, but when I actually run the program, the OS adds this extra crap to it like blue trim borders, which takes up the space where my components should be and pushes them off the screen forcing me to manually resize it to see them. How can I fix this issue or at least find out the size of the extra crap that Windows is adding so I can compensate for it?

Tamba
Apr 5, 2010

yourDialog.setUndecorated(true);

(and I think you need to do this before it is displayed/set visible)

edit: http://download.oracle.com/javase/6/docs/api/java/awt/Dialog.html#setUndecorated%28boolean%29

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Better solution is to set the size on whatever JPanel or other component you add to the window, rather than the window itself. Layout managers, man- layout managers.

Bakalakadaka
Sep 18, 2004

Yo I need to make a method to sort an array of objects, each object being made up of a string and 3 integers, and it has to be able to sort them by each variable based on input. I'm not really sure how to set up the method so that it can sort by a specific variable in each object.

Any suggestions to help me put this together?

Adbot
ADBOT LOVES YOU

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Check out this method Collections.sort.

What you really need to learn is how to create your own Comparator which does what you want. Once you've figured out how to create the comparator, you just tell the Collections.sort method to use that and it will do the rest.

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