LinuxQuestions.org
Go Job Hunting at the LQ Job Marketplace
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 01-02-2004, 11:41 PM   #1
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 63
Angry Float/Double to String?


I'm trying to make a graphical program in Java (my first shot...ghehe) and I'm having a little hard time in here.
The program is a very simple calculator. It asks for 3 user's input. The first one is a number, the second is an operator ( + - * /) and the last one is another number. As it's very hard-coded, I'm trying to get it to run first

Code:
// import API-JOptionPane which holds the dialog boxes
import javax.swing.JOptionPane;

class Calc {
  
  public static void main ( String[] arguments ) {
    
    String userInput1, userInput2, userOperator;
    double userTotal;
    
     // Display a message to the user:
    JOptionPane.showMessageDialog( null, "Welcome to my hard-coded Program!");
                                        
    userInput1 =     JOptionPane.showInputDialog ( null, "Insert a number" );
    userOperator = JOptionPane.showInputDialog ( null, "What to do?");
    userInput2 =     JOptionPane.showInputDialog ( "Insert a second number" );
    
    // ----- Program comes here ---- //
    //userTotal = Integer.parseInt(userInput1) + Integer.parseInt(userInput2);
    
   JOptionPane.showMessageDialog ( null, userInput1 + " " + userOperator + " " + 
                                                       userInput2 + " = " + userTotal);
            
  }
}
The problem is... Me, with all my lack of wisdom, have no idea how to make the user "userOperator" to perform a math operation. I know that in Java, all user's inputs are in Strings form, so I've to convert it (parseInt) into integers to make math operations. What I cannot think is how to make the operator (userOperator) to work together with both user's input (userInput1 and userInput2). The uncommented line:

//userTotal = Integer.parseInt(userInput1) + Integer.parseInt(userInput2);

is useless. But converts the Strings into Integers. But it will always add the inputs, and I want it to be a user defined operation.

Any idea fellows?

Thanks in advance
 
Old 01-02-2004, 11:53 PM   #2
ter_roshak
Member
 
Registered: May 2001
Location: Everett, WA
Distribution: Gentoo, RedHat
Posts: 102

Rep: Reputation: 15
You may want to use a switch statement to evaluate the value of your userOperator compared to the various functions that you would want to implement on your calculator.

You would have to parse your userOperator into a char and compare it to all of your operators as chars like so:

Code:
switch (userOperator)
{
  case '+':
    userTotal = Integer.parseInt(userInput1) + Integer.parseInt(userInput2) ;
      break;
  case '-':
    userTotal = Integer.parseInt(userInput1) - Integer.parseInt(userInput2) ;
      break;
   //etc...
}
Just a thought...

Josh
 
Old 01-03-2004, 12:01 AM   #3
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 63
Oh man, thanks a lot . I'll try it out.

Once again, many thanks
 
Old 01-03-2004, 12:25 AM   #4
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 63
almost there. I still fall into the converting problem. I know that Java can parse String to Integer, but I cannot make a String into a Char. Here is how the program looks like now:

Code:
// import API-JOptionPane which holds the dialog boxes
import javax.swing.JOptionPane;

class Calc {
  
  public static void main ( String[] arguments ) {
    
    String userInput1, userInput2, userOperator;
    double userTotal;
    
     // Display a message to the user:
    JOptionPane.showMessageDialog( null, "Welcome to my hard-coded Program!");
                                        
    userInput1 =     JOptionPane.showInputDialog ( null, "Insert a number" );
    userOperator = JOptionPane.showInputDialog ( null, "What to do?");
    userInput2 =     JOptionPane.showInputDialog ( null, "Insert a second number" );
    
    switch (userOperator)
    {
      case '+':
        userTotal = Integer.parseInt(userInput1) + Integer.parseInt(userInput2) ;
        break;
        
      case '-':
        userTotal = Integer.parseInt(userInput1) - Integer.parseInt(userInput2) ;
        break;
        
      case '*':
        userTotal = Integer.parseInt(userInput1) * Integer.parseInt(userInput2) ;
        break;
        
      case '/':
        userTotal = Integer.parseInt(userInput1) / Integer.parseInt(userInput2) ;
        break;
        
      default:
        JOptionPane.showMessageDialog ( null, "Oh no, another bug :'( " );
        break;
    }
    
    JOptionPane.showMessageDialog ( null, userInput1 + " " + userOperator + " " + userInput2 + " = " + userTotal);
    
  }
}
I've tried something like someChar = (char)userOperator; but it fails miserably :

Error: incompatible types
found : java.lang.String
required: int

Is it possible to convert/parse a String into a char?... I've to buy some programming books . Definitely...
 
Old 01-03-2004, 01:10 AM   #5
ter_roshak
Member
 
Registered: May 2001
Location: Everett, WA
Distribution: Gentoo, RedHat
Posts: 102

Rep: Reputation: 15
Hmmm, gimme a minute.

Josh
 
Old 01-03-2004, 09:21 AM   #6
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 63
Thanks a lot ter_roshak. I really appreciated your effort on this . Java is a real pain sometimes . Apparently this type of convertion ain't possible. It accepts Strings to Integer, so I was thinking to get that integer, convert it explicit to char and make the case: based on ASCI code. It did not work. I've tried to do the same in C++;

Code:
// The same thing, but in C++
#include <iostream>
#include <string.h>
using namespace std;

int main()
{

	// Declare variables
	char userInput1, userInput2, userOperator;
	double userTotal;

	// Print a message to the user
	cout << "Welcome to my buggy program :)\n";

	cout << " Insert a number\n ";
	cin >> userInput1;

	cout << " What to you want do with it? ( + - * / )";
	cin >> userOperator;

	cout << " \nInsert a second number\n" ;
	cin >> userInput2;

        // this is just a test, use always "+" or else it will fail.
        // I'd add the other cases later... but since not even 43 is working...
        // there's no need for it :)
	switch ((int)userOperator)
	{
		case 43: 
		{
			userTotal = (int)userInput1 + (int)userInput2;
			cout << userTotal;
			break;
		}
		default:
			cout << "Oh no, another bug :'( ";
			break;
	}

	return 0;

}
also did not work either. When I use explicit converting, it converts the char to integers and indeed gives a strange wrong result. Although, I've to get this working in Java, just thought that more peoples could see the actual problem . The bad thing is that the only way to get user's input in Java is... either console input (when they type the name of the program, followed by arguments) or with dialog boxes (as far as I know). And in both cases, it returns a String . I'm very very lost

Last edited by Mega Man X; 01-03-2004 at 09:24 AM.
 
Old 01-03-2004, 09:42 AM   #7
Langly
LQ Newbie
 
Registered: Jan 2003
Distribution: RH8.0; FreeBSD;
Posts: 17

Rep: Reputation: 0
hmm.. isn't there an String.charat() function in Java?
The main diffrence in C/Java is that in C/++ an string is an array of characters, and in java an string is an object, so you need to use String.charAt() or something like that..
 
Old 01-03-2004, 12:18 PM   #8
ter_roshak
Member
 
Registered: May 2001
Location: Everett, WA
Distribution: Gentoo, RedHat
Posts: 102

Rep: Reputation: 15
That's true, and should have been obvious to me... Use the userOperator.charAt(0) and see if that works for you.

Josh
 
Old 01-03-2004, 01:38 PM   #9
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 63
Yeah!!! That surely did the trick. I've placed userOperator.charAt(0) at my switch-case line and now it works as it should. Pretty nice to see "graphical" under Java .

It's cool the amount of functions Java actually has. I was not aware of charAt, but I was with .substring, .indexOf and .toUpperCase. God dammit, it's just too much . I will get some good Java books. Perhaps one of the Sams Teach yourself series Or else I doubt that Java and I can be good friends and get along. lol

Thanks a lot for the help ter_roshak and Langly. I could not make this without you guys.

Cheers
 
Old 01-03-2004, 04:17 PM   #10
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 63
Thumbs up Improving the Program!

Thanks to you guys, I'm improving the program. Now I've divided the program in functions, and a new object is created. If I don't do that, I cannot learn Java, since I was trowing everything into a C++ like style and that's not the point of Java. Here is what I have so far:

Code:
import javax.swing.JOptionPane;

class Calculator {
    String userInput1, userOperator, userInput2;
    double userTotal = 0.0;
  
    
    double makeCalculations() {
      
        switch ( userOperator.charAt(0) )
        {
            case '+':
            userTotal = Integer.parseInt(userInput1) + Integer.parseInt(userInput2) ;
            break;
        
            case '-':
            userTotal = Integer.parseInt(userInput1) - Integer.parseInt(userInput2) ;
            break;
        
            case '*':
            userTotal = Integer.parseInt(userInput1) * Integer.parseInt(userInput2) ;
            break;
        
            case '/':
            userTotal = Integer.parseInt(userInput1) / Integer.parseInt(userInput2) ;
            break;
        
            default:
            JOptionPane.showMessageDialog ( null, "ghehe, another bug :)" );
            break;
        }
        
        
        return userTotal;
    }
    
    
    void printOut () {
        JOptionPane.showMessageDialog ( null, userInput1 + " " 
                                       + userOperator + " " 
                                       + userInput2 + " = " 
                                       + userTotal);
    }
    
       
       
    public static void main ( String[] argument )
    {
    
       Calculator myCalculator = new Calculator();
       
       myCalculator.userInput1   = JOptionPane.showInputDialog ( null, "Insert the First Number" );
       myCalculator.userOperator = JOptionPane.showInputDialog ( null, "Which operation do to perform?" );
       myCalculator.userInput2   = JOptionPane.showInputDialog ( null, "Insert the Second Number" );

       myCalculator.makeCalculations ();
       myCalculator.printOut ();
   }

}
It's still not good, but Java is not so easy to play with . But it's getting a better shape

Last edited by Mega Man X; 01-03-2004 at 04:18 PM.
 
Old 01-03-2004, 06:35 PM   #11
Tesl
Member
 
Registered: Jun 2003
Location: Durham, UK
Distribution: Slackware 9, Mandrake 9.1
Posts: 163

Rep: Reputation: 30
i dont know if you know this already, but always be sure to look around java.sun.com

http://java.sun.com/j2se/1.4.2/docs/api/index.html

if you had looked at the String class, it would have told you about charAt

let me know any other modifications your after for your calculator, and il try and help out all i can (iv written a calculator in Java before, although the source for it is long since deleted )

as for books, the Java in 21 days is a great book Within a week of reading i was writing graphical and networking applications
 
Old 01-03-2004, 06:36 PM   #12
ter_roshak
Member
 
Registered: May 2001
Location: Everett, WA
Distribution: Gentoo, RedHat
Posts: 102

Rep: Reputation: 15
Its always good to have a good book to reference...<g> Although the Java API by Sun is a good reference also:

http://java.sun.com/j2se/1.4.1/docs/api/

Josh
 
Old 01-03-2004, 06:50 PM   #13
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 63
It's nice to see that you guys also are interested in learning ( and teaching me too, thanks mate ) Java . By the way, you both working pretty "syncronized". Almost the same answer with a minute of difference... ghehe.

I've downloaded that document to my harddrive this morning . I never though it was that well documented. Makes funny of M$ Visual Studio 6.0 which on CD is to install that slow, expensive junk, and 2 (in word, two) CD's for the MSDN ( the crappy help files...).

Thanks again guys.
 
Old 01-03-2004, 06:54 PM   #14
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Original Poster
Rep: Reputation: 63
I was running my program now and I've faced on problem... what if the user divides a number by 0?. I've first tried to:

if userInput2 == 0
userTotal = 0;

but that's lame, and would make the application bad, since you can make 2-0, 2+0, 2*0. But if you do 2/0, you got an invalid statement... Is there anyway to get around it?
Funny isn't it? Sun did all they could to make it easier, but I still got stuck into logical operations... I'm not a wise man :S
 
Old 01-03-2004, 07:31 PM   #15
Tesl
Member
 
Registered: Jun 2003
Location: Durham, UK
Distribution: Slackware 9, Mandrake 9.1
Posts: 163

Rep: Reputation: 30
just break that case statement up a little. Take the second integer and test if it is zero, if its not you can divide as normal, or if it is make a nice little popup or something

off the top of my head: (following code isnt tested or anything)

Code:
case '/':
        if (Integer.parseInt(userInput2) == 0) {
                      JOptionDialog.showMessageDialog(null, "oh no you dont!");
                      break;
        } else {
              userTotal = Integer.parseInt(userInput1) / Integer.parseInt(userInput2) ;
              break;
     }
i havent tested that or anything, but hopefully you get the jist

Last edited by Tesl; 01-03-2004 at 07:33 PM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
count digits of a float || convert float to string nadroj Programming 6 07-11-2005 05:52 PM
c++: float to double conversion ashirazi Programming 6 11-30-2004 05:14 PM
string to double cynthia Programming 4 10-12-2004 03:40 AM
Java | C | C++ - Float/Double question Mega Man X Programming 6 01-01-2004 11:14 AM
java covert double into string iceman47 Programming 10 05-28-2003 11:51 PM


All times are GMT -5. The time now is 10:20 AM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration