How do you create a calculator in bukkit? - java

I am just learning bukkit and i want to make a calculator like i do with all new programming languages (i know basic Java) but i cant seem to find a way to add the args that someone inputs and i couldn't find a tutorial on this for bukkit. Also can anyone help me parse the numbers so it gives a different error message if you try to add something thats not a double. I tried adding a switch statement to do this but that didn't work.
This is what i got so far...
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
#SuppressWarnings("unused")
Player player = (Player) sender;
if(commandLabel.equalsIgnoreCase("calc")){
if(args.length == 1){
String n1 = args[0];
if (true){
if (args[0].equalsIgnoreCase("+") || args[0].equalsIgnoreCase("-")){
String n2 = args[1];
if (args[0].equalsIgnoreCase("+")){
double answer = Double.parseDouble(n1) + Double.parseDouble(n2);
sender.sendMessage("The answer is " + answer);
}
}else{
sender.sendMessage("Please use + or -");
}
}
}else{
sender.sendMessage(ChatColor.RED + "Incorrect Syntax");
}
}
return false;
}
}

You could do something like this:
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
if(cmd.getName().equalsIgnoreCase("add")){//if the comand is /add
if(args.length == 2){// if there are two arguments
try{
long n1 = Long.parseLong(args[0]);//get the first number
long n2 = Long.parseLong(args[1]);//get the second number
long result = n1 + n2;//add the two numbers together
sender.sendMessage(n1 + " + " + n2 + " equals " + result);//tell the sender the result
}
catch(Exception e){
//the user did not enter numbers
}
}
else{
sender.sendMessage("usage: /add num1 num2");
}
}
return true;
}
return false;
}
Then you could do /add <number 1> <number 2> and it would add those numbers together for you

I edited your code and now it is working !
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("calc")) { //if the command is /calc
if (args.length == 3) { // if the command structure is something like this /calc <number> <operator> <number>
if (args[1].equalsIgnoreCase("+")) { // if the operator is +
double number1 = 0;
double number2 = 0;
double result = 0;
try { // see if the first and second numbers are a double
number1 = Double.parseDouble(args[0]);
number2 = Double.parseDouble(args[2]);
} catch (Exception e) { // if the two arguments aren't numbers
s.sendMessage(ChatColor.RED + "The argument " + ChatColor.DARK_RED + args[0] + ChatColor.RED
+ " or the argument " + ChatColor.DARK_RED + args[2] + ChatColor.RED
+ " is not a number !");
return false; // the code stops here
}
result = number1 + number2; // doing the adition
s.sendMessage(ChatColor.GREEN + "" + number1 + " + " + number2 + " = " + result); // send message to the player with the resut
} else if (args[1].equalsIgnoreCase("*")) { //same as adition
double number1 = 0;
double number2 = 0;
double result = 0;
try {
number1 = Double.parseDouble(args[0]);
number2 = Double.parseDouble(args[2]);
} catch (Exception e) {
s.sendMessage(ChatColor.RED + "The argument " + ChatColor.DARK_RED + args[0] + ChatColor.RED
+ " or the argument " + ChatColor.DARK_RED + args[2] + ChatColor.RED
+ " is not a number !");
return false;
}
result = number1 * number2;
s.sendMessage(ChatColor.GREEN + "" + number1 + " * " + number2 + " = " + result);
} else if (args[1].equalsIgnoreCase("/") || args[1].equalsIgnoreCase(":")) { //same as adition
double number1 = 0;
double number2 = 0;
double result = 0;
try {
number1 = Double.parseDouble(args[0]);
number2 = Double.parseDouble(args[2]);
} catch (Exception e) {
s.sendMessage(ChatColor.RED + "The argument " + ChatColor.DARK_RED + args[0] + ChatColor.RED
+ " or the argument " + ChatColor.DARK_RED + args[2] + ChatColor.RED
+ " is not a number !");
return false;
}
result = number1 / number2;
s.sendMessage(ChatColor.GREEN + "" + number1 + args[1] + number2 + " = " + result);
} else if (args[1].equalsIgnoreCase("-")) { //same as adition
double number1 = 0;
double number2 = 0;
double result = 0;
try {
number1 = Double.parseDouble(args[0]);
number2 = Double.parseDouble(args[2]);
} catch (Exception e) {
s.sendMessage(ChatColor.RED + "The argument " + ChatColor.DARK_RED + args[0] + ChatColor.RED
+ " or the argument " + ChatColor.DARK_RED + args[2] + ChatColor.RED
+ " is not a number !");
return false;
}
result = number1 - number2;
s.sendMessage(ChatColor.GREEN + "" + number1 + " - " + number2 + " = " + result);
} else {
s.sendMessage(ChatColor.RED + "Operator not recognized !");
s.sendMessage(ChatColor.RED + "Please use " + ChatColor.WHITE + "/calc number + number"
+ ChatColor.RED + " OR " + ChatColor.WHITE + "/calc number - number" + ChatColor.RED
+ " OR " + ChatColor.WHITE + "/calc number * number" + ChatColor.RED + " OR "
+ ChatColor.WHITE + "/calc number : number" + ChatColor.WHITE + " to get a result !");
}
} else {
s.sendMessage(ChatColor.RED + "Usage - /calc number operator number ");
}
}
return false;
}

Related

random walk across 10x10 grid array

The purpose of this program is to build a 10x10 array grid made out of periods (.), allow the user to designate a starting point, and then the program will randomly choose numbers which are assigned to directions for the 'walker' to go. Each time it moves it marks its spot with the next letter in the alphabet (the starting point is marked by A). I haven't done this part yet but I know how I will; if the walker crosses out of the bounds of the array (AKA > 10 or < 0) it will say "you were arrested" and if the variable alpha == 'Z' it way say "You made it home".
The main problem as far as I can tell is with the method processing(), where I draw numbers from getRand (which I have confirmed is working) and then assign them directions which are given to the array. But for some reason when it prints the grid it only shows the starting point, and not the movement of the walker.
Another question I have of lesser importance is if there is a more brief way to display my grid than how I have been (A massive brick of text in a System.out.print)
package walktester;
import java.lang.Math;
import java.util.Random;
import java.util.Scanner;
class DrunkWalker {
private char[][] walkgrid = new char[10][10];
private static int randNSEW;
private int randomnum;
private int startrow;
private int startcol;
private char alpha = 'A';
private int nextrow;
private int nextcol;
public DrunkWalker(int r, int c) {
startrow = r;
startcol = c;
nextrow = startrow;
nextcol = startcol;
for (int i = 0; i < 10; i ++) {
for (int j = 0; j < 10; j++)
walkgrid[i][j] = '.';
}
walkgrid[r][c] = alpha;
}
public static void getRand(){
int x100 = 0;
double randomNum = 0.0;
randomNum = Math.random();
x100 = (int) (randomNum * 100);
randNSEW = x100 % 4;
}
public int getNextRow(){
return nextrow;
}
public int getNextCol(){
return nextcol;
}
public void processing(){
for(int i = 0; i < 26; i ++){
getRand();
if(randNSEW == 0){
nextcol--;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 1){
nextrow++;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 2){
nextcol++;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 3){
nextrow--;
walkgrid[nextrow][nextcol] = alpha++;
}
}
}
public char[][] DisplayGrid() {
System.out.print(
walkgrid[0][0] + " " + walkgrid[0][1] + " " + walkgrid[0][2] + " " + walkgrid[0][3] + " " + walkgrid[0][4] + " " + walkgrid[0][5] + " " + walkgrid[0][6] + " " + walkgrid[0][7] + " " + walkgrid[0][8] + " " + walkgrid[0][9] + "\n" +
walkgrid[1][0] + " " + walkgrid[1][1] + " " + walkgrid[1][2] + " " + walkgrid[1][3] + " " + walkgrid[1][4] + " " + walkgrid[1][5] + " " + walkgrid[1][6] + " " + walkgrid[1][7] + " " + walkgrid[1][8] + " " + walkgrid[1][9] + "\n" +
walkgrid[2][0] + " " + walkgrid[2][1] + " " + walkgrid[2][2] + " " + walkgrid[2][3] + " " + walkgrid[2][4] + " " + walkgrid[2][5] + " " + walkgrid[2][6] + " " + walkgrid[2][7] + " " + walkgrid[2][8] + " " + walkgrid[2][9] + "\n" +
walkgrid[3][0] + " " + walkgrid[3][1] + " " + walkgrid[3][2] + " " + walkgrid[3][3] + " " + walkgrid[3][4] + " " + walkgrid[3][5] + " " + walkgrid[3][6] + " " + walkgrid[3][7] + " " + walkgrid[3][8] + " " + walkgrid[3][9] + "\n" +
walkgrid[4][0] + " " + walkgrid[4][1] + " " + walkgrid[4][2] + " " + walkgrid[4][3] + " " + walkgrid[4][4] + " " + walkgrid[4][5] + " " + walkgrid[4][6] + " " + walkgrid[4][7] + " " + walkgrid[4][8] + " " + walkgrid[4][9] + "\n" +
walkgrid[5][0] + " " + walkgrid[5][1] + " " + walkgrid[5][2] + " " + walkgrid[5][3] + " " + walkgrid[5][4] + " " + walkgrid[5][5] + " " + walkgrid[5][6] + " " + walkgrid[5][7] + " " + walkgrid[5][8] + " " + walkgrid[5][9] + "\n" +
walkgrid[6][0] + " " + walkgrid[6][1] + " " + walkgrid[6][2] + " " + walkgrid[6][3] + " " + walkgrid[6][4] + " " + walkgrid[6][5] + " " + walkgrid[6][6] + " " + walkgrid[6][7] + " " + walkgrid[6][8] + " " + walkgrid[6][9] + "\n" +
walkgrid[7][0] + " " + walkgrid[7][1] + " " + walkgrid[7][2] + " " + walkgrid[7][3] + " " + walkgrid[7][4] + " " + walkgrid[7][5] + " " + walkgrid[7][6] + " " + walkgrid[7][7] + " " + walkgrid[7][8] + " " + walkgrid[7][9] + "\n" +
walkgrid[8][0] + " " + walkgrid[8][1] + " " + walkgrid[8][2] + " " + walkgrid[8][3] + " " + walkgrid[8][4] + " " + walkgrid[8][5] + " " + walkgrid[8][6] + " " + walkgrid[8][7] + " " + walkgrid[8][8] + " " + walkgrid[8][9] + "\n" +
walkgrid[9][0] + " " + walkgrid[9][1] + " " + walkgrid[9][2] + " " + walkgrid[9][3] + " " + walkgrid[9][4] + " " + walkgrid[9][5] + " " + walkgrid[9][6] + " " + walkgrid[9][7] + " " + walkgrid[9][8] + " " + walkgrid[9][9] + "\n"
);
return walkgrid;
}
}
public class WalkTester {
public static void main(String[] args) {
Scanner inpr = new Scanner(System.in);
Scanner inpc = new Scanner(System.in);
Scanner inpchoice = new Scanner(System.in);
int r = 0;
int c = 0;
char choice = 'y';
while(choice == 'y' || choice == 'Y') {
System.out.println("Please enter x coordinate between 1 and 10.");
r = inpr.nextInt();
r = r - 1;
System.out.println("Please enter y coordinate between 1 and 10");
c = inpr.nextInt();
c = c - 1;
if(r < 0 || r > 9 || c < 0 || c > 9){
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
DrunkWalker drunkwalker = new DrunkWalker(r, c);
drunkwalker.DisplayGrid();
System.out.println("Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
}
}
The code that moves the walker is in a method called processing(), but you never call it.
You can make your DisplayGrid() method simpler (and it will still print the same stuff):
public char[][] DisplayGrid() {
for(int y = 0; y < 10; y++) {
for(int x = 0; x < 10; x++) {
System.out.print(walkgrid[x][y] + " ");
}
System.out.println();
}
return walkgrid;
}
Your processing() method needs to check if the walker leaves the bounds of the area. If you don't, you'll get an ArrayIndexOutOfBoundsException.
public boolean processing(){
for(int i = 0; i < 26; i ++){
getRand();
if(randNSEW == 0){
nextcol--;
}
if(randNSEW == 1){
nextrow++;
}
if(randNSEW == 2){
nextcol++;
}
if(randNSEW == 3){
nextrow--;
}
if(nextrow < 0 || nextrow >= 10 || nextcol < 0 || nextcol >= 10) {
return false;
}
walkgrid[nextrow][nextcol] = alpha++;
}
return true;
}
Now you need to call processing() and check the return value to see if the walker succeeded:
DrunkWalker drunkwalker = new DrunkWalker(r, c);
boolean walkerSucceeded = drunkwalker.processing();
drunkwalker.DisplayGrid();
if(walkerSucceeded) {
System.out.println("You made it home");
} else {
System.out.println("You were arrested");
}
And keep in mind (as you will see when you test this), that the walker can cross their own tracks (so you might see some letters missing).

How do I display "N/A" instead of max and min values in an expression evaluation?

My code works, but what I need it to do is when nothing is enter the evaluation for the highest and the lowest should be N/A. Right now all it displays is the max and min number when something isn't entered.
Example:
Press K for keyboard or F to read expressions from a file OR escape to exit:
k
Please Enter a Post-Fix Expression (eg: 5 2 *)
Application Closed
Evaluations complete....
Highest Value: -3.4028235E38
Lowest Value: 3.4028235E38
Agregate result: 0.0
Average result: NaN
Valid expressions: 0.0
Invalid Expressions: 0.0
I need the ones in bold to say n/a but i don't know how.
private static void keyboardService(){
while (true){
System.out.println("Please Enter a Post-Fix Expression (eg: 5 2 *)");
String postfix=keyboard.nextLine();
String [] elements =postfix.split(" ");
if (postfix.equals("")){
System.out.println("Application Closed");
evaluation();
System.exit(0);
}
if (elements.length == 3){
try{
num1 = Float.valueOf(elements[0]);
num2 = Float.valueOf(elements[1]);
float total;
if(elements[2].equals("+")){
total = num1 + num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else if(elements[2].equals("*")){
total = num1 * num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else if(elements[2].equals("/")){
total = num1 / num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else if(elements[2].equals("-")){
total = num1 - num2;
display(total + " = " + num1 + elements[2] + num2);
valid_count = valid_count + 1;
calc(total);
}
else{
display("Error Invalid Expression: "+ postfix);{
invalid_count = invalid_count + 1;
}
}} catch(NumberFormatException e){
display("Error Invalid Expresion: "+postfix);
invalid_count = invalid_count + 1;
} //end of second if
} else {
display("Error Invalid Expression: "+ postfix);
invalid_count = invalid_count + 1;
}
}
}//end of keyboard service
////////////////////////////////////////////////////////////////////////////////////////////////////////
private static void calc(float total){
highest = Math.max(highest, total );
lowest= Math.min(lowest, total);
aggregate = aggregate + total;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
private static void evaluation(){
display("Evaluations complete....");
display("Highest Value: " + highest);
display("Lowest Value: " + lowest);
display("Agregate result: " + aggregate );
display("Average result: " + aggregate/valid_count);
display("Valid expressions: " + valid_count);
display("Invalid Expressions: " + invalid_count);
}
}
Here you go:
display("Highest Value: " + (highest == Float.MIN_VALUE ? "N/A" : String.valueOf(highest)));
display("Lowest Value: " + (lowest == Float.MAX_VALUE ? "N/A" : String.valueOf(lowest)));
and so on
In the evaluation method, before you print, check highest and lowest.
if (highest < 0)
display("Highest Value: " + "N/A");
else
display("Highest Value: " + highest);
Beside the fact that a better structure for you code would be the prefered solution you could achieve it with following changes in your code.
in your method ` keyboardService()
...
String [] elements =postfix.split(" ");
boolean validInput = true;
if (postfix.equals("")){
validInput = false;
in your method evaluation()
display("Highest Value: " + (validInput ? highest : "n/a"));
display("Lowest Value: " + (validInput ? lowest : "n/a"));
display("Agregate result: " + (validInput ? aggregate : "n/a"));
display("Average result: " + (validInput ? aggregate / valid_count : "n/a"));
display("Valid expressions: " + valid_count);
display("Invalid Expressions: " + invalid_count);

Java: Highscore function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have created a counting game and I have tried to create a highscore method.
The problem is the program returns "null" when the "Highscore" menu is chosen. What could be causing this?
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
public class Räknesätt {
public static void main(String[]args) throws IOException {
DecimalFormat df = new DecimalFormat("0.00");
int input = Integer.parseInt(JOptionPane.showInputDialog(null, "-------------------------" + "\n\n" +
"1. Spela" + "\n" +
"2. Highscores" + "\n" +
"3. Avsluta" + "\n\n" +
"-------------------------"));
if(input == 2) {
String highscores = "";
int rader = countline("Highscores");
BufferedReader inström1 = new BufferedReader
(new FileReader("Highscores"));
for(int i = 0; i <= rader; i++) {
highscores = inström1.readLine() + "\n";
}
JOptionPane.showMessageDialog(null, highscores);
}
else if(input == 3) {
System.exit(0);
}
else if(input == 1) {
String namn = JOptionPane.showInputDialog(null, "Skriv in ditt namn");
int counter = 0;
int rätt = 0;
int fel = 0;
while(counter < 10) {
int slump1 = 1 + (int)(Math.random()*100);
int slump2 = 1 + (int)(Math.random()*100);
List<String> räknesätt = new LinkedList<String>(Arrays.asList("+",
"-",
"*",
"/"));
int räknesättRand = (int)(Math.random()*4);
String räknesättStr = räknesätt.get(räknesättRand);
counter++;
switch(räknesättStr) {
case "+":
String svarStr1 = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " + " + slump2 + " = ");
int svar1 = Integer.parseInt(svarStr1);
if(svar1 == slump1 + slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
case "-":
String svarStr2 = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " - " + slump2 + " = ");
int svar2 = Integer.parseInt(svarStr2);
if(svar2 == slump1 - slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
case "*":
String svarStr3 = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " * " + slump2 + " = ");
int svar3 = Integer.parseInt(svarStr3);
if(svar3 == slump1 * slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
case "/":
String svarStr = JOptionPane.showInputDialog(null,namn + " räkna ut: " + "\n" + slump1 + " / " + slump2 + " = ");
int svar = Integer.parseInt(svarStr);
if(svar == (double)slump1 / slump2) {
JOptionPane.showMessageDialog(null, namn + " du räknade rätt!");
rätt++;
}
else {
JOptionPane.showMessageDialog(null, namn + " du räknade fel!");
fel++;
}
break;
}
}
JOptionPane.showMessageDialog(null, "Resultat för: " + namn + "\n\n" +
"=========================" + "\n" +
"Antal räknade tal: " + counter + "\n" +
"Antal rätt: " + rätt + "\n" +
"Antal fel: " + fel + "\n" +
"Rättprocent: " + (double)100*rätt/(rätt+fel) + "%");
PrintWriter utström1 = new PrintWriter
(new BufferedWriter
(new FileWriter("Highscores")));
utström1.println(namn + ", " + (double)100*rätt/(rätt+fel) + "% rätt");
utström1.close();
}
}
public static int countline (String filnamn)throws IOException {
BufferedReader inström1 = new BufferedReader
(new FileReader(filnamn));
int lines = 0;
while(inström1.readLine() != null) {
++lines;
}
inström1.close();
return lines;
}
}
Code is trying to open a handle to a non-existent file by the name 'Highscores'.
Problem is being caused by the following line of code :
BufferedReader inström1 = new BufferedReader
(new FileReader("Highscores"));
The solution would be to create this file upfront, at the beginning of the program and write default contents into it.
Here is how you can go about doing it.
private static void createHighScoreFile() throws IOException {
PrintWriter printWriter = new PrintWriter
(new BufferedWriter
(new FileWriter("Highscores")));
printWriter.write("0\n");
printWriter.close();
}
public static void main(String[] args) throws IOException {
createHighScoreFile();
DecimalFormat df = new DecimalFormat("0.00");
There is also one more issue related to reading the contents of the file.
The condition in the for loop attempts to read an extra line from the file, which turns out to be null always. It needs to be fixed this way.
for (int i = 0; i <= rader; i++) {
to
for (int i = 0; i < rader; i++) {

How can I use a while to continuously ask for input from a user and exit the program when "quit" is typed without using system.exit()?

I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
next();
}
public static void next() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
next3(expression);
}
public static void next3(String expression) {
while (!expression.equals("quit")) {
next2(expression);
next();
}
}
public static void next2(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static boolean QuitFunction(String expression) {
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return false;
}
else {
return true;
}
}
}
Take a look at this code. I think this might help you in the right direction. It's similar to what you have already written except it eliminates the need for method calls in your while loop.
Scanner input = new Scanner(System.in);
while (!input.hasNext("quit")) {
String expression = input.nextLine(); // gets the next line from the Scanner
next2(expression); // process the input
}
// once the value "quit" has been entered, the while loop terminates
System.out.println("Goodbye");
Writing it this way drastically cleans up your code and prevents a new declaration of Scanner kb = new Scanner(System.in); each time an input is processed.

What is wrong with my loop

I'm a beginner Java student trying to make this code list the amount saved and interest for 8 years. I'm trying to use a for loop for it. It calculates the interest but only lists it for 1 year. Would appreciate any help solving this problem.
import javax.swing.JOptionPane;
import java.text.*;
public class RetirementGoal3
{
private static DecimalFormat percentFormat = new DecimalFormat("###.##%");
private static DecimalFormat moneyFormat = new DecimalFormat("$###,###,###.00");
private static double interest;
private static double saveAmount;
private static double total;
private static int Max_Year = 8;
private static int year;
private static double totalSave;
private static double totalInterest;
public static void main(String[] args)
{
calculateR();
}
public static double calculateR()
{
String result = JOptionPane.showInputDialog(null, "Enter how much money you can save annually.");
if(result != null)
saveAmount = Double.parseDouble(result);
String result1 = JOptionPane.showInputDialog(null, "Enter your interest rate(As a decimal)");
if(result1 != null)
interest = Double.parseDouble(result1);
totalSave = saveAmount;
for(year = 1; year <= Max_Year; ++ year)
{
totalInterest = saveAmount + saveAmount * interest;
JOptionPane.showMessageDialog(null, " If you save " + moneyFormat.format(totalSave) + " each year for " + Max_Year + " years" + "\n With " + percentFormat.format(interest) + " Interest" + " Without Interest" + "\n\nAfter year " + year + " " + moneyFormat.format(totalSave) + " " + moneyFormat.format(totalInterest));
return total;
}
return total;
}
}
You have a return statement inside your for loop. So, the first iteration returns, exiting the for loop right away.
You have a return statement already in the correct location, after the for loop, so all you have to do is remove the return statement that is inside the for loop.
Change you loop to :
for(year = 1; year <= Max_Year; ++ year)
{
totalInterest = saveAmount + saveAmount * interest;
JOptionPane.showMessageDialog(null, " If you save " + moneyFormat.format(totalSave) + " each year for " + Max_Year + " years" + "\n With " + percentFormat.format(interest) + " Interest" + " Without Interest" + "\n\nAfter year " + year + " " + moneyFormat.format(totalSave) + " " + moneyFormat.format(totalInterest));
}
Remove the return. As soon as you do a return it stops execution of that function and return to the callers.
for(year = 1; year <= Max_Year; ++ year)
{
totalInterest = saveAmount + saveAmount * interest;
JOptionPane.showMessageDialog(null, " If you save " + moneyFormat.format(totalSave) + " each year for " + Max_Year + " years" + "\n With " + percentFormat.format(interest) + " Interest" + " Without Interest" + "\n\nAfter year " + year + " " + moneyFormat.format(totalSave) + " " + moneyFormat.format(totalInterest));
return total; //<-- PROBLEM
}
The problem is the return inside the loop. It executes one iteration and when it gets to the return statement it exits the loop. I guess you want to move it outside the loop.
Update after your comment: Try this
String resultString = "";
for(year = 1; year <= Max_Year; year++)
{
totalInterest = saveAmount + saveAmount * interest;
resultString += " If you save " + moneyFormat.format(totalSave) +
" each year for " + Max_Year + " years" + "\n" +
" With " + percentFormat.format(interest) + " Interest" +
" Without Interest" + "\n\nAfter year " + year + " " +
moneyFormat.format(totalSave) +
" " + moneyFormat.format(totalInterest) + "\n";
}
JOptionPane.showMessageDialog(null, resultString);
return total;
}
Note that this will display things the way you want to but i think your calculations go wrong somewhere.

Categories