if else only executing else in java - java

so i'm struggling with this problem which seems i cannot understand, im completely new in java and i need help.. so i am making a simple program which will determine if you have passed the subject or not via point grades and it seems it only determines the ELSE STATEMENT.. here's the code.. it will really help me out alot.. thanks in advance
String studID=" ",course=" ", name=" ", dept=" ", subj=" ";
double exam1=0, exam2=0, exam3=0, exam4=0;
double avg, pgrade;
String msg=" ";
studID =JOptionPane.showInputDialog("Please fill-out the following fields:"
+ "\nStudent ID: ");
name = JOptionPane.showInputDialog("Name: ");
dept = JOptionPane.showInputDialog("Department: ");
course = JOptionPane.showInputDialog("Course: ");
subj = JOptionPane.showInputDialog("Subject: ");
exam1 = Double.parseDouble(JOptionPane.showInputDialog("First Examination: "));
exam2 = Double.parseDouble(JOptionPane.showInputDialog("Second Examination: "));
exam3 = Double.parseDouble(JOptionPane.showInputDialog("Third Examination: "));
exam4 = Double.parseDouble(JOptionPane.showInputDialog("Final Examination: "));
avg = (exam1 + exam2 + exam3 + exam4)/4;
pgrade =(100 - avg + 10) / 10;
if (avg==100)
{
msg = "passed - Excellent!";
}else if (avg>100 && avg<89)
{
msg = "Passed - Very Good!";
}else if (avg>90 && avg<84)
{
msg = "Passed - Average";
}else if (avg>85 && avg<79)
{
msg = "Passed - Good";
}else if (avg>80 && avg<74)
{
msg = "Passed - Satisfactory";
}else if (avg>75 && avg<49)
{
msg = "Failed";
}else if (avg>50 && avg<0.00)
{
msg = "Dropped";
}else if (avg==0.00 && avg<0.00)
{
msg = "No such Grade";
}else
{
msg = "Out of Range or Invalid.";
}
JOptionPane.showMessageDialog(null, new JTextArea (
"|======Student Details=======|"
+ "\n|StudentID:\t" + studID +"\t |"
+ "\n|Name:\t" + name + "\t |"
+ "\n|Department:\t" +dept+ "\t |"
+ "\n|Course:\t"+course+"\t |"
+ "\n|Subject:\t"+subj + "\t |"
+ "\n|=======Grade Details======= |"
+ "\n|First Second Third Fourth |"
+ "\n|"+exam1+" "+exam2+" "+exam3+" "+exam4+"\t |"
+ "\n|Average:\t" +avg + "\t|"
+ "\n|Point Grade\t:" +pgrade+"\t|"
+ "\n|Remarks:"+msg+"\t|"
+ "\n|=============================|"));
}
}

The condition is wrong because to include a variable in a range you have to set
else if(avg>89 && avg<100)

Your comparisons were wrong to begin with so try something along the lines of what I have corrected, its not the best available, so you can improve it.
String studID=" ",course=" ", name=" ", dept=" ", subj=" ";
double exam1=0, exam2=0, exam3=0, exam4=0;
double avg, pgrade;
String msg=" ";
studID =JOptionPane.showInputDialog("Please fill-out the following fields:"
+ "\nStudent ID: ");
name = JOptionPane.showInputDialog("Name: ");
dept = JOptionPane.showInputDialog("Department: ");
course = JOptionPane.showInputDialog("Course: ");
subj = JOptionPane.showInputDialog("Subject: ");
exam1 = Double.parseDouble(JOptionPane.showInputDialog("First Examination: "));
exam2 = Double.parseDouble(JOptionPane.showInputDialog("Second Examination: "));
exam3 = Double.parseDouble(JOptionPane.showInputDialog("Third Examination: "));
exam4 = Double.parseDouble(JOptionPane.showInputDialog("Final Examination: "));
avg = (exam1 + exam2 + exam3 + exam4)/4;
pgrade =(100 - avg + 10) / 10;
if (avg==100)
{
msg = "passed - Excellent!";
}else if (avg<100 && avg>89)
{
msg = "Passed - Very Good!";
}else if (avg<90 && avg>84)
{
msg = "Passed - Average";
}else if (avg<85 && avg>79)
{
msg = "Passed - Good";
}else if (avg<80 && avg>74)
{
msg = "Passed - Satisfactory";
}else if (avg<75 && avg>49)
{
msg = "Failed";
}else if (avg<50 && avg>0.00)
{
msg = "Dropped";
}else if (avg==0.00)//no one gets below zero in a fair system
{
msg = "No such Grade";
}else
{
msg = "Out of Range or Invalid.";
}
JOptionPane.showMessageDialog(null, new JTextArea (
"|======Student Details=======|"
+ "\n|StudentID:\t" + studID +"\t |"
+ "\n|Name:\t" + name + "\t |"
+ "\n|Department:\t" +dept+ "\t |"
+ "\n|Course:\t"+course+"\t |"
+ "\n|Subject:\t"+subj + "\t |"
+ "\n|=======Grade Details======= |"
+ "\n|First Second Third Fourth |"
+ "\n|"+exam1+" "+exam2+" "+exam3+" "+exam4+"\t |"
+ "\n|Average:\t" +avg + "\t|"
+ "\n|Point Grade\t:" +pgrade+"\t|"
+ "\n|Remarks:"+msg+"\t|"
+ "\n|=============================|"));
}}

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).

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

I'm having problems accessing the total price I initialized inside my if else statements

How can I get the sum of the three Total prices inside the if else statements for red velvet, buttercream and vanilla? And display it in allTextArea text area?
Here's my code:
double redVelvetPrice = 4.00;
double buttercreamPrice = 7.00;
double vanillaPrice = 3.00;
double firstHalf = 6.00;
double firstDozen = 12.00;
double firstBox = 25;
double secondHalf = 6.00;
double secondDozen = 12.00;
double secondBox = 25;
double thirdHalf = 6.00;
double thirdDozen = 12.00;
double thirdBox = 25;
String s1 = "";
String s2 = "The flavors you selected is/are: \n";
String s3 = "";
String s4 = "";
String s5 = "";
String totalPrice = "";
if (redVelvetCB.isSelected()){
s1=s1+ " "+ redVelvetCB.getText() + '\n';
if (firstHalfRB.isSelected()){
s3 ="A " + firstHalfRB.getText() + " of Red Velvet Cupcakes\n = $" + redVelvetPrice * firstHalf + '\n' + '\n';
}
else if (firstDozenRB.isSelected()){
s3 =firstDozenRB.getText() + " of Red Velvet Cupcakes\n = $" + redVelvetPrice * firstDozen + '\n' + '\n';
}
else if (firstBoxRB.isSelected()){
s3 =firstBoxRB.getText() + " of Red Velvet Cupcakes\n = $" + redVelvetPrice * firstBox + '\n' + '\n';
}
}
if (buttercreamCB.isSelected()){
s1=s1+ " "+ buttercreamCB.getText() + '\n';
if (secondHalfRB.isSelected()){
s4 ="A " + secondHalfRB.getText() + " of Buttercream Cupcakes\n = $" + buttercreamPrice * secondHalf + '\n' + '\n';
}
else if (secondDozenRB.isSelected()){
s4 =secondDozenRB.getText() + " of Buttercream Cupcakes\n = $" + buttercreamPrice * secondDozen + '\n' + '\n';
}
else if (secondBoxRB.isSelected()){
s4 =secondBoxRB.getText() + " of Buttercream Cupcakes\n = $" + buttercreamPrice * secondBox + '\n' + '\n';
}
}
if (vanillaCB.isSelected()){
s1=s1+ " "+ vanillaCB.getText() + '\n';
if (thirdHalfRB.isSelected()){
s5 ="A " + thirdHalfRB.getText() + " of Vanilla Cupcakes\n = $" + vanillaPrice * thirdHalf + '\n' + '\n';
}
else if (thirdDozenRB.isSelected()){
s5 =thirdDozenRB.getText() + " of Vanilla Cupcakes\n = $" + vanillaPrice * thirdDozen + '\n' + '\n';
}
else if (thirdBoxRB.isSelected()){
s5 =thirdBoxRB.getText() + " of Vanilla Cupcakes\n = $" + vanillaPrice * thirdBox + '\n' + '\n';
}
allTextArea.setText(greeting+s2+"\n"+s1+"\n"+s3+s4+s5+"\nTotal Price is "+totalPrice+".\n"+deliv+payment+bye);
I tried to set the total Price equal to redVelvetPrice + butercreamPrice + vanillaPrice, but the answer would be 14.0 which is the sum of the variables I initialized outside the if else statements (4.00,7.00,3.00),
I want it to be the sum of the prices of the three after selecting the quantity of each flavor. Help me.
You should use an other data type for the totalPrice. It's easier to calculate with numbers than strings.
double totalPrice = 0f;
After that you add up all the different combinations in your if/else statements
if (firstHalfRB.isSelected()){
s3 = "A " + firstHalfRB.getText() + " of Red Velvet Cupcakes\n = $" + redVelvetPrice * firstHalf + "\n\n";
totalPrice += (redVelvetPrice * firstHalf);
}
else if (firstDozenRB.isSelected()){
s3 = firstDozenRB.getText() + " of Red Velvet Cupcakes\n = $" + redVelvetPrice * firstDozen + "\n\n";
totalPrice += (redVelvetPrice * firstDozen);
}
When printing the total in the TextArea you may want to format it so it only has 2 positions after decimal point:
String.format("%.2f", totalPrice);

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

SimpleDateFormat showing too much info

This is a exercise that computes compatibility between two persons based on https://en.wikipedia.org/wiki/Biorhythm, it works well. However when executing, the program shows the date as for example "Fri Apr 08 00:00:00 EET 2014", but I would like it to show this info without hours, minutes, seconds and time zone. What to do?
import java.util.Scanner;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class bior {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String nameOne;
String nameTwo;
String dobOneIn;
String dobTwoIn;
Date dobOne = new Date();
Date dobTwo = new Date();
boolean validEntry;
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Enter name of first person!");
nameOne = input.nextLine();
while (nameOne.equals("")) {
System.out.println("Enter name of first person!");
nameOne = input.nextLine();
}
System.out.println("Enter name of second person!");
nameTwo = input.nextLine();
while (nameTwo.equals("")) {
System.out.println("Enter name of second person!");
nameTwo = input.nextLine();
}
do {
try {
System.out.println("Enter date of birth of " + nameOne + "! (MM/DD/YYYY)");
dobOneIn = input.nextLine();
dobOne = format.parse(dobOneIn);
validEntry = true;
}
catch (ParseException e) {
validEntry = false;
}
} while (!validEntry);
do {
try {
System.out.println("Enter date of birth of " + nameTwo + "! (MM/DD/YYYY)");
dobTwoIn = input.nextLine();
dobTwo = format.parse(dobTwoIn);
validEntry = true;
}
catch (ParseException e) {
validEntry = false;
}
} while (!validEntry);
int diff = Math.abs((int)((dobOne.getTime() - dobTwo.getTime()) / (24 * 60 * 60 * 1000)));
System.out.println();
System.out.println("Name of second person: " + nameTwo + ".");
System.out.println("DOB of " + nameOne + ": " + dobOne + ".");
System.out.println("DOB of " + nameTwo + ": " + dobTwo + ".");
System.out.println("Difference between DOBs (days): " + diff + ".");
float physicalBio = diff % 23;
float emotionalBio = diff % 28;
float intellectualBio = diff % 33;
physicalBio = physicalBio / 23;
emotionalBio = emotionalBio / 28;
intellectualBio = intellectualBio / 33;
if (physicalBio > 0.5) {
physicalBio = 1 - physicalBio;
}
if (emotionalBio > 0.5) {
emotionalBio = 1 - emotionalBio;
}
if (intellectualBio > 0.5) {
intellectualBio = 1 - intellectualBio;
}
physicalBio = 100 - (physicalBio * 100);
emotionalBio = 100 - (emotionalBio * 100);
intellectualBio = 100 - (intellectualBio * 100);
System.out.println("Physical compatibility: " + java.lang.Math.round(physicalBio) + " %.");
System.out.println("Emotional compatibility: " + java.lang.Math.round(emotionalBio) + " %.");
System.out.println("Intellectual compatibility: " + java.lang.Math.round(intellectualBio) + " %.");
}
}
You declared a SimpleDateFormat but never used it:
Try this:
System.out.println("DOB of " + nameOne + ": " + format.format(dobOne) + ".");
You should make the following modification :
System.out.println("DOB of " + nameOne + ": " + format.format(dobOne) + ".");
System.out.println("DOB of " + nameTwo + ": " + format.format(dobTwo) + ".");
SimpleDateFormat has the format(Date date) method for this purpose.
You can print dobOneIn and dobTwoIn in your println statement which already has format you need:
System.out.println();
System.out.println("Name of second person: " + nameTwo + ".");
System.out.println("DOB of " + nameOne + ": " + dobOneIn + ".");
System.out.println("DOB of " + nameTwo + ": " + dobTwoIn + ".");
System.out.println("Difference between DOBs (days): " + diff + ".");

Categories