This code is supposed to get check whether a number is a palindrome.
Whenever I run the method check Palindrome its comes up with a java.lang.StringOutOfBoundsException.
Please help.
import java.util.*;
/**
* Lab 1 .
* #author Kevin Rasquinha
* #version 30 July 2016
*/
public class Lab1
{
private Scanner scan = new Scanner(System.in);
/**
* count the number of digits in a number
* #param num the number to analyse
* #return the number of digits it has
*/
public int numDigits (int num)
{
int nDigits = 0;
int digit;
while (num>0)
{
digit = num % 10; // take off the last digit
num = num /10; // reduce the number
nDigits = nDigits + 1; // increment count of digits
}
return nDigits;
}
/**
* Read a number from the keyboard, and report how many digits it has.
* Ensure the number is within a desired range.
*/
public void countDigits ()
{
int num=0;
while (num<1 || num > 1000)
{
System.out.print("What number (1 to 1000)? ");
num = scan.nextInt();
scan.nextLine();
System.out.println("Num = " + num);
if (num<1 || num > 1000)
System.out.println("1 to 1000, please");
}
System.out.println (num + " has " + numDigits(num) + " digits");
}
/**
* method used to if a number is the sum of the cube of its digits
* #param args (not used)
*/
public void sumCubesDigits ()
{
for (int initial = 1; initial < 1000; initial ++)
{
int num = initial;
int thirddig = num%10;
num = num / 10;
int secdig = num%10;
num = num / 10;
int firstdig = num%10;
int sum = (thirddig*thirddig*thirddig) + (secdig*secdig*secdig) + (firstdig*firstdig*firstdig);
if (sum == initial)
{
System.out.println ("The number " + initial + " is equal to the sum of the cube of its digits.");
}
}
}
/**
* Recieves an int and writes the same int backwards
* #param args (not used)
*/
public int backwards(int num)
{
int rev = 0;
int value = num;
while (value != 0)
{
rev = rev*10;
rev = rev + value%10;
value /= 10;
}
return rev;
}
/**
* Receives digit from method backwards
* Asses whether backwards = the original number
* #param args (not used)
*/
public boolean palindrome (int num, int digit)
{
boolean a = false;
int normal = num;
int reversed = digit;
if( reversed == digit)
{
a = true;
}
return a;
}
/**
* Recieves int from user - num
* Sends num to backwards
* Sends num to palindrome
* Recieves boolean from palindrome
* Outputs message to user
*/
public void checkPalindrome ()
{
System.out.println ("Enter number to be see if it is a palindrome");
int num = scan.nextInt();
int digit = backwards(num);
boolean check = palindrome (num, digit);
if (check = true)
{
System.out.println("Your number is a palindrome");
}
}
/**
* Present a menu to the user, and obtain their selection. If they
* type an erroneous value, report it and try again. Either upper
* case or lower case input is accepted.
* #return an upper case character showing the user's choice
*/
public char menuChoice ()
{
System.out.println("");
System.out.println("What do you want to do?");
System.out.println("(c) Count the digits in a number");
System.out.println("(g) Find out the numbers where the the sum of the cube of its digits is equal to it");
System.out.println("(p) Find out if a number is a palindrome");
System.out.println("(q) Quit");
System.out.print("Your choice? ");
char answer = ' ';
boolean ok = false;
while (! ok)
{
answer = scan.nextLine().trim().toUpperCase().charAt(0);
ok = (answer == 'C' || answer == 'Q' || answer == 'G' || answer == 'P');
if (! ok)
{
System.out.println("Please type one of c,C,q,Q,g,G,p,P");
System.out.print("Your choice? ");
}
}
return answer;
}
/**
* test driver for the program
*/
public void test()
{
char answer = ' ';
while (answer != 'Q')
{
answer = menuChoice();
switch (answer)
{
case 'C': countDigits(); break;
case 'G': sumCubesDigits(); break;
case 'P': checkPalindrome();break;
case 'Q': break;
}
}
}
/**
* main program: create a test driver and let it loose
* #param args (not used)
*/
public static void main (String [] args)
{
Lab1 l1 = new Lab1();
l1.test();
}
}
A StringIndexOutOfBoundsException is mostly thrown when you use charAt to select a character from a string that isn't there.
I guess your issue is here:
answer = scan.nextLine().trim().toUpperCase().charAt(0);
because that is the only charAt in your code.
What would that line do if the user entered nothing? Throw an Exception of course!
You should change if (check = true) to if (check == true) and answer = scan.nextLine().trim().toUpperCase().charAt(0); to answer = scan.nextLine();
if(answer != null)
answer = answer.trim().toUpperCase().charAt(0);
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
What's the simplest way to print a Java array?
(37 answers)
Closed 10 months ago.
I have a method called processClaims() which takes input from the user "by asking how many files need to be claimed". The method is shown below.
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
The problem is with the array or the for loop I belive. The output is shown below which isn't correct
[LInsuranceSystem$EarthquakeInsurance;#548c4f57
If that is wrong here is the whole code, I am having trouble debugging this.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
public class Slack
{
public static void main(String[] args) throws FileNotFoundException {
InsuranceSystem insuranceSystem = new InsuranceSystem();
insuranceSystem.start();
}
}
class InsuranceSystem {
Scanner input = new Scanner(System.in);
Calendar dateTime = Calendar.getInstance();
ArrayList<String> claimsReport = new ArrayList<>();
EarthquakeInsurance[] claims;
String fileName = " ";
char cont = ' ', correct = ' ';
public InsuranceSystem() {
}
public void start() throws FileNotFoundException {
System.out.println("MUTUALLY ACCIDENTAL INC.");
System.out.println("Do you want an analysis of earthquake coverage for your property? Enter 'Y' or 'N': ");
cont = input.next().charAt(0); //reads user input from input and applies to it var cont
input.nextLine(); //clears buffer
if (cont == 'y' || cont == 'Y') {
processClaims();
writeClaimsRecords();
checkInputFile();
}
printThankYou();
}
public void processClaims() {
int size = 0, j = 0, k = 0;
String suffix = " ", aClaim = " ";
System.out.println("How many claims will be filed?");
size = input.nextInt();
while (size <= 0) {
System.out.println("Invalid integer! Re-enter the number of claims to be filed: ");
size = input.nextInt();
}
EarthquakeInsurance[] claims = new EarthquakeInsurance[size];
for (int i = 0; i >= 0; i++) {
j = (i + 1) % 10;
k = (i + 1) % 100;
suffix = j == 1 && k != 11 ? "st" :
j == 2 && k != 12 ? "nd" :
j == 3 && k != 13 ? "rd" : "th";
claims[i] = new EarthquakeInsurance();
if (i > 0) {
System.out.println("Is this " + i + suffix + " claim for the same property owner? 'Y' or 'N': ");
cont = input.next().charAt(0);
if (cont == 'n' || cont == 'N') {
claims[i].setInsured();
}
else{
claims[i].setInsured(claims[i].getInsured());
}
}
else
{
claims[i].setInsured();
claims[i].setHomeInsVal();
claims[i].setRichter();
}
input.nextLine();
aClaim = String.format("%n%nPAYOUT FOR EARTHQUAKE DAMAGE"
+ "%n%nHomeowner: %S"
+ "%n%nDate: %tD"
+ "%nTime: %tr%n"
+ "%n%-52s %4s $%,20.2f"
+ "%nDeductible %47s %,20.2f"
+ "%n%46s TOTAL %4s $%,20.2f%n",
claims[i].getInsured(), dateTime, dateTime, claims[i].getMessage(), " ",
claims[i].getPayout(), " ",
claims[i].getDeductible(), " ",
" ", claims[i].getPayout() +
claims[i].getDeductible());
aClaim += claimsReport;
for ( EarthquakeInsurance eachClaim : claims);
System.out.println(claims);
}
}
public void writeClaimsRecords() throws FileNotFoundException
{
String record = " ";
Scanner input = new Scanner(System.in);
System.out.println("Enter the file name for the claims' records (WARNING: This will erase a pre-existing file!): ");
fileName = input.nextLine();
PrintWriter outputFile = new PrintWriter(fileName);
for(int i = 0; i < claims.length; i++){
record = String.format("%s, %f, %f%n", claims[i].insured, claims[i].homeInsVal, claims[i].richter);
}
outputFile.printf(record);
outputFile.close();
System.out.println("Data written to the" + fileName + " file.");
}
public void checkInputFile() throws FileNotFoundException {
String fileRecord = " ";
File file = new File("Claims.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()) {
fileRecord = inputFile.nextLine();
System.out.println(fileRecord);
System.out.println("");
inputFile.close();
}
}
public void printThankYou() {
System.out.println("Thank you for using the Earthquake Coverage Analyzer.");
}
class EarthquakeInsurance {
//STUDENTS INSERT LINE COMMENTS DESCRIPTIVE OF THE PURPOSE OF EACH VARIABLE.
private String insured;
private String coverage;
private String message;
private double homeInsVal;
private double richter;
private double payout;
private double deductible;
private Scanner input = new Scanner(System.in);
private boolean repeat;
private char correct;
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance() {
}//END Default Constructor
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public EarthquakeInsurance(String insured, double homeInsVal, double richter) {
setInsured(insured);
setHomeInsVal(homeInsVal);
setRichter(richter);
}//END EarthquakeInsurance(String, double, double)
/**
* STUDENTS CODE copy() AND PROVIDE METHOD BOX COMMENTS.
*/
public String copy() {
String insuranceObj = " ";
return insuranceObj;
}
/**
* STUDENTS CODE equals AND PROVIDE METHOD BOX COMMENTS.
*/
public boolean equals(String aClaim) {
boolean isEqual = false;
if (isEqual = false) {
isEqual = true;
}
return isEqual;
}
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setInsured(String insured) {
this.insured = insured;
}//END setInsured(String): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setHomeInsVal(double homeInsVal) {
this.homeInsVal = homeInsVal;
}//END setHomeInsVal(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public final void setRichter(double richter) {
this.richter = richter;
}//END setRichter(double): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setInsured() {
String insuredCopy = null, first = null, last = null;
int indexOfSpace = 0;
do {
System.out.printf("%nMUTUALLY ACCIDENTAL, INC."
+ "%nEarthquake Coverage Analyzer"
+ "%n%nPlease enter your name: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
while (!isAlpha(insuredCopy)) {
System.out.printf("%nInvalid name! Please re-enter: ");
insured = input.nextLine();
insuredCopy = new String(insured).replace(" ", "");
}//while insured's name is NOT alphabetic
System.out.printf("%nYour Name: %s"
+ "%n%nIs this name correct? \'Y\' or \'N\': ",
insured);
correct = input.nextLine().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
} while (repeat); //do-while insured name is not correct
indexOfSpace = insured.indexOf(" "); //Locate where the space is in insured.
if (indexOfSpace > 0) {
first = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, indexOfSpace).toLowerCase();
last = Character.toUpperCase(insured.charAt(indexOfSpace + 1))
+ insured.substring(indexOfSpace + 2, insured.length()).toLowerCase();
insured = first + " " + last;
}//if there is more than one name, capitalize the first letter in each
else {
insured = Character.toUpperCase(insured.charAt(0))
+ insured.substring(1, insured.length()).toLowerCase();
}//else capitalize first letter of a single name
}//END setInsured(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setHomeInsVal() {
do {
do {
System.out.printf("%nPlease enter the insured value of your home: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when homeInsVal is invalid
homeInsVal = input.nextDouble();
if (homeInsVal < 0) {
System.out.printf("%nThe insured value of your home cannot be less than or equal to 0.%n");
repeat = true;
}//END if homeInsVal less than zero then prompt again
else {
System.out.printf("%nHome\'s Insured Value: $%,.0f"
+ "%n%nIs this insured value correct? \'Y\' or \'N\': ",
homeInsVal);
correct = input.next().toLowerCase().charAt(0);
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of insured value
} while (repeat); //END do-while repeats when homeInsVal is not correct
}//END setHomeInsVal(): final void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void setRichter() {
do {
do {
System.out.printf("%nRichter Scale Damage Assessment"
+ "%n 9.0+ Total destruction."
+ "%n 8.0 Most structures fell."
+ "%n 7.0 Many buildings destroyed."
+ "%n 6.0 Many buildings considerably damaged, some collapsed."
+ "%n 4.5 Damage to poorly constructed buildings."
+ "%n 3.5 Felt by many people, no destruction."
+ "%n 0 Generally not felt by people."
+ "%n%nPlease enter the Richter scale value for the earthquake: ");
repeat = !input.hasNextDouble();
validateNumber();
} while (repeat); //END do-while repeats when richter is invalid
richter = input.nextDouble();
if (richter < 0) {
System.out.printf("%nInvalid! Richter cannot be negative. Please re-enter.%n");
repeat = true;
}//END if richter less than zero then prompt again
else {
System.out.printf("%nRichter Scale: %.2f"
+ "%n%nIs this richter value correct? \'Y\' or \'N\': ",
richter);
correct = input.next().toLowerCase().charAt(0);
input.nextLine();
repeat = correct == 'y' ? false : true;
}//END else validate the correctness of richter
} while (repeat); //END do-while repeats when homeInsVal is not correct
testRichter();
}//END setRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
private void testRichter() {
if (richter >= 9.0) {
payout = homeInsVal * .90;
deductible = homeInsVal * .10;
message = "Total destruction.";
}//END if richter >= 9.0 else richter < 9.0
else if (richter >= 8.0) {
payout = homeInsVal * .80;
deductible = homeInsVal * .20;
message = "Most structures fell.";
}//END if richter >= 8.0 else richter < 8.0
else if (richter >= 7.0) {
payout = homeInsVal * .70;
deductible = homeInsVal * .30;
message = "Many buildings destroyed.";
}//END if richter >= 7.0 else richter < 7.0
else if (richter >= 6.0) {
payout = homeInsVal * .60;
deductible = homeInsVal * .40;
message = "Many buildings considerably damaged, some collapsed.";
}//END if richter >= 6.0 else richter < 6.0
else if (richter >= 4.5) {
payout = homeInsVal * .50;
deductible = homeInsVal * .50;
message = "Damage to poorly constructed buildings.";
}//END if richter >= 4.5 else richter < 4.5
else if (richter >= 3.5) {
payout = 0;
deductible = 0;
message = "Felt by many people, no destruction.";
}//END if richter >= 3.5 else richter < 3.5
else if (richter >= 0) {
payout = 0;
deductible = 0;
message = "Generally not felt by people.";
}//END if richter >= 0 else richter < 0
}//END testRichter(): void
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getInsured() {
return insured;
}//END getInsured(): int
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getHomeInsVal() {
return homeInsVal;
}//END getHomeInsVal(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getRichter() {
return richter;
}//END getRichter(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getPayout() {
return payout;
}//END getPayout(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public double getDeductible() {
return deductible;
}//END getDeductible(): double
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public String getMessage() {
return message;
}//END getMessage(): String
/**
* STUDENTS ARE TO DESCRIBE WHAT'S GOING ON WITH THE CODE IN METHOD BOXES.
*/
public void validateNumber() {
if (repeat) //AS LONG AS THE INPUT IS "NOT" AN INTEGER OR DOUBLE
{
input.next(); //CONSUME NON-NUMERIC VALUE.
System.out.printf("%nWarning: You entered an invalid integer or "
+ "floating-point value.%n"); //RE-PROMPT
}//END if repeat when a number is an invalid type
}//END validateNumber(boolean): void
/**
* chars() returns the integer values of the characters in word.
* <p>
* allMatch determines whether the integer values for each character
* matches the predicate (criterion) that each character is a letter.
* <p>
* The :: is a method reference operator for calling isLetter from
* the Character class.
*
* #param word is the incoming String value to test.
* #return is true when the word is not empty and is alphabetic
* or false when it isn't.
*/
public final boolean isAlpha(String word) {
/* Test to see if the word is not empty AND if each letter
* in a word is an alphabetic character.
*/
return word != null && word.chars().allMatch(Character::isLetter);
}//END isAlpha(String): final boolean
}//END CLASS EarthquakeInsurance
}
Mistake 1)
for ( EarthquakeInsurance eachClaim : claims);
remove semi
Mistake 2)
System.out.println(claims);
Yes you are print the whole list
See also How do I print my Java object without getting "SomeType#2f92e0f4"?
I need help with my coding. I am practicing again with my java programming and today I am creating a calculator that has the same function as the real calculator but again I run into errors and unable to figure out again.
Okay, the way I wanted my calculator to works is instead of getting line by line input from the user like this:-
In code output
Enter Number: 1
Enter Operator (+,-, /, *, ^ (Power) or s (Square): +
Enter Number: 2
Ans: 3
I wanted it to calculate when the user press enter like this:-
The Output that I want
enter number: 1+2*4
Ans: 12
So they can add as many long numbers as they want before they hit enter calculate. The users are supposed to be able to reset the number to when using the calculator while in the loop of the calculation.
at the beginning of the code, it will ask the user for an input to continue or exit the calculator. Then if continue it will run the calculation. The calculator will be looping until the users press E to exit the calculator and if exit it will exit the code.
This is where I have errors. First, I can't figure out how to break from the loop inside the looping calculator and second at the beginning of the code when the user press E it was supposed to exit the calculator but it didn't. The third error is when the user using the square to calculate I want it to get straight to show the answer instead of asking another number.
and I want to simplify the code in public static void main(String[] args)for the calculation part. Is it possible to put the switch case in method and call it inside the main? or do you have a suggestion on how to simplify the calculation part?
Please help me:(
public class TestingCalculator {
public static void main(String[] args){
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
String a = ans.next();
activateCalc = a.charAt(0);
while (activateCalc != 'E' || activateCalc != 'e') {
Scanner input = new Scanner(System.in);
System.out.print("Enter number: ");
String n =input.next();
numA = Double.parseDouble(n);
while (calculator = true) {
//User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); //User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA,numB);
break;
case '-':
answer =subtract(numA,numB);
break;
case '*':
answer = multiply(numA,numB);
break;
case '/':
answer = divide(numA,numB);
break;
case '^':
answer = power(numA, numB);
break;
case 's':
case 'S':
answer = Math.pow(numA, 2);
break;
}
//The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator: ");
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
}
}
ans.close();
}
//Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
}
Instead of trying to identify the problems with your application, I decided to focus on producing a program that works the way you want (with the input you specified). The code was a little big, but I tried to leave it well commented for you to understand what I did. I know that some things may still be a little confusing, so I will simulate running the program to try to make it clearer how it works.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestingCalculator
{
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Evaluates a mathematical expression.
*
* #param line Mathematical expression. This line cannot have blank
* spaces
* #return Result of this mathematical expression
*/
public static String calc(String line)
{
while (!hasOnlyNumbers(line)) {
// Checks if line has parentheses
if (line.contains("(")) {
// Get index of the most nested parentheses
int parentheses_begin = line.lastIndexOf("(");
int parentheses_end = line.substring(parentheses_begin).indexOf(")");
String ans = calc(line.substring(parentheses_begin+1, parentheses_end));
// Replaces content of parentheses with the result obtained
if (line.length()-1 >= parentheses_end+1)
line = line.substring(0,parentheses_begin)+ans+line.substring(parentheses_end+1);
else
line = line.substring(0,parentheses_begin)+ans;
}
// Checks if line has potentiation operator
else if (line.contains("^")) {
int opIndex = line.indexOf("^");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = power(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has square operator
else if (line.contains("s")) {
int opIndex = line.indexOf("s");
String n1 = extractFirstNumber(line, opIndex);
double ans = square(Double.valueOf(n1));
line = calc(parseLine(line, n1, opIndex, ans));
}
// Checks if line has multiplication operator
else if (line.contains("*")) {
int opIndex = line.indexOf("*");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = multiply(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has division operator
else if (line.contains("/")) {
int opIndex = line.indexOf("/");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = divide(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has sum operator
else if (line.contains("+")) {
int opIndex = line.indexOf("+");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = add(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has subtraction operator
else if (line.contains("-")) {
int opIndex = line.indexOf("-");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = subtract(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
}
// Returns line only when it has only numbers
return line;
}
/**
* Checks if a line contains only numbers.
*
* #param line Line to be analyzed
* #return If a line contains only numbers
*/
private static boolean hasOnlyNumbers(String line)
{
return line.matches("^[0-9.]+$");
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param n2 Number to the right of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, String n2, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
int lenSecondNumber = n2.length();
if (line.length()-1 >= opIndex+lenSecondNumber+1)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+lenSecondNumber+1);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
if (line.length()-1 >= opIndex+2)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+2);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Extracts the first number from an operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 2 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the left of the operator
*/
private static String extractFirstNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex-1;
while (i>=0 && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i--;
}
// Reverses the result, since the number is taken from the end to the
// beginning
num = num.reverse();
return num.toString();
}
/**
* Extracts the second number from a math operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 3 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the right of the operator
*/
private static String extractSecondNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex+1;
while (i<line.length() && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i++;
}
return num.toString();
}
// Method for the operators.
private static double add(double numA, double numB)
{
double answer = numA + numB;
return answer;
}
private static double subtract(double numA, double numB)
{
double answer = numA - numB;
return answer;
}
private static double multiply(double numA, double numB)
{
double answer = numA * numB;
return answer;
}
private static double divide(double numA, double numB)
{
double answer = numA / numB;
return answer;
}
private static double power(double numA, double numB)
{
int answer = (int) Math.pow(numA, numB);
return answer;
}
private static double square(double num)
{
int answer = (int) Math.pow(num, 2);
return answer;
}
//-------------------------------------------------------------------------
// Main
//-------------------------------------------------------------------------
public static void main(String[] args) throws IOException
{
char option;
String inputLine = "";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
option = input.readLine().charAt(0);
while (option != 'E' && option != 'e') {
// Gets user input
System.out.print("Enter mathematical expression: ");
inputLine += input.readLine();
// Processes input
inputLine = inputLine.replaceAll(" ", "");
inputLine = inputLine.replaceAll("S", "s");
// Evaluates input
System.out.println("Evaluating...");
String ans = TestingCalculator.calc(inputLine);
// Displays answer
System.out.println("Ans: "+ans);
// Checks if the user wants to continue running the program
System.out.print("Press E to Exit the calculator: ");
inputLine = input.readLine();
if (inputLine.length() > 0)
option = inputLine.charAt(0);
}
input.close();
}
}
Output
Enter mathematical expression: (1+2*4)/3
Evaluating...
Ans: 3.0
Output 2
Enter mathematical expression: 1+2*9/3
Evaluating...
Ans: 7.0
Desk checking
Input: (1+2*4)/3
calc( (1+2*4)/3 )
not hasOnlyNumbers( (1+2*4)/3) ) ? true
( (1+2*4)/3) ) contains '(' ? true
int parentheses_begin = 0
int parentheses_end = 6
String ans = calc( 1+2*4 )
calc( 1+2*4 )
not hasOnlyNumbers( 1+2*4 ) ? true
( 1+2*4 ) contains '(' ? false
( 1+2*4 ) contains '^' ? false
( 1+2*4 ) contains 's' ? false
( 1+2*4 ) contains '*' ? true
int opIndex = 3
int n1 = 2
int n2 = 4
String ans = n1 * n2 = 2 * 4 = 8
line = calc( 1+8 )
calc( 1+8 )
not hasOnlyNumbers( 1+8 ) ? true
( 1+8 ) contains '(' ? false
( 1+8 ) contains '^' ? false
( 1+8 ) contains 's' ? false
( 1+8 ) contains '*' ? false
( 1+8 ) contains '/' ? false
( 1+8 ) contains '+' ? true
int opIndex = 1
int n1 = 1
int n2 = 8
String ans = n1 + n2 = 1 + 8 = 9
line = calc( 9 )
calc( 9 )
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
ans = 9
(9-1 >= 6+1) ? true
line = 9/3
not hasOnlyNumbers( 9/3 ) ? true
( 9/3 ) contains '(' ? false
( 9/3 ) contains '^' ? false
( 9/3 ) contains 's' ? false
( 9/3 ) contains '*' ? false
( 9/3 ) contains '/' ? true
int opIndex = 1
String n1 = 9
String n2 = 3
double ans = 9 / 3 = 3
line = calc( 3 )
calc( 3 )
not hasOnlyNumbers( 3 ) ? false
return 3
line = 3
not hasOnlyNumbers( 3 ) ? false
return 3
Some observations
No checks are made to see if the user-provided input is valid
It is important to maintain the order of operations that are verified in the calc method, in order to maintain precedence between operators (exponentiation / radication must be done first, followed by multiplication / division and finally addition / subtraction operations)
I had problems with the Scanner class, so I used BufferedReader to read the input
Square operation must be done as follows: <num>s or <num>S
Hope this helps. If you don't understand something, tell me I can explain it to you.
try below code and one suggestion try to handle the negative scenarios as well.
public static void main(String[] args) {
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
Scanner input = new Scanner(System.in);
activateCalc = input.next().charAt(0);
while (true) {
if (activateCalc != 'E' && activateCalc != 'e') {
System.out.print("Enter number: ");
String n = input.next();
numA = Double.parseDouble(n);
// User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); // User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA, numB);
break;
case '-':
answer = subtract(numA, numB);
break;
case '*':
answer = multiply(numA, numB);
break;
case '/':
answer = divide(numA, numB);
break;
case '^':
answer = power(numA, numB);
break;
case 'S':
case 's':
answer = Math.pow(numA, 2);
break;
default:
answer = 0;
}
// The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator or Y to continue : ");
activateCalc = input.next().charAt(0);
if(activateCalc != 'E' && activateCalc != 'e')continue;
}
System.out.println("Thank you for using the calculator. By :) ");
ans.close();
break;
}
}
// Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
This question requires debugging details so here we go:
Your code does not seem to compile because of the error:
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
where you had to use comparison == operator instead of assignment =.
Similar issue is in your inner loop while (calculator = true) - and there's a warning that this value is never used - but this does not affect much.
You cannot exit the loop because you never check the input for exit, it should be:
System.out.println("Press E to Exit the calculator: ");
activateCalc = input.next().charAt(0);
But even if you updated activateCalc, you'd get into endless loop anyway because of the error in this condition while (activateCalc != 'E' || activateCalc != 'e') -- even if user presses 'e', or 'E' this condition is always true.
It goes like this: The purpose of the Project4Appclass is to create a math game for children to play thatwill strengthen their addition and subtraction skills. In order for the game to allow the student to get enough practice, the game will ask the student 10 questions. If the student gets the first 10 questions correct, the game should end. Otherwise, the game should continue until one of two things happen: 1) the student’s percent of correct answers reaches at least 85%, or 2) the student hascompleted 20 questions. When the game ends, the student should be told the number of addition questions he/she got correct and incorrect as well as the number of subtraction questions he/she got correct and incorrect. It should also give a score which isthe percent of questions he/she got correct. (and use no "Break")
package proj3;
import java.util.Random;
public class Question {
private int operand1;
private int operand2;
private char operator;
/**
* <p> Name: main method </p>
*
*/
public Question()
{
Random rand = new Random();
boolean random = rand.nextBoolean();
if(rand.nextBoolean())
{
operator = '+';
operand1 = rand.nextInt(13);
operand2 = rand.nextInt(13);
}
else
{
operator = '-';
operand1 = rand.nextInt(13 - 6) + 6;
operand2 = rand.nextInt((operand1 - 0) + 1) + 0;
}
}
/**
* getOperand1 method - returns what's stored in the instance variable value
* #return the state of the instance variable value
*/
public int getOperand1()
{
return operand1;
}
/**
* getOperand2 method - returns what's stored in the instance variable value
* #return the state of the instance variable value
*/
public int getOperand2()
{
return operand2;
}
/**
* getOperator method - returns what's stored in the instance variable value
* #return the state of the instance variable value
*/
public char getOperator()
{
return operator;
}
/**
* toString method - this method returns the state of the Question object
* #return a reference to a String object that contains
* the operands and the operator
*/
public String toString()
{
String question;
question = operand1 + " " + operator + " " + operand2 + " " + "=";
return question;
}
/**
* determineAnswer method - this method returns the state of the card object
* #return a reference to a Question object that contains the answer to
* a random question.
*/
public int determineAnswer()
{
if(operator == '+')
return operand1 + operand2;
else
return operand1 - operand2;
}
}
This is what Project4App currently looks like(stuck on)
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int percentage = 0;
int questions = 0;
while( questions > 10 && questions < 20 && percentage >= 85.0)
{
Question q = new Question();
System.out.println("What is the result?");
System.out.println(q);
int answer = scan.nextInt();
if(answer == q.determineAnswer())
System.out.println("Congratulations, you got it correct!");
else
System.out.println("The correct answer for " + q + " is " + q.determineAnswer());
}
/**for(int i =0; i <= 20; i++)
{
Question q = new Question();
System.out.println("What is the result?");
System.out.println(q);
int answer = scan.nextInt();
if(answer == q.determineAnswer())
{
System.out.println("Congratulations, you got it correct!");
}
else
System.out.println("The correct answer for " + q + " is " + q.determineAnswer());
}
**/
}
}
Any advice will be appreciated on how to continue.
I did not test
boolean isOver = false;
while( !isOver ){
questions++;
Question q = new Question();
System.out.println("What is the result?");
System.out.println(q);
int answer = scan.nextInt();
if(answer == q.determineAnswer())
System.out.println("Congratulations, you got it correct!");
else
System.out.println("The correct answer for " + q + " is "+ q.determineAnswer());
if( (questions > 10 && percentage >= 85.0) || questions == 20){
isOver = true;
}
}
My factorial method is working correctly although I would like to change the output from just outputting the number and the factorial result. For example I would like if the user enters 6 for the output to say 6 * 5 * 4 * 3 * 2 * 1 = 720, instead of factorial of 6 is: 720.
int count, number;//declared count as loop and number as user input
int fact = 1;//declared as 1
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
System.out.println(number);//prints number the user input
if (number > 0) {
for (i = 1; i <= number; i++) {//loop
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
}
create a string and store the numbers.
try something like this.
int count, number;//declared count as loop and number as user input
String s; //create a string
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
int fact = number;//store the number retrieved
System.out.println(number);//prints number the user input
if (number > 0) {
s=String.valueOf(number);
for (int i = 1; i < number; i++) {//loop
fact = fact * i;
s = s +" * "+String.valueOf(number-i);
}
System.out.println(s+ " = " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
Check out this recursive approach: (check negative numbers yourself :D)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(getFactorialString(num, " = " + getFactorial(num)));
}
public static String getFactorialString(int num, String result) {
if (num == 0) return "0 => 1";
if (num == 1) {
result = "" + num + "" + result;
} else {
result = getFactorialString(num - 1, result);
result = "" + num + " x " + result;
}
return result;
}
public static int getFactorial(int num) {
if (num == 0) return 1;
return num * getFactorial(num - 1);
}
I'm trying to make a ATM that can make deposit, withdrawal and show balance. But I have a problem with the program's balance it only shows the balance for the ten most recent transactions rather than all the transactions made.
I'm not allowed to use global variables,other methods and constants.
Here is how it should work
Earlier transactions:
=====================
1
2
3
4
5
6
7
8
9
10
=======================
Balance: 55 KR
Earlier transactions:
=====================
2
3
4
5
6
7
8
9
10
11
=======================
Balance: 66 KR
Code
import java.util.Scanner;
public class Bankomat
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// Declarer variables
int[] trans = new int[10];
int amount = 0;
int balance = 0;
int sum = 0;
int theChoice = 1;
while(theChoice != 4)
{
theChoice= menu();
switch(theChoice)
{
case 1:
System.out.println("\nDu valde \"deposit\"");
System.out.print("\nState the value you want to take in: ");
sum = in.nextInt();
if(sum == 0)
{
System.out.print("\nYou have given are wrong value.\n");
}
else
{
amount = (int) + sum;
makeTransactions(trans,amount);
}
break;
case 2:
System.out.println("\nDu valde \"withdrawal\"");
System.out.print("\nState the value you want to take in: ");
sum = in.nextInt();
if(sum == 0)
{
System.out.print("\nDu har angett ett felaktigt belopp.\n");
}
else
{
amount = (int) - sum;
makeTransactions(trans,amount);
}
break;
case 3:
System.out.println("\nDu valde \"Balance\"");
showTransactions(trans,balance);
break;
case 4:
System.out.println("\nDu valde \"Quit\"");
break;
}
}
}
/**
* MENU
* #return val skickar tillbaka input värdet
*/
public static int menu()
{
Scanner in = new Scanner(System.in);
int choice = 0;
// Den här delen kommer att skriva ut menu
System.out.println("1. deposit");
System.out.println("2. withdrawal");
System.out.println("3. Balance");
System.out.println("4. Quit");
System.out.print("Your choice: ");
choice = in.nextInt();
return choice;
}
/**
* This method will sum up all the ten latest transaction and show the balance
* #param trans array that saves the latest transactions
* #param balance Int that sums up all the values
*/
public static void showTransactions(int[] trans, int balance )
{
System.out.println();
System.out.println("Tidigare transaktioner: ");
System.out.println("-------------------------------------------\n");
for(int i = 0; i < trans.length; i++)
{
if(trans[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(trans[i] + "\n");
balance = balance + trans[i];
}
}
System.out.println("-------------------------------------------\n");
System.out.println("Saldo: " + balance + "KR" + "\n" );
}
/**
* This method saves the latest transaction
* #param trans array that saves the latest transactions
* #param amount int that saves the latest transaction
*/
public static void makeTransactions(int[] trans, int amount)
{
int position = findNr(trans);
if(position == -1)
{
moveTrans(trans);
trans[trans.length - 1] = amount;
}
else
{
trans[position] = amount;
}
}
/**
* This metod will look for a empty position
* #param trans array that saves the latest transactions
* #return position
*/
private static int findNr(int[] trans)
{
int position = -1;
for(int i = 0; i < trans.length; i++)
{
if (trans[i] == 0)
{
position = i;
break;
}
}
return position;
}
/**
* This method will move the transaction
* #param trans array that saves the latest transactions
*/
private static void moveTrans(int[] trans)
{
for(int i = 0; i < (trans.length - 1); i++)
{
trans[i] = trans[i + 1];
}
}
}
[EDITED] Complete solution:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
// Declarer variables
int[] trans = new int[10];
int amount = 0;
int balance = 0;
int sum = 0;
int theChoice = 1;
while(theChoice != 4)
{
theChoice= menu();
switch(theChoice)
{
case 1:
System.out.println("\nDu valde \"deposit\"");
System.out.print("\nState the value you want to take in: ");
sum = in.nextInt();
if(sum == 0)
{
System.out.print("\nYou have given are wrong value.\n");
}
else
{
amount = (int) + sum;
balance += amount;
makeTransactions(trans,amount);
}
break;
case 2:
System.out.println("\nDu valde \"withdrawal\"");
System.out.print("\nState the value you want to take in: ");
sum = in.nextInt();
if(sum == 0)
{
System.out.print("\nDu har angett ett felaktigt belopp.\n");
}
else
{
amount = (int) - sum;
balance += amount;
makeTransactions(trans,amount);
}
break;
case 3:
System.out.println("\nDu valde \"Balance\"");
showTransactions(trans,balance);
break;
case 4:
System.out.println("\nDu valde \"Quit\"");
break;
}
}
}
/**
* MENU
* #return val skickar tillbaka input värdet
*/
public static int menu()
{
Scanner in = new Scanner(System.in);
int choice = 0;
// Den här delen kommer att skriva ut menu
System.out.println("1. deposit");
System.out.println("2. withdrawal");
System.out.println("3. Balance");
System.out.println("4. Quit");
System.out.print("Your choice: ");
choice = in.nextInt();
return choice;
}
/**
* This method will sum up all the ten latest transaction and show the balance
* #param trans array that saves the latest transactions
* #param balance Int that sums up all the values
*/
public static void showTransactions(int[] trans, int balance )
{
System.out.println();
System.out.println("Tidigare transaktioner: ");
System.out.println("-------------------------------------------\n");
for(int i = 0; i < trans.length; i++)
{
if(trans[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(trans[i] + "\n");
}
}
System.out.println("-------------------------------------------\n");
System.out.println("Saldo: " + balance + "KR" + "\n" );
}
/**
* This method saves the latest transaction
* #param trans array that saves the latest transactions
* #param amount int that saves the latest transaction
*/
public static void makeTransactions(int[] trans, int amount)
{
int position = findNr(trans);
if(position == -1)
{
moveTrans(trans);
trans[trans.length - 1] = amount;
}
else
{
trans[position] = amount;
}
}
/**
* This metod will look for a empty position
* #param trans array that saves the latest transactions
* #return position
*/
private static int findNr(int[] trans)
{
int position = -1;
for(int i = 0; i < trans.length; i++)
{
if (trans[i] == 0)
{
position = i;
break;
}
}
return position;
}
/**
* This method will move the transaction
* #param trans array that saves the latest transactions
*/
private static void moveTrans(int[] trans)
{
for(int i = 0; i < (trans.length - 1); i++)
{
trans[i] = trans[i + 1];
}
}
The problem is because of how you initialized your int[] trans. You're only storing the first 10 transactions. You should use ArrayList instead, because it's dynamic.
ArrayList<Integer> trans = new ArrayList<Integer>, then to add new transactions to your array
It only shows the last 10 because you initialze your array to 10 indexes
int[] trans = new int[10];
Either make it bigger or use something different.
A great class to use in this case would be a vector. You don't need to initialize a size because it resizes itself dynamically.
Now, if you use a vector, but only want to print the last ten transactions, then surround your print statements in conditionals
if(i > trans.length - 10)
{
System.out.print(trans[i] + "\n");
}
The reson for this is in your showTransactions() not only are you printing the transactions, you are also adding them, computing your balance. We want to compute your balance with all your transactions (thus we need to change your array to a vector or other class with dynamic resizing) while also only printing what you need (thus the if statement)