Skip to content

Commit 641df67

Browse files
authored
Update PowerOf.java for Negative Exponents
1 parent 31716ee commit 641df67

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

recursiveFunction/PowerOf.java

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Name: Mason Z.
22
// Program: PowerOf
3-
// Date: Apr 16, 2024
3+
// Date: Apr 24, 2024
44
// Description: powerOf function + superscript function
55

66
import java.util.Scanner;
@@ -14,23 +14,38 @@ public static void main(String[] args) {
1414
System.out.println("what is base value?");
1515
int b = s.nextInt();
1616
System.out.println("what is the exponent? (power of)? ");
17-
int a = s.nextInt();
17+
s.nextLine();
18+
String c = s.nextLine();
19+
20+
int a;
21+
22+
// if negative exponent
23+
if (c.contains("-")) {
24+
c = c.substring(1);
25+
a = Integer.valueOf(c);
26+
System.out.println(b + " to the power of " + "-" + a + " is " + "1/" + powerOf(b, a));
27+
}
1828

19-
// System.out.println(b + " to the power of " + a );
20-
System.out.println(b + superscript(a) + " is " + powerOf(b, a));
21-
}
29+
// if positive exponent or zero
30+
else {
31+
a = Integer.valueOf(c);
32+
System.out.println(b + " to the power of " + a + " is " + powerOf(b, a));
33+
}
2234

35+
36+
}
37+
2338

2439
// powerOf function
2540
// recursive function - learning example!
2641
// b = base, a = exponent
2742
private static int powerOf(int b, int a) {
28-
if (a == 0 )
43+
if (a == 0)
2944
return 1;
3045
else
3146
return b * powerOf(b, a-1);
3247
}
33-
48+
3449

3550
// superScript function
3651
public static String superscript(int n) {
@@ -42,9 +57,4 @@ public static String superscript(int n) {
4257
}
4358
return sb.toString();
4459
}
45-
46-
47-
48-
49-
5060
}

0 commit comments

Comments
 (0)