I am pretty new to Java. I am doing a program that calculates an Income Tax summary based on one's marital status. My program works, aside from one problem: my input validation section for the marital status is not working properly. When I enter something other than s, S, m, M, c, and C, the program is supposed to perform input validation for that, but currently, when I enter something like x, it skips the gross income and exemptions, and spits out that tax rate, taxes owed, and taxable income are all 0.
EDIT: Sorry if that was confusing. Basically, if the user uses invalid input, and the user then enters something valid, I want to know how to make it go back to the beginning of the switch statement to determine the tax rate Any help would be appreciated!
import java.util.Scanner;
public class TaxPrep
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char maritalStatus;
double grossIncome = 0;
double numberOfExemptions = 0;
double taxRate = 0;
double taxableIncome = 0;
double taxesOwed = 0;
String anotherCustomer = "y";
System.out.print("_ _ _ _ _ ' S T A X P R E P A R E R\n\n");
do{
System.out.print("Are you (s)ingle, (m)arried, or (c)ohabiting?\n");
System.out.print("Enter s, m, or c ==> ");
maritalStatus = sc.next().charAt(0);
switch (maritalStatus)
{
case 's': case 'S':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 20;
break;
case 'm': case 'M':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 25;
break;
case 'c': case 'C': //tax rate for cohabiting depends on taxable income
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
if (taxableIncome <= 20_000)
{
taxRate = 10;
break;
}
else if (taxableIncome <= 50_000)
{
taxRate = 15;
break;
}
else
{
taxRate = 30;
break;
}
default: //if input for marital status is invalid
do{ //continues to ask for valid input until user inputs a valid marital status
System.out.print("\nInvalid entry.");
System.out.print("\nAre you (s)ingle, (m)arried, or (c)ohabiting?");
System.out.print("\nEnter s, m, or c ==> ");
maritalStatus = sc.next().charAt(0);
} while (maritalStatus != 's' && maritalStatus != 'S' && maritalStatus != 'm' && maritalStatus != 'M' && maritalStatus != 'c' && maritalStatus != 'C');
}
taxesOwed = taxableIncome * (taxRate / 100);
//taxable income and taxes owed cannot be negative
if (taxableIncome < 0)
{
taxableIncome = 0;
}
if (taxesOwed < 0)
{
taxesOwed = 0;
}
//tax summary
System.out.print("\nINCOME TAX SUMMARY");
System.out.print("\ntax rate: " + taxRate + "%");
System.out.print("\ntaxable income: $" + taxableIncome);
System.out.print("\ntaxes owed: $" + taxesOwed);
//would you like to process another customer?
System.out.print("\n\nProcess another customer? (y/n): ");
anotherCustomer = sc.next();
System.out.print("\n");
} while (anotherCustomer.equalsIgnoreCase("y")); //as long as user enters 'y' or 'Y', the program will continue to calculate the income tax summary
}
}
Instead of retrying after
default: //if input for marital status is invalid
do{ //continues to ask for valid input until user inputs a valid marital status
} while(...);
simply skip to the end of the outer loop:
default:
System.out.print("\nInvalid entry.");
continue;
You need to have the switch-Statement inside the do-while-loop you got in default in your example, like
boolean martialStatusValid = true
maritalStatus = sc.next().charAt(0);
do {
martialStatusValid = true;
switch (maritalStatus) {
//your cases here
default:
martialStatusValid = false;
//display some kind of error message ...
}
} while (! martialStatusValid)
That way, as long as the martialStatus is invalid the User will be prompted for new input and the switch will repeat.
One thing to note abound Launes "continue-solution: that will start the next iteration of the outer do-loop, so basically restart your Program. Might not be what you're after if you have more Sections with user input, f.e. if you want to ask for sex etc.
Related
I have a java project that is a Income tax calculator, and I am supposed to add a error message to it so that the program will not respond to a number that is 0 or less in the income prompt. I am just not sure where to put the prompt or what type of error message I need to accomplish this. Code:
import java.util.Scanner;
public class TaxCalculator {
static void calculate() {
// The tax rates for different types of customers.
final double RATE1 = 0.20;
final double RATE2 = 0.25;
final double RATE3 = 0.10;
final double RATE4 = 0.15;
final double RATE5 = 0.30;
final double RATE1_SINGLE_LIMIT = 1;
final double RATE2_MARRIED_LIMIT = 1;
final double RATE3_COHABITATING_LIMIT = 20000;
final double RATE4_COHABITATING_LIMIT = 50000;
double tax = 0;
Scanner in = new Scanner(System.in);
//Prompt for user to enter the customers income
System.out.print("Enter customer's income: ");
double income = in.nextDouble();
in.nextLine();
System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus = in.next();
in.nextLine();
// Where the taxes are calculated
if (maritalStatus.equals("s") && income > RATE1_SINGLE_LIMIT) {
tax = RATE1 * income;
} else if (maritalStatus.equals("m") && income > RATE2_MARRIED_LIMIT) {
tax = RATE2 * income;
} else if (maritalStatus.equals("c") && income <= RATE3_COHABITATING_LIMIT) {
tax = RATE3 * income;
} else if (maritalStatus.equals("c") && income <= RATE4_COHABITATING_LIMIT) {
tax = RATE4 * income;
} else {
tax = RATE5 * income;
}
System.out.print("Your income tax is: $" + tax);
}
// asks user if they would like to process another customer.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String newResponse = "";
do {
calculate();
System.out.println();
System.out.println("Process another response?. Please enter 'y' for yes, or 'n' for no: ");
newResponse = in.next();
in.nextLine();
} while (newResponse.equals("y"));
}
}
You could add the loops after printing appropriate prompts:
System.out.print("Enter customer's income: ");
double income;
while ((income = in.nextDouble()) <= 0) {
System.out.print("Income " + income + " is invalid. Please input correct income which must be greater than 0: ");
in.nextLine();
}
System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus;
while (!(maritalStatus = in.next()).matches("[smc]")) {
System.out.print("Marital status " + maritalStatus + " is invalid. Please input correct value: 's', 'm', or 'c': ");
in.nextLine();
}
Output:
Enter customer's income: -12
Income -12.0 is invalid. Please input correct income which must be greater than 0: -23
Income -23.0 is invalid. Please input correct income which must be greater than 0: 2300
Please enter 's' for single, 'm' for married, or 'c' for cohabitating: 1
Marital status 1 is invalid. Please input correct value: 's', 'm', or 'c': m
I have an application that acts as a gradebook. However, in the console log when I type in a grade there seems to be an error. I was hoping someone could fix this to where I am able to put in a grade percentage and the error does not pop up.enter code here
Below is what the error says:java.lang.NumberFormatException: For input string: "70%"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Gradebook.getScores(Gradebook.java:45)
at Gradebook.main(Gradebook.java:154)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Here is my code:
import java.util.Scanner;
public class Gradebook {
//getNumStudents takes a Scanner object as parameter
//the reader object lets us take user input
public static int getNumStudents(Scanner reader){
int numStudents = 0;
//we get the number of students
do{
System.out.print("Enter number of students: ");
numStudents = Integer.parseInt(reader.nextLine());
//we determine if the user input is valid
//it should be greater than 0
//because we don't want the number o students to be negative
//if it is not valid then we keep taking inputs
if(numStudents > 0){
break;
}else{
System.out.println("Please enter atleast 1 student.");
}
}while(true);
System.out.println("================================================================================================================================================");
//we return numStudents
return numStudents;
}
//getScores takes our Scanner object again and the number student as parameter this time
public static String[] getScores(Scanner reader, int numStudents){
//we create an array of string studInfo
//that will be returned containing the name, and scores of our students
String[] studInfo = new String[numStudents];
String name = "";
int quiz = 0;
int assign = 0;
int test1 = 0;
int test2 = 0;
//we use a for loop to keep taking student scores
for(int i = 0; i < numStudents; i++){
//enter name
System.out.print("Enter student "+(i+1)+" name: ");
name = reader.nextLine();
//enter quiz, assignment, test1 and test2 scores
//we also validate scores to not be negative
//and not out of bounds
do{
System.out.print("Enter Quiz Score (over 40): ");
quiz = Integer.parseInt(reader.nextLine());
if(quiz >= 0 && quiz <= 40){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Assignment Score (over 30): ");
assign = Integer.parseInt(reader.nextLine());
if(assign >= 0 && assign <= 30){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Midterm Test Score (over 55): ");
test1 = Integer.parseInt(reader.nextLine());
if(test1 >= 0 && test1 <= 55){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Final Test Score (over 65): ");
test2 = Integer.parseInt(reader.nextLine());
if(test2 >= 0 && test2 <= 65){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
//after we get the name and student's score
//we put it in a string
studInfo[i] = name+ " " +quiz+ " " +assign+ " " +test1+ " " +test2;
System.out.println();
}
//return the studInfo
return studInfo;
}
//our displayGrade takes String array as parameter
public static void displayGrade(String[] studInfo){
//this is our header for our formatted table
System.out.println("================================================================================================================================================");
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10s%-15s%s", "Name", "Quiz", "Assignment", "Midterm Test", "Final Test", "Average", "Letter Grade", "Status"));
System.out.println("================================================================================================================================================");
//we go through our array of string
for(int i = 0; i < studInfo.length; i++){
//the split method returns an array of strings
//that are split by a delimeter
String[] data = studInfo[i].split(" ");
//we sum up the scores
//but we have to parse it to double first
//to get the closest sum
double sum = ((Double.parseDouble(data[1]) / 40.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[2]) / 30.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[3]) / 55.0) * 100.0) * 0.3;
sum += ((Double.parseDouble(data[4]) / 65.0) * 100.0) * 0.4;
//after that we round the sum and convert it to int and put it in average
int average = (int) Math.round(sum);
char letterGrade = ' ';
//we get the letter grade using a nested if else
if(average>=0 && average<=59){
letterGrade = 'F';
}else if(average>=60 && average<=69){
letterGrade = 'D';
}else if(average>=70 && average<=79){
letterGrade = 'C';
}else if(average>=80 && average<=89){
letterGrade = 'B';
}else if(average>=90 && average<=100){
letterGrade = 'A';
}
String status = "";
//we determine the status of our student here
//using switch case
//if the leter grade is f then he fails
//if the case is D then he needs to go to remedial class
//otherwise they pass
switch(letterGrade){
case 'F':
status = "Fail";
break;
case 'D':
status = "Remedial";
break;
case 'A': case 'B': case 'C':
status = "Pass";
break;
}
//we displat student information
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10d%-15c%s", data[0], data[1], data[2], data[3], data[4], average, letterGrade, status));
}
System.out.println("================================================================================================================================================");
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
displayGrade(getScores(reader, getNumStudents(reader)));
}
}
Instead of nextLine() you can use next("[0-9]+%?") and then remove the optional % character:
public static int getNumStudents(Scanner reader) {
int numStudents = 0;
//we get the number of students
do {
System.out.print("Enter number of students: ");
// Read the number either with or without the % sign
String input = reader.next("[0-9]+%?");
if (input.endsWith("%")) {
// Remove the % sign if present
input = input.substring(0, input.length() - 1);
}
numStudents = Integer.parseInt(input);
// we determine if the user input is valid
// it should be greater than 0
// because we don't want the number o students to be negative
// if it is not valid then we keep taking inputs
if (numStudents > 0) {
break;
}
System.out.println("Please enter at least 1 student.");
} while (true);
System.out.println("================================================================================================================================================");
// we return numStudents
return numStudents;
}
I am sorry to post again so soon, but I ran into another error in my Tax program. My program is only supposed to work if someone enters only 's,' 'S,' 'm,' 'M,' 'c,' or 'C' for the marital status. When I entered anything that does not start with one of those letters, it prints Invalid Entry, like it is supposed to, but when I enter something that starts with an upper/lowercase s, m, or c, it proceeds as if I only entered that first letter. How do I make it so that the program only proceeds if you enter the one letter?
Thanks!!
Here is my code:
import java.util.Scanner;
public class TaxPrep
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char maritalStatus;
double grossIncome = 0;
double numberOfExemptions = 0;
double taxRate = 0;
double taxableIncome = 0;
double taxesOwed = 0;
String anotherCustomer = "y";
System.out.print("A A R O N ' S T A X P R E P A R E R\n\n");
do{
System.out.print("Are you (s)ingle, (m)arried, or (c)ohabiting?\n");
System.out.print("Enter s, m, or c ==> ");
maritalStatus = sc.next().charAt(0);
switch (maritalStatus)
{
case 's': case 'S':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 20;
break;
case 'm': case 'M':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 25;
break;
case 'c': case 'C': //tax rate for cohabiting depends on taxable income
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
if (taxableIncome <= 20_000)
{
taxRate = 10;
break;
}
else if (taxableIncome <= 50_000)
{
taxRate = 15;
break;
}
else
{
taxRate = 30;
break;
}
default: //if input for marital status is invalid
System.out.print("\nInvalid entry.\n");
continue;
}
taxesOwed = taxableIncome * (taxRate / 100);
//taxable income and taxes owed cannot be negative
if (taxableIncome < 0)
{
taxableIncome = 0;
}
if (taxesOwed < 0)
{
taxesOwed = 0;
}
//tax summary
System.out.print("\nINCOME TAX SUMMARY");
System.out.print("\ntax rate: " + taxRate + "%");
System.out.print("\ntaxable income: $" + taxableIncome);
System.out.print("\ntaxes owed: $" + taxesOwed);
//would you like to process another customer?
System.out.print("\n\nProcess another customer? (y/n): ");
anotherCustomer = sc.next();
System.out.print("\n");
} while (anotherCustomer.equalsIgnoreCase("y")); //as long as user enters 'y' or 'Y', the program will continue to calculate the income tax summary
}
}
You are testing only the first character, even if the entered word is longer:
maritalStatus = sc.next().charAt(0);
sc.next() returns a String, and charAt(0) returns just its first character. So if you entered "sFoo", maritalStatus would just be 's' and the "Foo" would be ignored.
You should get the whole entered String (and possibly convert it to upper case for easier comparison in the switch). The variable maritalStatus should be declared as String in this case:
maritalStatus = sc.next().toUpperCase();
switch (maritalStatus) {
case "S":
//...
}
Switch statement works with Strings, unless you are using Java 6 or older. In that case you would use:
maritalStatus = sc.next().toUpperCase();
if (maritalStatus.equals("S")) {
//...
} else if...
I am trying to create a while loop where the user has a total of three tries to enter a valid number. I'm not understanding how the system recognizes that 3 invalid attempts have been made before displaying the message.
Classes, variables, and scanner objects are made. After the three attempts, I want to say "No more tries". I already have the program written to use the user's input for quantity if its valid. This is just if they input three invalid attempts.
Updated code:
int quantity = 0;
// Get user's desired amount of lemonade cups
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
quantity = keyboard.nextInt(); // Store amount of cups wanted
int attempts = 0;
int maxAttempts = 3;
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
while (attempts < maxAttempts) {
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt(); }
else {
System.out.println("Subtotal: " + defaultFormat.format(subTotal));
System.out.println("Tax: " + defaultFormat.format(totalTax));
System.out.println("Total: " + defaultFormat.format(totalPrice));
}
attempts++;
if (attempts >= 3) {
System.out.print ("No lemonade for you");
break;
}
// Ask for user's payment method
Scanner method = new Scanner(System.in);
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
String payment = method.nextLine();
dxdy is correct about the braces required for making the while() loop function.
Once the while loop has ended (either quantity is between 1 and 20, or attempts > maxAttempts), you just need to have an if statement like the following:
if (attempts > maxAttempts) {
System.out.println("No more tries);
return -1; // or something else to break out of your code
}
and then continue on with the rest of your code working with the quantity variable.
You seem to be missing the opening and closing brackets for the loop. As it is, your code reads
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts)
System.out.println("That is an invalid amount, please try again");
// these below are not part of the loop
quantity = keyboard.nextInt();
attempts++;
Instead you should do
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts){
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt();
attempts++;
}
try this code:
//start with 1 since the user will attempt it at least one time.
int attempts = 1;
int maxAttempts = 3;
int quantity=0;
Scanner keyboard = new Scanner(System.in);
//LESS THAN OR EQUAL TO 3...
while(attempts<=maxAttempts){
System.out.print("Enter amount: ");
quantity = keyboard.nextInt();
//check if valid
if(quantity < 1 || quantity >= 20){
//check if it's 1st and 2nd trial.
if(attempts<maxAttempts){
System.out.println("That is an invalid amount, please try again");
}else{
//third trial and still invalid
System.out.print("No more tries");
}
}else{
//user entered a valid amount so let's break the loops.
System.out.println("The amount is valid. Value of amount: "+ quantity);
break;
}
//increment attempts
attempts++;
}
//never forget to close the scanner
keyboard.close();
}
}
Though I could have turned this into methods if it's allowed
EDIT: As you updated the question, so it was necessary to update the answer too. Here it is what you actually want.
public static void main(String[] args) {
// Get user's desired amount of lemonade cups
String name = "Jimmy Nguyen";
Scanner keyboard = new Scanner(System.in);
int quantity;// Store amount of cups wanted
int lemonadeCost = 4; // Suppose
int attempts = 0;
int maxAttempts = 3;
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
while (attempts < maxAttempts) {
quantity = keyboard.nextInt();
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again\n");
++attempts;
} else {
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
System.out.println("Subtotal: " + subTotal);
System.out.println("Tax: " + totalTax);
System.out.println("Total: " + totalPrice);
// Ask for user's payment method
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
keyboard.nextLine();
String payment = keyboard.nextLine();
break;
}
if (attempts >= 3) {
System.out.print("No lemonade for you");
break;
}
}
}
My program will calculate the area but I need to have each different shape in it's own method and I'm having difficulty understanding how to first separate them all into their own method and link them all together. Any help is much appreciated.
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "Please choose which area/volume to calculate: 1-Circle 2-Triangle 3-Cone 4-Cylinder 5-Sphere 6-Quit: ";
System.out.print(s);
System.out.println(" ");
int num = keyboard.nextInt();
if (num < 1 || num > 6){
System.out.print("Please choose a number between 1 and 6: ");
num = keyboard.nextInt();
}
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 2){
System.out.print("Please enter the base: ");
double b = keyboard.nextDouble();
double at;
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
at = .5 * b * h;
System.out.print("The area of the triangle is: " + at);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 3){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double v1;
v1 = (1/3) * 3.14 * r * r * h;
System.out.print("The volume of the cone is: " + v1);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 4){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double vc;
vc = 3.14 * r * r * h;
System.out.print("The volume of the cylinder is: " + vc);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 5){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double vs;
vs = (4/3) * 3.14 * r * r * r;
System.out.print("The volume of the sphere is: " + vs);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 6){
System.out.print("Thank you for using this program");
}
}
}
You can use switch..case
switch(num) {
case 1: calculateCircleArea();
break;
case 2: calculateTriangleArea();
break;
case 3: calculateConeVolume();
break;
case 4: calculateCylinderVolume();
break;
case 5: calculateSphereVolume();
break;
case 6: System.out.print("Thank you for using this program");
break;
default: System.out.print("Please choose a number between 1 and 6: ");
break;
}
You can create new private/public methods to do the calculations and seperate them.
Take this part
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
You can create a new method for the calculation like so
public static double getArea(double radius)
{
return 3.14*radius*radius;
}
Then, inside your if statement you can say
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = getArea(r);
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
you see in this case, you get a one-line method which isn't very usefull. But you can split off more extensive calculations as well, this is just as an example. In addition, instead of all the if-blocks, you can use a switch statement like the other answer shows you.