Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mufflon

macrumors 6502
Sep 15, 2006
264
2
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

PHP:
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 :)
 

mufflon

macrumors 6502
Sep 15, 2006
264
2
well the problem is that you have 2 separate functions in the class, meaning less clean code.

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

macrumors 6502
Sep 15, 2006
264
2
well the problem is that you have 2 separate functions in the class, meaning less clean code.

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

macrumors 68020
Original poster
Aug 15, 2006
2,467
0
The Rainbow Nation RSA
Ok, please excuse me but I don't really understand. You said I have two seperate class functions? here's my code

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

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
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

Code:
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

macrumors 6502
Sep 15, 2006
264
2
I always end up mixing up the terminology :(

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

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 ();
    }
}

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

macrumors 68020
Original poster
Aug 15, 2006
2,467
0
The Rainbow Nation RSA
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

Code:
	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

macrumors 6502
Sep 15, 2006
264
2
yeah you can do trigonometrical functions in java, using the math library (standard java package)

check out this link for reference

once you've imported java.Math.*

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

Jasonbot

macrumors 68020
Original poster
Aug 15, 2006
2,467
0
The Rainbow Nation RSA
Cool, do I just go import java.Math.*; in the 1st line?

Another Problem:
Code:
//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

macrumors 6502
Sep 15, 2006
264
2
well if they enter the wrong value you should do:
Code:
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

Code:
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

macrumors 6502
Sep 15, 2006
264
2
if you have everything implemented in a method within a class you can do something like this:
Code:
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

macrumors 68020
Original poster
Aug 15, 2006
2,467
0
The Rainbow Nation RSA
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

macrumors 6502
Sep 15, 2006
264
2
okay just tell me where you got stuck

the code can also be simplified like this:

Code:
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.

Code:
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:
Code:
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

macrumors 68020
Original poster
Aug 15, 2006
2,467
0
The Rainbow Nation RSA
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???
Code:
	if  (a != double)
	{
		noa = JOptionPane.showInputDialog(null, "Enter your First value:", "Learning V2.1", JOptionPane.QUESTION_MESSAGE);	
	}
 

mufflon

macrumors 6502
Sep 15, 2006
264
2
Code:
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

macrumors 6502
Sep 15, 2006
264
2
You can use the following code

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

macrumors 68020
Original poster
Aug 15, 2006
2,467
0
The Rainbow Nation RSA
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:
Code:
//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

macrumors 6502
Sep 15, 2006
264
2
well a try / catch means more or less:

Code:
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 :) )
 

mufflon

macrumors 6502
Sep 15, 2006
264
2
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:

Code:
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:

Code:
inPut myInput = new inPut();
standard way

Code:
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

macrumors 6502
Sep 15, 2006
264
2
and a way to implement ths without challenging your skills as a develop too much yet is to do this:

Code:
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

macrumors 603
Dec 20, 2002
5,316
0
sunny los angeles
larswik said:
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) 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
Code:
int someVariable;
someVariable = 1;
you can just put
Code:
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:
Code:
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.