Java Calculator (need assistance for my first project) - java

This is my first try on Java. The project is a calculator that takes a number, an operator signal (+,-,*,/), and another number to create an equation and give the final value of it, asking after that if the user wants to restart the program for another equation or not. I would like to know if there is anything that I can do to improve my code.
Thanks!
/*
Name: Felipe de Araujo
Project #: 1
*/
import java.util.Scanner; //Importing API.
public class Calculator {
public static void main(String[] args){
int a = 1; //Creating variable for the first while loop.
System.out.println("Welcome to the calculator!"); //Program introduction.
while (a == 1){
Scanner input = new Scanner(System.in); //Creating the input.
double firstNumber, secondNumber, result; char operator; //Creating all variables.
//Program asking for the first number.
System.out.print("First Number: ");
firstNumber = input.nextDouble();
//Program asking for the operator
System.out.print(firstNumber + " (+,-,*,/): ");
operator = input.next(".").charAt(0);
int repeat = 1; //Creating variable for the next while loop.
//Evaluating the operator to determine if it is inside the criteria (+,-,*,/).
if (operator == '+' || operator == '-' || operator == '*' || operator == '/'){
System.out.print(firstNumber + " " + operator + " Second Number: "); //If the operator is inside the criteria than start
//asking for the second number.
}
else { //If the operator is not inside the criteria run the loop until the user type something that is.
while (repeat == 1){
System.out.print(operator + " not recognized, please select between (+,-,*,/): ");
operator = input.next(".").charAt(0);
if (operator == '+' || operator == '-' || operator == '*' || operator == '/') {
System.out.print(firstNumber + " " + operator + " Second Number: ");
repeat++;
}
}
}
secondNumber = input.nextDouble(); //Initialize the secondNumber variable to the number typed.
//Equalling the variable result to the return given by the method calculatorMethod, with the variables given.
result = calculatorMethod(firstNumber, secondNumber, operator);
System.out.println(firstNumber + " " + operator + " " + secondNumber + " = " + result);//Printing the equation.
System.out.println(" ");
// Asking the user to continue the program for another operation.
char out;//Creating the variable out.
System.out.print("[y/Y] - continue | [n/N] or any other to end program: ");
out = input.next(".").charAt(0);//Initializing the variable out to what was typed.
//Verifying if the user wants to continue the program.
if (out == 'y' || out == 'Y'){
System.out.println(" ");
}
else {//If the users type anything besides y/Y the program will exit the main loop, ending the program.
System.out.println("Bye!");
a++;
}
}
}
//Declaring the calculatorMethod and all its behaviors.
private static double calculatorMethod(double a, double b, char c){
if (c == '+'){
return a + b;
}
else if (c == '-'){
return a - b;
}
else if (c == '*'){
return a * b;
}
else {
return a / b;
}
}
}

hello and welcome to the Java world :) . Some tips :
Try to give clear name to your variables. 'a', 'b', 'c' could be complicated to understand.
Favor short methods to improve the readability of your code. For example you can create an other method which return an object of : separator + the two numbers and an other one which print the result.
You can use switch(variable) in your calculatorMethod method. For example :
switch (c) { // you have to change the name of all the variables 'c', 'a' and 'b'
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
default:
return a / b;
}
}
You can create an enum or a list with the different operators.
When you check the input operator, you can use a while() loop and delete the if...else loop. The condition of the while loop could be "while the operator is not the correct one (and so, not contained in the list of correct operators), loop again and again".
The scanner initialization Scanner input = new Scanner(System.in); should be out the while() loop because you need to initialize only one time the scanner and in this case, you initialize X times (X refers to the numbers of loops).
Good luck :)

Related

Need Help to Understand Some Basic Java concepts about While loop conditional statements and type conversion

I was just trying to code a simple calculator and it works fine...
What I want to do now is include a 'do while' or 'while' loop to repeat a statement till a user enters one of the four basic operator signs. I have achieved it using other methods (if and switch) but I want to simplify it.
Also I faced a lot of problems learning how to parse a character in scanner and JPane methods. I could achieve using various resources on the internet but a simple method that would help me understand the logic more clearly and not just achieve will be highly appreciated...
public class MyCalculator{
public static void main (String [] args){
// Let us code a simple calculator
char OP;
System.out.println("This is a simple calculator that will do basic calculations such as :\nAddition, Multiplication, Substraction and Division.");
// Create a scanner object to Read user Input.
Scanner input = new Scanner(System.in);
System.out.println("Enter Any positive number followed by pressing ENTER.");
int firstNum = input.nextInt();
// Need to Loop the below statement till one of the four (+,-,*,/) operator is entered.
System.out.println("Enter your choice of OPERATOR sign followed by pressing ENTER.");
OP = input.next().charAt(0);
System.out.println("Enter your Second number followed by an ENTER stroke.");
int secNum = input.nextInt();
// Various possible Resolution
int RSum = firstNum+secNum;
int RSubs= firstNum-secNum;
int RPro = firstNum*secNum;
double DPro = firstNum/secNum;
// Conditional statements for Processing
Switch (OP){
case '+': System.out.println("The Resulting sum is "+ RSum);
break;
case '-': System.out.println("The Resulting sum is "+ RSubs);
break;
case '*': System.out.println("The Resulting Product is "+ RPro);
break;
case '/': System.out.println("The Resulting Divisional product is "+ DPro);
break;
default : System.out.println("Try Again");
}
}
}
You can use something like this:
while(scanner.hasNext()) {
//some code
int number = scanner.NextInt();
}
But I would implement a calculator as follow:
int num1 = scanner.NextInt();
String op = scanner.Next();
int num2 = scanner.NextInt();
You can loop through a String as follow and do your checks:
for (char ch : exampleString.toCharArray()){
System.out.println(ch);
}
You can also loop through a String as follow:
for (int i=0; i<examplestring.length(); i++) {
char c = examplestring.charAt(i);
}
You can loop until you get a + or a - as follow:
char operator;
do {
char operator = scanner.next().get(0);
}while(operator != '+' || operator != '-')
You can loop and print error messages as follow:
char operator;
do {
char operator = scanner.next().get(0);
if(!isValidOperator(operator)) {
System.out.println("invalid operator");
}
}while(!isValidOperator(operator))
public boolean isValidOperator(char operator) {
if(operator == '+') {
return true;
} else if (operator == '-') {
return true;
}
return false;
}

Trying to create a quiz with java, but something went wrong. What part of my program did i screw up?

So I'm starting to get the hang of java, and I'm creating a quiz as a mini project. However, when I get to the input part of my program, it breaks down. What's going on?
I also apologize for the formatting
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int score = 0;
int total = 0;
System.out.println("Are you ready for a quiz? (Y/N)");
char answer = in.findInLine(".").charAt(0);
if (answer == 'Y' || answer == 'y');
{
String a = "Barrow";
String b = "Juneau";
String c = "Anchorage";
String d = "Annapolis";
System.out.println("Alright! Lets get right to it!");
System.out.println("What is the Capital of Alaska?");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
char choice = in.findInLine(".").charAt(0);
if (choice == 'B' || choice == 'b')
{
System.out.println("Good Job! 1 point for you!");
score = score + 1;
}
else
{
System.out.println("Incorrect! the answer was actually " + b);
}
String e = "Yes";
String f = "No";
System.out.println("Alright, Next Question! Can you"
+ " store the value 'cat' in a variable of type int?");
System.out.println("A: " + e);
System.out.println("B: " + f);
char secchoice = in.findInLine(".").charAt(0);
if (secchoice == 'A' || secchoice == 'a')
{
System.out.println("Correct! Good Job!");
score = score + 1;
}
else
{
System.out.println("Incorrect");
}
System.out.println("What is the result of 2+2X3-5?");
int result = in.nextInt();
if (result == 3)
{
System.out.println("Correct! Good Job!");
}
else
{
System.out.println("Incorrect");
}
System.out.println("Your total score was " + score + "out of 3");
}
}
}
You are getting a NullPointerException on line 26 because of the way that findInLine() works. Basically, you have used up the one line of input you give it when it starts and the Scanner has advanced passed it to find the next one (which does not exist). In other words, you should use another method for Scanner or use an entirely different approach for getting input.
For example, it is preferable to use this technique
char answer = in.nextLine().charAt(0);
because nextLine() will wait until it has more input.
Of course, you will have to come up with some way to parse the input from the user to make sure that it is valid (i.e. if they can only choose between 'Y' and 'N' you handle the case where they choose neither).
That would look something like
char answer = parseInput(in.nextLine().charAt(0));
where parseInput(String s) is a method you write yourself.
As far as other approaches go, this tutorial from Oracle can help you get started.

Initializing a variable Java

I'm writing a simple program with a do while loop and switch, which cna accept a mathematical operation and execute it for given 2 numbers.
The problem I have is, why should I initialize the result produced by the operation to zero at the beginning.
If I don't make ans=0, it gives me errors. If the given conditions are not met, some code parts are not executed and I don't need "ans".
package q3;
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operator;
float no1, no2, ans=0; // <-------------- Why should I initialize ans
do {
System.out.println(" Mathematical Operations to be performed :");
System.out.println("\t * Multiplication\n\t / Division\n\t + Addition\n\t - Subtraction");
System.out.println("Press any other character to exit");
System.out.print("Mathematical Operator : ");
operator = input.next().charAt(0);
if (operator == '*' || operator == '/' || operator == '+' || operator == '-') {
System.out.print("Number 1: ");
no1 = input.nextFloat();
System.out.print("Number 2: ");
no2 = input.nextFloat();
switch (operator) {
case '*':
ans = no1 * no2;
break;
case '/':
ans = no1 / no2;
break;
case '+':
ans = no1 + no2;
break;
case '-':
ans = no1 - no2;
break;
}
System.out.println("The answer of " + no1 + operator + no2 + " = " + ans);
}
} while (operator == '*' || operator == '/' || operator == '+' || operator == '-');
}
}
Java requires that all local variables are initialised before they are used.
In your print line, you read the value of abs, but not all control paths set a value to it. (Even though you think you've covered all possibilities of your switch given the outer if, the compiler will not see things that way: some other thread could modify operator).
So your IDE / compiler is suggesting that you initialise it at the point of declaration.
This is because if no case evaluates to true, the value of ans will not be set. So you cannot use it.
You can overcome this by adding a default case, and setting the value of ans as 0 in that.
You should initialize ans=0; because you didn't have a default value for ans, for this you need to initialized it.
But if you add the defualt value you don't need to initialize it like this:
...
case '-':
ans = no1 - no2;
break;
default :
ans = someValue;
break;
Well, it could be that none of the case statements apply and as a result ans would still be un-initialized. And since local variables have to be initialised before they are being used, you get this error.
If you didnt initialize it, you ans will have a garbage value at first.
It is not compulsory to initialize it.
But your program will be a better program if you initialize it.

How to fix this code for a Java program that simulates a simple calculator?

Kindly help me to fix this code for a Java program that simulates a simple calculator.
It reads two integers and a character. If the character is a +, the sum is printed; if it is a -, the difference is printed; if it is a *, the product is printed; if it is a /, the quotient is printed; and if it is a %, the remainder is printed.
import java.util.Scanner;
class calc {
private int a,b,and;
private char c;
public static void main (String args[])
{
System.out.println ("Enter the first Integer");
Scanner scan = new Scanner (System.in);
a=scan.nextInt();
System.out.println("Enter the second Integer");
b=scan.nextInt();
System.out.println("Enter the operation sign");
c=scan.nextChar();
if (c=='+')
and=a+b;
else if (c=='-')
and=a-b;
else if (c=='*')
and=a*b;
else if (c=='/')
and=a/b;
else if (c=='%')
and=a%b;
else
{
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is "+ ans);
}
}
Couple of things:
Make all your variables static so that you can use them within main or i would suggest move them within main.
Use nextLine().charAt(0) instead of nextChar which isn't defined in Scanner.
Instead of newxInt(); use nextInt(); api of Scanner
out is a static field (note lower case o), so change System.Out to System.out.
do an import static java.lang.System.exit; so you could use exit(0); without any issues from compiler.
Edit: Just for OP (Make sure you give meaningful name to variables) -
import static java.lang.System.exit;
import java.util.Scanner;
public class calc {
public static void main(String args[]) {
int a, b, ans = 0;
char c;
System.out.println("Enter the first Integer");
Scanner scan = new Scanner(System.in);
a = scan.nextInt();
scan.nextLine();
System.out.println("Enter the second Integer");
b = scan.nextInt();
scan.nextLine();
System.out.println("Enter the operation sign");
c = scan.nextLine().charAt(0);
if (c == '+')
ans = a + b;
else if (c == '-')
ans = a - b;
else if (c == '*')
ans = a * b;
else if (c == '/')
ans = a / b;
else if (c == '%')
ans = a % b;
else {
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is " + ans);
}
}
Output:
Enter the first Integer
10
Enter the second Integer
20
Enter the operation sign
+
The result is 30
Change
c=scna.nextChar();
to
c=scan.nextChar();
Also change
exit(0)
to
System.exit(0)
b=scan.newxInt(); to b=scan.nextInt();
Change all Out to out

While loop JOptionPane issues

Ok - I know that I am fairly close to the solution but need a nudge in the right direction. I need the user to hit YES and the program to begin asking the question again.
After execution, I get the following errors
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 1 at java.lang.String.charAt(Unknown
Source) at Vowel3.main(Vowel3.java:49)
// java class for Panel I/O
import javax.swing.JOptionPane;
// declaration of the class
public class Vowel33
{
// declaration of main program
public static void main(String[] args)
{
// objects used to store data
String input_string = null;
int a_count = 0;
int e_count = 0;
int i_count = 0;
int o_count = 0;
int u_count = 0;
int i = 0;
int yes = 0;
// 1. display a descriptive message
String display_message = "This program asks the user for a sentence,\n"
+ "searches the sentence for all vowels,\n"
+ "and displays the number of times each"
+ "vowel appears in the sentence";
JOptionPane.showMessageDialog(null, display_message, "Lab 3 Description", JOptionPane.INFORMATION_MESSAGE);
// 4. visit each String posotion
do{
// 3. input the character string
input_string = JOptionPane.showInputDialog("Enter the sentence to search");
// 5. if position i of String is a vowel
// 6. increase the appropriate vowel counter
if (input_string.charAt(i) == 'a' || input_string.charAt(i) == 'A')
a_count++;
else if (input_string.charAt(i) == 'e' || input_string.charAt(i) == 'E')
e_count++;
else if (input_string.charAt(i) == 'i' || input_string.charAt(i) == 'I')
i_count++;
else if (input_string.charAt(i) == 'o' || input_string.charAt(i) == 'O')
o_count++;
else if (input_string.charAt(i) == 'u' || input_string.charAt(i) == 'U')
u_count++;
i++;
String display_message1 = input_string // 7. display the String
+ "\n\n" + "has " + input_string.length() + " characters.\n\n" // 8. display the number of characters
+ "There are \n"
+ a_count + " a's,\n" // 9. disaply the number of each vowel
+ e_count + " e's,\n"
+ i_count + " i's,\n"
+ o_count + " o's, and\n"
+ u_count + " u's.\n\n";
JOptionPane.showMessageDialog(null, display_message1, "Lab 3 Description", JOptionPane.INFORMATION_MESSAGE);
yes = JOptionPane.showConfirmDialog(null, "Would you like to enter another string?\n\n", "Extra Credit", JOptionPane.YES_NO_OPTION);
} while (i < input_string.length());
if (i == input_string.length())
{
yes = JOptionPane.showConfirmDialog(null, "Would you like to enter another string?\n\n", "Extra Credit", JOptionPane.YES_NO_OPTION);
if (yes == 1)
{
input_string = JOptionPane.showInputDialog("Enter the sentence to search");
}
}
} // end of main
} // end of the class
In your code you have a condition where the loop can still be executed if yes is 0. Since yes is never redefined from what I can see, you basically have an infinite loop and your code will error out when i exits the bounds of your string's length.
Also not sure why you have two JOptionPanes at the bottom of the loop (which would execute x times where x = input_string.length())
Consider something like:
if(i == input_string.length()) {
//ask the user if they want to enter another string
if(the user selected yes){
yes = 1;
//instantiate again with new input_string
}
}
Another note: Assuming you want to show a message asking if the user wants to enter another string once you've finished iterating through their first entry, it seems moot to have the yes variable and condition.

Categories