View Single Post
Old 10-05-2012, 05:22 PM   PM User | #1
Jposemato
New to the CF scene

 
Join Date: Oct 2012
Posts: 4
Thanks: 1
Thanked 0 Times in 0 Posts
Jposemato is an unknown quantity at this point
String to strings? Help please

Hi guys, Im pretty new to Java so bare with me as I make a complete fool of myself. Im trying to start out by making a simple calculator, capable of the functions plus, minus, divide, multiply. I had no trouble doing this within eclipse, however turning it into a windowed program made it a lot harder for me.

The basic problem im having is using the method:
String = JOptionPane.showInputDialog("text")

Mine looks like this:
Code:
inStr1 = JOptionPane.showInputDialog("Please Input an Equation\n" +
				"* = multiply, / = Divide,\n" +
				"Include spaces and Decimals (Using Doubles!)\n" +
				"For example: 2.0 + 4.2, Then ENTER!");
This works all fine and dandy however I can no longer perform math with this, as it is a string. I know how to use the Double.parseDoube(), however I need it to break a line like "2.0 + 4.2" into Double num1 = 2.0; String sign = +; Double num2 = 4.2;

A good chunk of the problematic area, As you can see I tried playing around with a few things but I am completely lost at this point lol, thanks in advance.
Code:
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.util.regex.*;


public class Calculator {

    static Scanner console = new Scanner(System.in);
    
	public static void main(String[] args)
	{
//		System.out.println("Please Input an Equation\n" +
//				"* = multiply, / = Divide,\n" +     <--- Non-Windowed
//				"Include spaces and Decimals (Using Doubles!)\n" +
//				"For example: 2.0 + 4.2, Then ENTER!");

		double num1;
		double num2;
		double sum;
		String sign;
		String num1a;
		String num2a;
		String inStr1;
		String inStr2;
		String outStr;
		int repeats;
		num1a = "a";
		num2a = "b";
		sum = 1;
		
        inStr1 = JOptionPane.showInputDialog("Please Input an Equation\n" +
				"* = multiply, / = Divide,\n" +
				"Include spaces and Decimals (Using Doubles!)\n" +
				"For example: 2.0 + 4.2, Then ENTER!");
		String data = inStr1;
		String[] values = data.split(" ");
		num1a = String[0];
		sign = String[1];
		num2a = String[2];
		
 		num1 = Double.parseDouble(num1a);
		num2 = Double.parseDouble(num2a);
		
//		num1 = console.nextDouble();  <--- Old code (The none window
//		sign = console.next();                                   way)
//		num2 = console.nextDouble();
		if (sign.equals("+")){
			sum = num1 + num2;
		}
		if (sign.equals("-")){
			sum = num1 - num2;
		}
		if (sign.equals("*")){
			sum = num1 * num2;
		}
		if (sign.equals("/")){
			sum = num1 / num2;
		}
I believe the part here: String[] values = data.split(" "); is the proper way of doing it, however I don't think the String[0] part is right.
Jposemato is offline   Reply With Quote