PDA

View Full Version : Java Noob Help




Jasonbot
Sep 16, 2006, 02:32 AM
I need some very basic help with Java and XCode.
I've just started java at school, using PC's with JCreator, and now when I take my project home and run it in Xcode I can't compile or anything.
In fact most of the options are grayed out.

Can anyone help me?

Here's the code:


import javax.swing.*;

public class variables
{
public variables ()
{

String name = "Jason";
String surname = "BoTHa";
int age = 17;
char gender = 'm';
double height = 148.9;

boolean married = true;
short treasures_found = 12;
byte shot = 4;
float bank_account = 8.1f;
long distance_traveled = 7834;

JOptionPane.showConfirmDialog(null,name);


}

public static void main(String args[])
{
new variables ();
}
}



THANX!



robbieduncan
Sep 16, 2006, 03:22 AM
You cannot just open a java file in XCode and compile/run it. The only way to use XCode is with XCode projects. You need to start a new XCode Java project and add the file to it.

Or since you are trying to learn something find out what's going on in all these IDEs. Use the command line javac to compile the file(s) and java to run then.

Jasonbot
Sep 16, 2006, 03:30 AM
Whoa :confused: OK, I tried the whole Xcode project thing -Really confusing! What should I use for java?

robbieduncan
Sep 16, 2006, 03:31 AM
Probably Java Tool...

Jasonbot
Sep 16, 2006, 03:35 AM
Is this a seperate IDE? Link...

robbieduncan
Sep 16, 2006, 03:53 AM
No it's a choice in XCode. When you choose New Project scroll down to the Java section then choose Java Tool (it's the last item in there). If I were you I'd learn to use the command line tools. It'll be useful in the long run anyway.

Jasonbot
Sep 16, 2006, 04:16 AM
Ok now there's a prblem under projects there's no java section???

robbieduncan
Sep 16, 2006, 04:22 AM
Which version of XCode are you using? Did you install ALL the optional support packages as Java project templates may not be installed by default...

I see the Java section on XCode 2.3 on OSX 10.4.7

bousozoku
Sep 16, 2006, 04:23 AM
You should see something like the screen shot I've attached.

mufflon
Sep 16, 2006, 05:02 AM
well it's been mentioned earlier, try finding your project using the terminal.
When found use
javac *filename*

which will try to compile your application, if it works then you know that you have a valid distribution of java installed (which afaik should be default, but still worthwhile to check).

The project you've posted seems kinda strange to me overall, but when you begin programming I suppose everyone has to find their own way to implement stuff - based on personal prefences and structure.

You could also try to install eclipse instead (http://www.eclipse.org/), which is a nice alternative to xcode an is available on all platforms - free

Jasonbot
Sep 16, 2006, 06:19 AM
I'll try re-install Xcode when I get back to my mac tomorrow. Until then is java and standard option when installing xcode? or is it one of those custom check box options??

Eraserhead
Sep 16, 2006, 12:30 PM
I'll try re-install Xcode when I get back to my mac tomorrow. Until then is java and standard option when installing xcode? or is it one of those custom check box options??

Can't remember TBH, look through the options and install all java related ones, you should also get the latest version of the Java development software from Apple's Developer website.

You will probably find it easier to compile files via the command line using the command javac but a Java Tool Project should be fine.

I would say that this isn't as easy as it should be.

bousozoku
Sep 16, 2006, 12:37 PM
I'll try re-install Xcode when I get back to my mac tomorrow. Until then is java and standard option when installing xcode? or is it one of those custom check box options??

There are custom options? :D I've never done anything but a standard installation and gotten Java, along with everything else.

Jasonbot
Sep 16, 2006, 01:32 PM
Is xcode really that hard for java compiling? I think I'll try Eclipse. Right Now I'm using J J Edit It's only a few kbs and it's freeware

bousozoku
Sep 16, 2006, 01:46 PM
It's not that Xcode makes Java compiling difficult, but like many IDEs, it works from a project. It shouldn't force you into the project but it's a choice their designers made.

Eclipse really doesn't seem any easier to use--it's just different. JEdit seems to only be an editor--you can't create a product with it. You'll find quite a few threads on everyone's favourite tools here. I use a number of them but for Java, I tend to stick with jGrasp and NetBeans for smaller projects.

larswik
Sep 16, 2006, 01:50 PM
Hey I just started learning Java and you are way ahead of me. Just for fun on my side I copied your code and pasted it into jEdit which is the program that I am learning with and then I use the Terminal to complie it. It did pop up with a result.

I understood some of your code since that is the chapter that I am reading right now. But what popped up after compiling the code and running it wasn't what I thought was going to pop up.

But it seemed to work fine using that method. I hope that ws OK that I ran your code as a fun test for my self.

-Lars

Jasonbot
Sep 16, 2006, 02:49 PM
Hey I just started learning Java and you are way ahead of me. Just for fun on my side I copied your code and pasted it into jEdit which is the program that I am learning with and then I use the Terminal to complie it. It did pop up with a result.

I understood some of your code since that is the chapter that I am reading right now. But what popped up after compiling the code and running it wasn't what I thought was going to pop up.

But it seemed to work fine using that method. I hope that ws OK that I ran your code as a fun test for my self.

-Lars



Wow, I have a fan! I really don't mind that you used My code. It was my 3rd lesson @ school, I hope I'll become a really 1337 programer one day.

Are you learning from a book or something? Is it hard?

odedia
Sep 16, 2006, 04:03 PM
Use Eclipse for pure Java, forget XCode. XCode is good for many things, Pure java isn't one of them. It works, but there are better options out there.

larswik
Sep 17, 2006, 01:30 AM
yap, Java for Dummies book. I'm not planning on being a programmer but I need some software for a hotel project to communicat with many hotels using Telnet and Java. There is no spacific program for what I need so I decuded to learn Java to try to create it.

The one thing with your code what I was expecting was to see the other stuff like Age, and numbers poping up since you used the INT / DOUBLE /SHORT /FLOAT and so on but all that I got was a window that popped up with your name on it and the Cancel / No /Yes button.

What did all that other stuff do since it was typled in? I twas neat seeign the code since I just read that page the other night on CHAR / FLOAT / SHORT /BYTE and so on. and having to state what your Variables are before you declare a Variable, if I got that right.

-Lars

Jasonbot
Sep 17, 2006, 02:41 AM
No, my code's very basic. It's just to outline how you can use variables instead of typing in the different numbers/characters everytime. I don't know much yet, mybe next lesson we'll learn how to make the variables do some cool stuff?

But yes, you have to declare your variables in the variables part of teh code before you can use them...

Jasonbot
Sep 17, 2006, 02:53 AM
Cool, xcode works! I used the right project and everything goes smoothly! But is there anyway to make a .class file instead of a .jar file? Thanx:D

bousozoku
Sep 17, 2006, 03:10 AM
Cool, xcode works! I used the right project and everything goes smoothly! But is there anyway to make a .class file instead of a .jar file? Thanx:D

I don't know of a way but the .class file is in the .jar (Java ARchive) file. Besides that, the .jar file can be double-clicked on Mac OS X to launch it.

Jasonbot
Sep 17, 2006, 03:16 AM
I guess, I could also compiule it in terminal.

Just some basic text colour help now -How do I know what colour text means what?

EDIT: I understand about the colours now. I want to know how I can make the syntax colours in xcode look similar to the ones in JCreator(the app we are using @ school)

Eraserhead
Sep 17, 2006, 04:13 AM
You can find/change all of the colours in Xcode preferences (font and colour options), basically green is a comment, red is a string of text, blue is a character/number, purple is a keyword (eg for java, int, float, public, static, import etc. etc.), black is any other text in the document.

Jasonbot
Sep 17, 2006, 07:02 AM
Ok, The colours are just confusing me because I used (Useless) JCreator @ school :(

mufflon
Sep 17, 2006, 04:19 PM
But yes, you have to declare your variables in the variables part of teh code before you can use them...

This is not really the topic of the thread, but you don't have to

public variables ()
{

String name = "Jason";
String surname = "BoTHa";
(...)

JOptionPane.showConfirmDialog(null,name);

}

As it is enough to declare them in the main part of your class.
This doesn't mean you can't do this if you want to, it might be more pleasing to you, but it also means you don't have to if you don't :)

Jasonbot
Sep 17, 2006, 11:28 PM
O! that's pretty cool. I guess its just neater if you do them before?

Jasonbot
Sep 19, 2006, 10:49 AM
here it is, it multiplies:D
http://rapidshare.de/files/33681093/Learning.jar.html

mufflon
Sep 19, 2006, 01:03 PM
well the problem is that you have 2 separate functions in the class, meaning less clean code.


class firstClass {

//something here

public int something() {

int variable1 = 2;

int variable2 = 3;

}
}

class anotherClass {

//some stuff happens here
}


generally it's a lot neater to have all code and variables you need defined locally in every function - thus minimizing calls to functions in other / same classes as well minimizing so called global variables (variables that any function in a class can call to - this is very much needed to minimize memory usage, as well as to have variables only specific classes need only be defined in their respective places (less headache)

mufflon
Sep 19, 2006, 01:08 PM
well the problem is that you have 2 separate functions in the class, meaning less clean code.


import java.util.*;


public class SortedList<E extends Comparable<? super E>> implements Iterable {
private LinkedList<E> theList;
private boolean duplicates;

public SortedList() {
this.theList = new LinkedList<E>();
this.duplicates = true;
}

public SortedList(boolean d) {
this.theList = new LinkedList<E>();
this.duplicates = d;
}

public boolean insert(E x) {
if (!this.theList.isEmpty()) {
for (ListIterator<E> i = this.theList.listIterator(); i.hasNext(); ) {
E temp = i.next();

if (temp.compareTo(x) == 0 && !this.duplicates) {
return false;
}
if (temp.compareTo(x) >= 0) {
//as-ful implementation
i.remove();
i.add(x);
i.add(temp);
return true;
}
}

this.theList.add(x);
return true;
} else {
this.theList.add(x);
return true;
}
}

public void remove(E x) {
if(!this.theList.isEmpty()) {
for (ListIterator<E> i = this.theList.listIterator(); i.hasNext(); ) {
if(i.next().compareTo(x) == 0) {
i.remove();
}
}
}
}

public E find(E x) {
if(!this.theList.isEmpty()) {
for (ListIterator<E> i = this.theList.listIterator(); i.hasNext(); ) {
E temp = i.next();
if(temp.compareTo(x) == 0) {
return temp;
}
}
}
return null;
}

public int size() {
return this.theList.size();
}

public boolean isEmpty() {
return this.theList.isEmpty();
}

public Iterator iterator() {
// TODO Auto-generated method stub
return this.theList.iterator();
}



}



It's usually a lot more simple to keep variables where you need them and only there, nowhere else.

This is from a recent hand in assignment in my java course, where we implemented a list that arranges elements in a specific order (defined by the interface compareTo) - the easier structure you have the easier your code is to implement, debug and use.

edit: doh intended to just remove some of what I wrote in the earlier post

Jasonbot
Sep 19, 2006, 10:55 PM
Ok, please excuse me but I don't really understand. You said I have two seperate class functions? here's my code

//
// Learning.java
// Learning
//
// Created by Jason on 2006/09/18.
// Copyright (c) 2006 __MyCompanyName__. All rights reserved.
//
import javax.swing.*;

public class Learning
{
public Learning()
{
//values
String noa = "";
String nob = "";

double answer = 0;



//other
String header = "Calculator";
float number = 1345213f;
int hi1 = 31254;
int hi2 = 345;
double hi3 = hi1/hi2;
char yes= 'y';

//First digit
noa = JOptionPane.showInputDialog(null, "value 1?", "What do u wanna know?", JOptionPane.QUESTION_MESSAGE);
JOptionPane.showConfirmDialog(null,"Your number = "+noa , "number1", JOptionPane.PLAIN_MESSAGE, JOptionPane.PLAIN_MESSAGE);

//Second Digit
nob = JOptionPane.showInputDialog(null, "value 2?", "What do u wanna know?", JOptionPane.QUESTION_MESSAGE);
JOptionPane.showConfirmDialog(null,"Your number = "+nob ,"number2", JOptionPane.PLAIN_MESSAGE, JOptionPane.PLAIN_MESSAGE);

//Maths
double a = Double.parseDouble(noa);
double b = Double.parseDouble(nob);
double ans = a*b;

//Your answer
JOptionPane.showConfirmDialog(null, "Number 1 = " +noa +"\nNumber 2 = " +nob +"\n" +noa +" x " +nob +"="+ans, "ANSWER", JOptionPane.PLAIN_MESSAGE, JOptionPane.INFORMATION_MESSAGE);


//if test

if(ans < 300)

{
JOptionPane.showMessageDialog(null,"Low number");
}

else if (ans > 900)
{
JOptionPane.showMessageDialog(null, "High Number");
}

else
{
JOptionPane.showMessageDialog(null, "Medium number");
}



}
public static void main(String args[])

{
new Learning ();

}

}

robbieduncan
Sep 20, 2006, 01:08 AM
OK some terminology: classes don't have functions. Classes have methods. Some methods are "special" and are called constructors. These create new instances of that class. You can tell which these are as they have the same name as the class and have no return type. You can have as many constructors in a class as you like as long as they have different signatures. You can chain constructors to minimise the amount of code you have to write.

So for example



public class Rectangle
{
float width, height;

public Rectangle
{
this(0.0); // If no size is given the create a rectangle with a width=height=0.0
}

public Rectangle(float size)
{
this(size,size); // If only one size is given create a square
}

public Rectangle(float width, float height)
{
this.width = width;
this.height = height;
}
}

mufflon
Sep 20, 2006, 07:01 AM
I always end up mixing up the terminology :(

ah well, what my previous post, jason, was referring to, was your inititial post

import javax.swing.*;

public class variables
{
public variables ()
{

String name = "Jason";
String surname = "BoTHa";
int age = 17;
char gender = 'm';
double height = 148.9;

boolean married = true;
short treasures_found = 12;
byte shot = 4;
float bank_account = 8.1f;
long distance_traveled = 7834;

JOptionPane.showConfirmDialog(null,name);


}

public static void main(String args[])
{
new variables ();
}
}

the other code is better, but I don't know how valid java swing is for learning java - it only creates a gui, whereas you'll need to understand while/for loops / recursive function to really enjoy most programming languages - stuff which imo is better learned in text-based applications than in a gui.

Jasonbot
Sep 20, 2006, 08:04 AM
Ok, I guess I've got some basic terminology, cool. But now I want my calculator program to be able to have the user change the signs, in this section of code I used "ifs" (my teacher said I should) but the problem is that the code doesnt want to do the calculations, it rather refers to the first line "double ans = 0;" instead of all my "ifs" how do I rectify this to display the answer as this string "ans = a*b;"? THANKS:D

double ans = 0;

if (operation == "1")
{
ans = a*b;
JOptionPane.showMessageDialog(null, ans);
}

else if (operation == "2")
{
ans = a/b;
JOptionPane.showMessageDialog(null, ans);
}

else if (operation == "3")
{
ans = a-b;
JOptionPane.showMessageDialog(null, ans);
}

else if (operation == "4")
{
ans = a+b;
JOptionPane.showMessageDialog(null, ans);
}

else
{
ans = 0;
JOptionPane.showMessageDialog(null, ans);
}




//Your answer
JOptionPane.showConfirmDialog(null, "Number 1 = " +noa +"\nNumber 2 = " +nob +"\n" +noa +" x " +nob +"="+ans, "ANSWER", JOptionPane.PLAIN_MESSAGE, JOptionPane.INFORMATION_MESSAGE);



EDIT: I fixed it, the error was with defining the variables... But now I was wondering if u can do Trig in java?

Here's the link:http://rapidshare.de/files/33793627/Learning.jar.html

mufflon
Sep 20, 2006, 09:33 AM
yeah you can do trigonometrical functions in java, using the math library (standard java package)

check out this link (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html) for reference

once you've imported java.Math.*

you can call methods using Math.*method*(something);

Jasonbot
Sep 20, 2006, 10:06 AM
Cool, do I just go import java.Math.*; in the 1st line?

Another Problem:
//First digit
noa = JOptionPane.showInputDialog(null, "Enter your First value:", "Learning V2.1", JOptionPane.QUESTION_MESSAGE);

double a = Double.parseDouble(noa);


if (a != double)
{
noa = JOptionPane.showInputDialog(null, "Enter your First value:", "Learning V2.1", JOptionPane.QUESTION_MESSAGE);
}
else if (a == double)
{
JOptionPane.showConfirmDialog(null,"Your number = "+noa , "Learning V2.1", JOptionPane.PLAIN_MESSAGE, JOptionPane.PLAIN_MESSAGE);
}
else
{
noa = JOptionPane.showInputDialog(null, "Enter your First value:", "Learning V2.1", JOptionPane.QUESTION_MESSAGE);
}

Basically I want the app not to die when someone enters the wrong value but rather to go back to the previous JOptionPane when doing so, thanksX_X

mufflon
Sep 20, 2006, 11:33 AM
well if they enter the wrong value you should do:

if (whateverNumber > maximum) {

ignore imput, go back to last JOptionPane

}

if (whateverNumber < minimum) {

ignore imput, go back to last JOptionPane

}


and you could also use (if an integer):

Integer.valueOf(input) which tries to check if it's an integer, if not it tries to get a value from the input

another possibility


try {
*input command*
} catch (inputMismatchError e) {
// comes here if input isn't a number)
go back to last JOptionPane


And you import the math lib just like you import your swing component - import *whatever* before the class declaration

mufflon
Sep 20, 2006, 11:43 AM
if you have everything implemented in a method within a class you can do something like this:

class myClass {
private int currentAction;
private int oldValue;
private int newValue;

public static void main(String[] args) {
// will run this method first anyhow
this.currentAction = 0;
this.myMethod();
}

public void myMethod() {
this.oldValue = this.newValue;

if(this.currentAction == 0) {
boolean quit = false;
// do your first command here
// set this.currentAction to something else
// input value goes to newValue first, then you handle calculations
}
else if (this.currentAction == 1) {
// for example: adding two numbers together
}
else if(this.currentAction == *someothervalue*) {

}
else if(this.currentAction == *your last value*) {
// a panel pops up to ask if you really want to quit
// sets the boolean quit to true
}
// if quit is not true you don't execute this part of the code
if(!quit) {
this.myMethod();
// calls itself again, thus you will have an endless self-calling loop
// until you chose to end it with quit = true
}
}
}


some of this might be too hard for you, but I've tried to make it simple and easy to understand, implementing your first own application is most certainly a healthy experience :)

Jasonbot
Sep 20, 2006, 12:02 PM
Yep, thnk you for all your effort but my attempts are in vain, I just can't get it? I know I must just add another elseif with some stuff in it but the rest is blank??? I'll try some more, won't give up:D

mufflon
Sep 20, 2006, 12:58 PM
okay just tell me where you got stuck

the code can also be simplified like this:


class someClass {
public static void main(String[] args) {
this.myMethod();
}

public void myMethod() {
// code that will be run over and over again
this.myMethod();
}
}


this is a simplified while loop (with a recursive method rather than a real while loop). Recursive means in this case a method that calls itself infinetly.


class someClass2 {
private int aNum = 1;
public static void main(String[] args) {
this.myMethod();
}

public void myMethod() {
System.out.println(String.valueOf(this.aNum));
this.aNum++;
if(this.aNum < 50) {
this.myMethod();
}
}
}


this code should help you understand the overall code structure, but you must run it in a terminal for you to really get any output.
- only place it in your java development environment and go for it - should compile without any real hickups.
if you place it in a folder, say your desktop folder

then you can reach the file by entering this in the terminal:

ls
cd Desktop
javac *.java
java someClass2


"ls" is a useful command to check what files and folders recides in your current terminal "view".

"cd Desktop" will switch your view from your user folder to your desktop

"javac *.java" should compile everything ending with .java in the current directory. "javac *filename" will ofc also work.
"java *filename*" will let you run the java application in the terminal.

Jasonbot
Sep 20, 2006, 01:12 PM
There's an error with your code:

"this.myMethod();","someClass2.java:4: non-static variable this cannot be referenced from a static context"

But anyway, all I want is a line in my if statements that will go back to the JOptionPane from before if you type in anything that is not a double instead of crashing? Is there no easier way?

Why can't this work with double as a value??? if (a != double)
{
noa = JOptionPane.showInputDialog(null, "Enter your First value:", "Learning V2.1", JOptionPane.QUESTION_MESSAGE);
}

mufflon
Sep 20, 2006, 01:30 PM
class mainClass {
public static void main(String[] args) {
someClass2 test = new someClass2(1);
}
}

class someClass2 {
private int aNum;

public someClass2(int i) {
this.aNum = i;
this.myMethod();
}

public void myMethod() {
System.out.println(String.valueOf(this.aNum));
this.aNum++;
if(this.aNum < 50) {
this.myMethod();
}
}
}

should work now :)
(run with the "mainClass")

mufflon
Sep 20, 2006, 01:38 PM
You can use the following code


try{
Double something = Double.doubleValue(input);
} catch(NumberFormatException e) {
// insert code to go back
}



you can't "jump between different JPane afaik unless you use a loop or a recursive function.

to be able to do this you'll need to import
java.lang.NumberFormatException to be able to catch the exception.

gl

Jasonbot
Sep 20, 2006, 02:04 PM
Ok, I tried the catch thing but maybe this is a little out of my league? I dont really have any idea what i'm doing. Maybe, as an alternative you could help me make a while loop to quit when I input a 5 in this line:
//operation
String operation = "";
operation = JOptionPane.showInputDialog(null, "enter the operation" + "\n 1=multiply" +"\n 2=divide" +"\n 3=subtract" +"\n 4=add", "Learning V2.1", JOptionPane.PLAIN_MESSAGE);


Does the while code go in that line or does it go with the ifs? One day I'll get my correct JOption pane:D

mufflon
Sep 20, 2006, 02:40 PM
well a try / catch means more or less:

try {
code
} catch(an error that might occur) {
//do something about it
// example to kill the application using System.exit(1)
}

tbh I don't know if what you aspire to make might be too hard, I'll try to work something out for tomorrow, involving less swing-interface thingies and more understandable code (well haven't really got the time, but this seems like a reasonable use of my spare time :) )

Jasonbot
Sep 20, 2006, 02:54 PM
Wow, thank you. You are like my teacher x56 r something:D How can I make it up to you, surely you won't do all this for nothing?

mufflon
Sep 20, 2006, 03:21 PM
Well you can tell me any inside information from apple *wink* *wink*

Everyone aspires to be something, we just happen to share the same goal - to be better at programming. Our age and and amount of completed projects varies probably to a great deal, but I was an aspiring new coder too - and still am, there's always so much more to do.

Anyhow, I intended to read som uni math, but got bored.
here is an input class for java:

import java.io.*;

class inPut {

Object item;
private InputStreamReader isr = new InputStreamReader( System.in );
private BufferedReader stdin = new BufferedReader( isr );
private boolean debug;
private String lastLine;
private int lastInt = 0;

public inPut() {
this.debug = false;
}

public inPut(boolean d) {
this.debug = d;
}

/**
* reads the next line of text, if IO error it will run another set of this
*/
public String nextLine() {
try {

String input = stdin.readLine();

// if input isn't null or shorter than String.length = 1 returns string

if(input != null || input.length() > 0) {
this.lastLine = input;
return this.lastLine;
}

} catch(IOException e) {

// if debug is true and error is reached application tells why and dies
// otherwise business as usual (retries)

if (this.debug) {
System.out.println("IOException error");
System.exit(1);
}

this.nextLine();
}
// if
return null;
}

public int nextInt() {

try {

String input = stdin.readLine();

// if input isn't null or shorter than String.length = 1 returns string

if(input != null || input.length() > 0) {
this.lastInt = Integer.valueOf(input);
return this.lastInt;
}

} catch(IOException e) {

// if debug is true and error is reached application tells why and dies
// otherwise business as usual (retries)

if (this.debug) {
System.out.println("IOException error");
System.exit(1);
}

this.nextInt();
}
return 0;
}

// same as the two methods above, only prints out some text too before input is needed
public int nextInt(String str) {
System.out.println(str);
return this.nextInt();
}

public String nextString(String str) {
System.out.println(str);
return this.nextLine();
}

public int getLastInt() {

return this.lastInt;
}

public String getLastLine() {

return this.lastLine;

}
}

(not on my main comp atm so no tar ball :(

Anyhow you declare this using:

inPut myInput = new inPut();
standard way

inPut myInput = new inPut(boolean debug);
this also allows some minor debugging - it will kill the application if you can't read anything

the following commands are available:

(if you myInput can be anything - it's the "name" you declare it as)

myInput.nextLine()
// returns the next line (end with [ENTER]) as a String
// if you only press enter return will be "null"
myInput.nextInt()
// returns the next int inserted
// if nothing then you get a "0" as return
myInput.nextLine(String str)
// returns same as nextLine() only prints the String str first
myInput.nextInt(String str)
// same as nextInt() only prints out the String str first
myInput.getLastInt()
// returns the latest int read with myInput.nextInt() / nextInt(String str)
myInput.getLastLine()
// returns the latest String read with myInput.nextLine() / nextLine(String str)



I will make the code more secure than this tomorrow though, but this should be enough to start implementing stuff.

And rather than just posting untested code I've actually compiled the stuff this time (but no test class - too late :) )

Remember, this is terminal only - don't mix this with your GUI-thingies =P

mufflon
Sep 20, 2006, 03:48 PM
and a way to implement ths without challenging your skills as a develop too much yet is to do this:


int action = 1;
String command;
inPut myInput = new inPut(true)

// as long as action isn't 0 this will continue
while (action != 0) {
if (action == 1)
// this is where you define the first num
int temp = myInput.nextInt("a number please: ");
// who cares what temp does, we have it all in the myInput.getLastIn()
// but we go to next step:
action = 2;
}
if (action == 2) {
String command = myInput.nextLine("what do you want to do? + - / * quit");
action = 3;
continue;
}
if (action == 3) {
switch(command) {
case "+":
System.out.println(String.valueOf(myInput.getLastInt() + myInput.getInt("and last num please")));
break;
// continue here;
case "quit":
// ser wishes to quit - application dies
action = 0;
break;
default:
// if neither command was inserted, return to 2
action = 2;
}
}
}


well it should be close to this anyhow
notice how the while lope ends when the user inserts "quit"

this may ofc be elaborated and experimented, the code itself should be good, but might have some bugs (running late over here ;) )

janey
Sep 20, 2006, 08:36 PM
yap, Java for Dummies book. I'm not planning on being a programmer but I need some software for a hotel project to communicat with many hotels using Telnet and Java. There is no spacific program for what I need so I decuded to learn Java to try to create it.

The one thing with your code what I was expecting was to see the other stuff like Age, and numbers poping up since you used the INT / DOUBLE /SHORT /FLOAT and so on but all that I got was a window that popped up with your name on it and the Cancel / No /Yes button.

What did all that other stuff do since it was typled in? I twas neat seeign the code since I just read that page the other night on CHAR / FLOAT / SHORT /BYTE and so on. and having to state what your Variables are before you declare a Variable, if I got that right.

-Lars
Didn't want to interrupt the flow of conversation, but the Dummies series is really lacking in anything useful. If you're looking for a good introduction to Java, i suggest a book like Thinking in Java by Bruce Eckel, which is VERY well written and easy to understand.
The third edition of the book is free online ( http://www.mindview.net/Books/TIJ ), except it doesn't cover j2se5 in any significant detail, if i remember correctly. The fourth edition (amazon link (http://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/sr=8-1/qid=1158801918/ref=pd_bbs_1/104-4106377-1355954?ie=UTF8&s=books)) is more recent and covers the latest developments.

However, if you're looking for more on swing and all that pretty stuff...Deitel's java book was pretty good when I last looked through it.

Also, I don't know if anyone else answered your question, but the rest of the variables and stuff (age, gender, etc.) are still "there", but aren't being used - if you look at the JOptionPane.showConfirmDialog(null,name) line, you'll see that only the name is supposed to be displayed.

And you can sorta take a shortcut, instead of doing something like

int someVariable;
someVariable = 1;
you can just put
int someVariable = 1;
thereby declaring and assigning the variable in one easy step. it'll still be there for you to use when you need it, so if you do something like:

JOptionPane.showConfirmDialog(null,someVariable);

it should give you another dialog box giving you whatever was assigned to that variable.

Nothing except what you explicitly wrote should be showing up. So basically, you can declare tons and tons of variables in your code, and never display it to the user. That's a different, separate step.

Jasonbot
Sep 21, 2006, 07:23 AM
lol, I'm not using Java for dummies. I'm using Java 2# manual for JCreator:D I'm almost on it doing the code and all, I think i'll get it soon

mufflon
Sep 21, 2006, 07:50 AM
lol, I'm not using Java for dummies. I'm using Java 2# manual for JCreator I'm almost on it doing the code and all, I think i'll get it soon


well the one who janey replied to was larswik, not yourself :)
Everyone isn't lucky enough to actually study a programming language @ school / uni, but have to rely on books that might or might not be what they are looking for.

Jasonbot
Sep 21, 2006, 10:35 PM
My bad! I guess I am pretty lucky, I asked some guys @ school about my code and they laughed! And gave me this solution for the quit thing:

//catch error
try
{
a = Double.parseDouble(noa);
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null,"ERROR: Please enter a valid number");

new Learning();
}

mufflon
Sep 22, 2006, 01:12 AM
well yeah, the try / catch statement is pretty powerful, so how have you structured your code now then? A repeating method or a loop? ;)

larswik
Sep 24, 2006, 04:02 PM
a little late posting here. The method that is workign for me is jEdit, the Apple Terminal and the Java for Dummies. Much of the time I have to go back and re read a section. So far I am on page 123 of 800 pages and I understand most of it. That is the beauty of this Fourm because it is my missing link. When I re read a section and I don't understand something the friendly people here help me answer it : )

Thanks for clearing up all the other info on the age, gender and other info that was on the page. I see now that it is there and not being used. It must have been an exercise from his book or something. That would explane the extra coding.

Speaking of new questions I need to post a new one.

thanks,

-Lars