New Posts  All Forums:Forum Nav:

Java try-catch help

post #1 of 2
Thread Starter 
Code:
// Calc7 - A four-function calculator with error checking

import

java.awt.*;
import

java.applet.*;

public class Addingmachine extends Applet

{

// ---------------------------------------------------------

// Attributes:

// TextArea total displays running total of calculations

// Label output shows current number being entered

// doubles memVal and curVal are used for calculations

// ---------------------------------------------------------

TextArea

total = new TextArea("", 5, 25, TextArea.SCROLLBARS_VERTICAL_ONLY);

Label

output = new Label();

double memVal = 0;

double curVal = 0;

// ---------------------------------------------------------

// The init() method sets the layout and color.

// It then calls the makeButtons() to do the actual layout

// for the calculator

// ---------------------------------------------------------

public void init()

{

setLayout(

new BorderLayout(5, 5));

setBackground(Color.

lightGray);

add(

"Center", makeButtons());

}

// ---------------------------------------------------------

// The action() method handles the button presses. Since

// this is a Java 1.0 applet, all button actions go through

// the action() method.

// ---------------------------------------------------------

public boolean action(Event ev, Object o)

{

// Local variables

String arg = (String) o;

// Key that was pressed

char c = arg.charAt(0); // First char of key caption

String s =

output.getText(); // Current value of output

// "Special" keys operate on current value

if (arg.equals("Backspace"))
backSpace(s);

else if (arg.equals("C"))
clearAll();

else if (arg.equals("CE"))
clearEntry();

else if (arg.equals("sqrt"))
setCurVal(Math.sqrt(

curVal));

else if (arg.equals("1/x"))
setCurVal(1.0 /

curVal);

else if (arg.equals("+/-"))
setCurVal(-

curVal);

// Digit keys are always added to current value

else if (c >= '0' && c <= '9')
setCurVal(s + c);

// Decimal point added only if not already in output

else if (c == '.')

{

if (s.indexOf(c) < 0)
setCurVal(s + c);

}

// Handle all of the operator keys

else

{

switch (c)

{

case '/':

memVal /= curVal;

break;

case '*':

memVal *= curVal;

break;

case '-':

memVal -= curVal;

break;

case '+':

memVal += curVal;

break;

case '%':

memVal %= curVal;

break;

case '=':

memVal = curVal;

total.append(padText("=============\
", 25));

break;

}

// Display results on the TextArea named total

String memstr =

"" + curVal + " " + c + " \
";

total.append(padText(memstr, 25));

memstr =

"" + memVal + " \
";

total.append(padText(memstr, 25));

// Clear the output Label

curVal = 0;

output.setText("");

}

return true;

}

// ----------------------------------------------------------

// These are utility methods

// ----------------------------------------------------------

String padText(String s,

int size)

{

String temp =

" " + s;

return temp.substring(temp.length() - size);

}

// Handles the backspace key

void backSpace(String s)

{

if (output.getText() != null && !output.getText().equals("")) {

s = s.substring(0, s.length() - 1);

setCurVal(s);

}

else {

}

}

// Handles the 'C' [Clear All] key

void clearAll()

{

total.setText("");

output.setText("");

curVal = memVal = 0;

}

// Handles the 'CE' [Clear Entry] key

void clearEntry()

{

output.setText("");

curVal = 0;

}

// Sets the current value, using a String

void setCurVal(String s)

{

output.setText(s);

curVal = (new Double(s)).doubleValue();

}

// Sets the current value, using a number

void setCurVal(double newValue)

{

curVal = newValue;

String dstring = Double.toString(newValue);

output.setText(dstring);

}

// ---------------------------------------------------------

// This lays out the appearance of the applet, using

// BorderLayout and GridLayout

// The colors used for the buttons may, or may not, appear

// on your copy, depending upon your Web browser

// ---------------------------------------------------------

Panel makeButtons()

{

// Create 4 Panels [p1 through p4]

Panel p =

new Panel(new BorderLayout(5, 5));

Panel p1 =

new Panel(new BorderLayout(5, 5));

Panel p2 =

new Panel(new BorderLayout(5, 5));

Panel p3 =

new Panel(new GridLayout(1, 3, 5, 5));

Panel p4 =

new Panel(new GridLayout(4, 5, 5, 5));

Panel p5 =

new Panel(new BorderLayout(5, 5));

// Add Backspace, CE, and C buttons to p3

p3.setForeground(

new Color(232, 0, 0));

p3.setFont(

new Font("Dialog", Font.PLAIN, 12));

p3.add(

new Button("Backspace"));

p3.add(

new Button("CE"));

p3.add(

new Button("C"));

// Add Number buttons to p4

p4.setForeground(

new Color(0, 0, 235));

p4.setFont(

new Font("Dialog", Font.PLAIN, 14));

p4.add(

new Button("7"));

p4.add(

new Button("8"));

p4.add(

new Button("9"));

p4.add(

new Button("/"));

p4.add(

new Button("sqrt"));

p4.add(

new Button("4"));

p4.add(

new Button("5"));

p4.add(

new Button("6"));

p4.add(

new Button("*"));

p4.add(

new Button("%"));

p4.add(

new Button("1"));

p4.add(

new Button("2"));

p4.add(

new Button("3"));

p4.add(

new Button("-"));

p4.add(

new Button("1/x"));

p4.add(

new Button("0"));

p4.add(

new Button("+/-"));

p4.add(

new Button("."));

p4.add(

new Button("+"));

p4.add(

new Button("="));

// Add and initialize output and total

// [Label and TextArea for output]

// output.setBackground(Color.WHITE);

// output.setForeground(Color.BLACK);

// output.setFont(new Font("Courier", Font.BOLD, 18));

total.setBackground(new Color(255, 255, 128));

total.setForeground(Color.black);

total.setFont(new Font("Courier", Font.BOLD, 14));

p5.add(

"Center", total);

p5.add(

"South", output);

// Hook up the panels

p2.add(

"North", p3);

p2.add(

"Center", p4);

// Add some spacing around outside

p1.add(

"North", p5);

p1.add(

"Center", p2);

p.setFont(

new Font("Helvetica", Font.PLAIN, 6));

p.add(

"North", new Label(" "));

p.add(

"East", new Label(" "));

p.add(

"West", new Label(" "));

p.add(

"South", new Label(" "));

p.add(

"Center", p1);

return p;

}

}
It's a calculator that works like an old adding machine. But it keeps throwing an error when trying to use operands. I'm supposed to write a try-catch to catch the error and deal with it. I can't find out where the error is, or how to catch it. Thanks for any help.
Life is a blast
(13 items)
 
  
CPUGraphicsRAMHard Drive
i5 @ 3.2 eVGA gtx260 8GB G.Skill 1666 Ripjaw DDR3 (2) 1.5TB Seagates 
Optical DriveOSMonitorKeyboard
ASUS DVD Burner Windows 7 Viewsonic VX2265wm (120Hz) Logitech G15 
PowerCaseMouseMouse Pad
ITZ Tagan 800 Watt Antec 900 Logitech MX518 Steelpad QcK+ 
  hide details  
Reply
Life is a blast
(13 items)
 
  
CPUGraphicsRAMHard Drive
i5 @ 3.2 eVGA gtx260 8GB G.Skill 1666 Ripjaw DDR3 (2) 1.5TB Seagates 
Optical DriveOSMonitorKeyboard
ASUS DVD Burner Windows 7 Viewsonic VX2265wm (120Hz) Logitech G15 
PowerCaseMouseMouse Pad
ITZ Tagan 800 Watt Antec 900 Logitech MX518 Steelpad QcK+ 
  hide details  
Reply
post #2 of 2
Exception on the '+' operand
Code:
Exception in thread "AWT-EventQueue-1" java.lang.StringIndexOutOfBoundsException: String index out of range: -17
at java.lang.String.substring(Unknown Source)
Code:
String padText(String s, int size)
{
String temp = " " + s;
return temp.substring(temp.length() - size);

}
If you debug here you'll see that you have temp.substring( 8 - 25 )

You can't call substring() with a negative value.


Here is an exception example.
Code:
try {
  // Some code
} catch (SomeException e) {
        // Print out the exception
        System.out.println("The error:" + e.getMessage() );
}

Edited by decompiled - 1/11/09 at 5:33pm
GAMR
(15 items)
 
  
CPUMotherboardGraphicsGraphics
6600K ASUS Z170-A ASUS 970 Strix ASUS 970 Strix 
RAMHard DriveHard DriveHard Drive
Crucial Ballistix Elite Samsung 850 EVO Intel 320 6400AAKS 
Hard DriveCoolingMonitorPower
6400AAKS Cooler Master Hyper 212 EVO ASUS VG24QE EVGA SuperNova 650 G2 
CaseMouseMouse Pad
Antec 1200 Razer Abyssus 3.5G QCK+ 
  hide details  
Reply
GAMR
(15 items)
 
  
CPUMotherboardGraphicsGraphics
6600K ASUS Z170-A ASUS 970 Strix ASUS 970 Strix 
RAMHard DriveHard DriveHard Drive
Crucial Ballistix Elite Samsung 850 EVO Intel 320 6400AAKS 
Hard DriveCoolingMonitorPower
6400AAKS Cooler Master Hyper 212 EVO ASUS VG24QE EVGA SuperNova 650 G2 
CaseMouseMouse Pad
Antec 1200 Razer Abyssus 3.5G QCK+ 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Application Programming