Java: Highscore function [closed] - java

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++) {

Related

Why my method don't read all of my File? ... Java?

I have to display all of records in my blocks (text files), and do a split to "cover" the Fields Separators, but only the first record of my blocks are diplayed. What am I doing wrong?
enter code here
public static void listAllStudents() throws IOException {
File path = new File(Descriptor.getBlockPath());
for (int i = 0; i < path.listFiles().length; i++) {
try {
FileInputStream file = new FileInputStream(Descriptor.getBlockPath() + "BLK" + i + ".txt");
InputStreamReader entrada = new InputStreamReader(file);
BufferedReader buf= new BufferedReader(entrada);
String piece = " ";
System.out.println("\nBLOCO " + i + " ------------------------------------------------------ +");
do {
if (buf.ready()) {
piece = buf.readLine();
System.out.println("\n¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨");
String string = " ", field[] = piece.split(Descriptor.getFieldSeparator());
string = " ";
System.out.println("CPF: " + field[0]);
System.out.println("Name: " + field[1]);
System.out.println("Course: " + field[2]);
System.out.println("Age: " + field[3]);
System.out.println("Phone: " + field[4]);
System.out.println("Active: " + field[5]);
string = " ";
}
} while (buf.ready());
buf.close();
} catch (IOException e) {
System.out.println();
}
}
}
See the documentation for the BufferedReader.readLine() method:
or null if the end of the stream has been reached
Then change your code to read the file line by line:
while ((piece = buf.readLine()) != null) {
String field[] = piece.split(Descriptor.getFieldSeparator());
if (field.length >= 6) {
System.out.println("CPF: " + field[0]);
System.out.println("Name: " + field[1]);
System.out.println("Course: " + field[2]);
System.out.println("Age: " + field[3]);
System.out.println("Phone: " + field[4]);
System.out.println("Active: " + field[5]);
}
}

Java: Number game only showing two players

I have created a number guessing game. The program lets you play as many rounds as you like and in the end it is going to display the number of guesses for each round. However, my program only gives output for two players... Here is the code:
import javax.swing.*;
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Hil0 {
public static void main(String[]args) throws IOException {
List<String> highscore = new LinkedList<String>(Arrays.asList());
while(true) {
String namn = JOptionPane.showInputDialog(null, "Välj namn");
int a = Integer.parseInt(JOptionPane.showInputDialog(null, "Mellan 0 och vilket tal vill du gissa?"));
int slumptal = 1 + (int)(Math.random()*a);
int counter = 0;
int count = 0;
count++;
String output = "";
while(true) {
counter++;
String inputStr = JOptionPane.showInputDialog(null, "Gissa vilket tal (0-" + a +")");
int input = Integer.parseInt(inputStr);
if(input < slumptal) {
JOptionPane.showMessageDialog(null, "Talet: " + input + " är för litet");
}
else if(input > slumptal) {
JOptionPane.showMessageDialog(null, "Talet: " + input + " är för stort");
}
else if(input == slumptal) {
highscore.add(namn + " " + counter + " gissningar" + " (0-" + a + ")");
JOptionPane.showMessageDialog(null, "Rätt!" + "\n" +
"Antal gissningar: " +
counter);
String janej = JOptionPane.showInputDialog(null, "Vill du spela igen?");
if(janej.equalsIgnoreCase("ja")) {
break;
}
else if(janej.equalsIgnoreCase("nej")) {
for(int i = 0; i <= count; i++) {
output += highscore.get(i) + "\n";
}
JOptionPane.showMessageDialog(null,"Resultat:" + "\n\n" + output);
System.exit(0);
}
}
}
}
} //Main
} //Class
May be it is because you variable count in each loop would be equals to 1. Try to replace it in to scope out of while loop.
It would be looks like this:
import javax.swing.*;
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Hil0 {
public static void main(String[]args) throws IOException {
List<String> highscore = new LinkedList<String>(Arrays.asList());
int count = 0; // put it here instead
while(true) {
String namn = JOptionPane.showInputDialog(null, "Välj namn");
int a = Integer.parseInt(JOptionPane.showInputDialog(null, "Mellan 0 och vilket tal vill du gissa?"));
int slumptal = 1 + (int)(Math.random()*a);
int counter = 0;
// int count = 0; move it out of while
count++;
String output = "";
while(true) {
counter++;
String inputStr = JOptionPane.showInputDialog(null, "Gissa vilket tal (0-" + a +")");
int input = Integer.parseInt(inputStr);
if(input < slumptal) {
JOptionPane.showMessageDialog(null, "Talet: " + input + " är för litet");
}
else if(input > slumptal) {
JOptionPane.showMessageDialog(null, "Talet: " + input + " är för stort");
}
else if(input == slumptal) {
highscore.add(namn + " " + counter + " gissningar" + " (0-" + a + ")");
JOptionPane.showMessageDialog(null, "Rätt!" + "\n" +
"Antal gissningar: " +
counter);
String janej = JOptionPane.showInputDialog(null, "Vill du spela igen?");
if(janej.equalsIgnoreCase("ja")) {
break;
}
else if(janej.equalsIgnoreCase("nej")) {
for(int i = 0; i < count; i++) { // use < insetad of <= because you count from 0
output += highscore.get(i) + "\n";
}
JOptionPane.showMessageDialog(null,"Resultat:" + "\n\n" + output);
System.exit(0);
}
}
}
}
}
}

Using JOptionPane to print reports

Okay so now I got my code to compile and run, but the output is incorrect now. I need to be able to select an option and then for 2, and 3 have 3 additional options after selecting that option. How should I adapt my coding to do this?
Task:
List of all information
List of all surgeries for a specific doctor (prompt for the doctor)
List of all surgeries of a specific type (prompt for the surgery type)
Total amount of surgery fees paid to each Doctor
Average Fees
Data File (patient.txt):
11111,Smith,Norris,Thyroid,1000.00
11112,Obama,Norris,Lasek,500.00
11113,Hoover,Norris,Dental,100.00
11114,Cena,Norris,Lasek,500.00
11115,Leto,Norris,Thyroid,1000.00
22221,Clark,Bond,Thyroid,1000.00
22222,Chang,Bond,Lasek,500.00
22223,Dent,Bond,Dental,100.00
22224,Nixon,Bond,Lasek,500.00
22225,Washington,Bond,Dental,100.00
33331,Jones,Lee,Dental,100.00
33332,Ross,Lee,Lasek,500.00
33333,Gates,Lee,Thyroid,1000.00
33334,Johnson,Lee,Thyroid,1000.00
33335,Carter,Lee,Dental,100.00
Code so far for reference:
package Patient_Reports_Package;
/**
* Created by bzink on 8/28/2015.
*/
import javax.swing.*;
import java.io.*;
import java.util.StringTokenizer;
/**
* The Patient_Reports_File class reads the data file into an array, and then has a menu for 5 reports.
*/
class Patient_Reports {
private final int[] id = new int[100];
private final String[] patient = new String[100];
private final String[] doctor = new String[100];
private final String[] surgery = new String[100];
private final double[] cost = new double[100];
private int count = -1;
private int i;
public static void main (String[] args) {
int selection;
String report_number;
Patient_Reports patient = new Patient_Reports();
patient.start_system();
report_number = patient.menu();
selection = Integer.parseInt(report_number);
while (selection !=6) {
if (selection == 1) {
patient.allInformationReport();
} else if (selection == 2) {
patient.surgeryDoctorReport();
} else if (selection == 3) {
patient.surgeryTypeReport();
} else if (selection == 4) {
patient.doctorFeesReport();
} else if (selection == 5) {
patient.averageFeesReport();
}
report_number = patient.menu();
selection = Integer.parseInt(report_number);
}//while loop
patient.writeReports();
System.exit(0);
}//main
//Read Data File into Array
private void start_system() {
String newLine;
try {
//define a file variable for Buffered read
BufferedReader Patient_Reports = new BufferedReader(new java.io.FileReader("C:\\Users\\Brandon\\" +
"Downloads\\Patient_Reports_File\\patient.txt"));
//read lines in file until there are no more lines in the file to read
while ((newLine = Patient_Reports.readLine()) != null) {
//there is a "," between each data item in each line
StringTokenizer delimiter = new StringTokenizer(newLine, ",");
count = count + 1;
id[count] = Integer.parseInt(delimiter.nextToken());
patient[count] = delimiter.nextToken();
doctor[count] = delimiter.nextToken();
surgery[count] = delimiter.nextToken();
cost[count] = Double.parseDouble(delimiter.nextToken());
}//while loop
Patient_Reports.close();
}//end try
catch (IOException error) {
//there was an error on the file writing
System.out.println("Error on file read " + error);
}//end catch
}//end start_system
//Report Menu
private String menu () {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Id ").append(" \n");
stringBuilder.append("Patient ").append(" \n");
stringBuilder.append("Doctor ").append(" \n");
stringBuilder.append("Surgery ").append(" \n");
stringBuilder.append("Cost ").append(" \n");
for (int i = 0; i < 6; i++) {
stringBuilder.append(i).append(" Name"+i).append('\n');
}
String startTag ="<font size='2' color='red'>";
String endTag = "</font>";
stringBuilder.append(startTag).append("Some content").append(endTag);
JOptionPane.showMessageDialog(null, stringBuilder.toString());
return stringBuilder.toString();
}//end menu\
/*
//Report Menu
private String menu() {
String report;
String Output = "Reports" + "\n" + "1. All_Information_Report" + "\n" +
"2. Surgeries_Doctor_Report" + "\n" +
"3. Surgeries_Type_Report" + "\n" +
"4. Doctor_Fees_Report" + "\n" +
"5. Average_Fees_Report" + "\n" +
"6. Exit" + "\n" +
" " + "\n" +
"Select a Report >";
report = JOptionPane.showInputDialog(null,
Output, "", JOptionPane.QUESTION_MESSAGE);
return report;
}//end menu\
*/
//Report containing all of the information
private void allInformationReport() {
System.out.println("All Information Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
/* void selectDoctor()
{
//select doctor
String doctorOutput;
//int intNum=0,intNum1=0,i,x=-1;
count=count+1;
doctorOutput = "Enter the Doctor's Name";
doctor[count] =JOptionPane.showInputDialog(null,doctorOutput,
"",JOptionPane.QUESTION_MESSAGE);
}//end select doctor
//Start Doctor Menu
public static void doctorMenu (String[] args) {
int selection;
String doctorName;
Patient_Reports doctor = new Patient_Reports();
doctor.start_system();
doctorName = doctorMenu();
selection = Integer.parseInt(doctorName);
while (selection !=4) {
if (selection == 1) {
doctor.norrisSurgeries();
} else if (selection == 2) {
doctor.bondSurgeries();
} else if (selection == 3) {
doctor.leeSurgeries();
}
doctorName = doctorMenu();
selection = Integer.parseInt(doctorName);
}//while loop
doctor.writeReports();
System.exit(0);
}//End Doctor Menu
//Report on all surgeries by Dr. Norris
private void norrisSurgeries() {
System.out.println("Norris Surgeries Report");
for (i = 0; i <= count; ++i) {
System.out.println(doctor[i] + " " + surgery[i] + " ");
}//for loop
}//end report
//Report on all surgeries by Dr. Bond
private void bondSurgeries() {
System.out.println("Bond Surgeries Report");
for (i = 0; i <= count; ++i) {
System.out.println(doctor[i] + " " + surgery[i] + " ");
}//for loop
}//end report
//Report on all surgeries by Dr. Lee
private void leeSurgeries() {
System.out.println("Lee Surgeries Report");
for (i = 0; i <= count; ++i) {
System.out.println(doctor[i] + " " + surgery[i] + " ");
}//for loop
}//end report
*/
//Report on all surgeries of a specific doctor (prompt for the doctor)
private void surgeryDoctorReport() {
System.out.println("Surgeries Doctor Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
/*
void selectSurgery()
{
//select surgery
String surgeryOutput;
//int intNum=0,intNum1=0,i,x=-1;
count=count+1;
surgeryOutput = "Enter the Surgery Type";
doctor[count] =JOptionPane.showInputDialog(null,surgeryOutput,
"",JOptionPane.QUESTION_MESSAGE);
}//end select surgery
*/
//Report on all surgeries of a specific type(Prompt for the surgery type)
private void surgeryTypeReport() {
System.out.println("Surgeries Type Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Report on the total amount of fees paid to each doctor
private void doctorFeesReport() {
System.out.println("Doctor Fees Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Report on the Average Fee
private void averageFeesReport() {
System.out.println("Average Fees Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Store Data File in Array
private void writeReports()
{
try {
BufferedWriter Patient_Reports = new BufferedWriter(new java.io.FileWriter("patient_out.txt"));
for (i = 0; i <= count; ++i) {
//put "," between each data item in the file
Patient_Reports.write(id[i] + "," + patient[i] + "," + doctor[i] + "," +
surgery[i] + "," + cost[i] + ",");
//write a new line in the file
Patient_Reports.newLine();
}//for loop
Patient_Reports.close();
}//end try
catch (IOException error) {
//there was an error on the write to file
System.out.println("Error on file write " + error);
}//end error
}//end write_reports
}
'
Use String or StringBuilder or StringBuffer to do this. But instead of String use either StringBuilder or StringBuffer. Since for String, you need some extra objects for String manipulation.
Ex:
StringBuilder sb = new StringBuilder();
sb.append("Id ").append(" Name\n");
for (int i = 0; i < 10; i++) {
sb.append(i).append(" Name"+i).append('\n');
}
JOptionPane.showMessageDialog(null, sb.toString());
Use HTML tags to produce better formatted results like <font>, <table>, etc.
Ex:
String startTag ="<font size='2' color='red'>";
String endTag = "</font>";
sb.append(startTag+"Some content"+endTag);

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.

How do you create a calculator in bukkit?

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;
}

Categories