How do you include an applet in a Java application? - java

So for my computer science class we have to make a gpa calculator and include an applet in the same program to display the full name of the student and their GPA. I have the program working
import java.util.*;
import java.text.DecimalFormat;
import javax.swing.JApplet;
import java.awt.*;
public class Project1_Michael_Micool extends JApplet
{
public static void main(String[]args)
{
String first_name, last_name, course1, course2, course3, course4;
//Sets all the needed variables to string values for first, last and course names
int cred_course1, cred_course2, cred_course3, cred_course4, total_credits;
//Sets all the course credits as int values
float grade_course1, grade_course2, grade_course3, grade_course4, grade_point1, grade_point2, grade_point3, grade_point4, total_grades_added, gpa;
Scanner scan = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat("0.##");
System.out.println("Welcome to the UNG GPA calculator.");
System.out.println();
System.out.println("Please enter your first name");
first_name = scan.next(); //Assigns the entered name as first_name
System.out.println("Please enter your last name");
last_name = scan.next(); //Assigns the entered name as last_name
System.out.println();
System.out.println("A: 4.0 A-:3.67 ");
System.out.println("B+:3.33 B:3.00 B-:2.67");
System.out.println("C+: 2.33 C:2.00 C-:1.67");
System.out.println("D+: 1.33 D:1.00 F:0.00");
System.out.println();
System.out.println("Please enter your first course name and number. EX: PSYC1101");
course1 = scan.next();
System.out.println("Please enter the number of credits for course 1.");
cred_course1 = scan.nextInt();
System.out.println("Please enter your grade for course 1 using the chart. EX: B+= 3.33");
grade_course1 = scan.nextFloat();
System.out.println();
System.out.println();
System.out.println("Please enter your second course name and number. EX: PSYC1101");
course2 = scan.next();
System.out.println("Please enter the number of credits for course 2.");
cred_course2 = scan.nextInt();
System.out.println("Please enter your grade for course 2 using the chart. EX: B+= 3.33");
grade_course2 = scan.nextFloat();
System.out.println();
System.out.println();
System.out.println("Please enter your third course name and number. EX: PSYC1101");
course3 = scan.next();
System.out.println("Please enter the number of credits for course 3.");
cred_course3 = scan.nextInt();
System.out.println("Please enter your grade for course 3 using the chart. EX: B+= 3.33");
grade_course3 = scan.nextFloat();
System.out.println();
System.out.println();
System.out.println("Please enter your fourth course name and number. EX: PSYC1101");
course4 = scan.next();
System.out.println("Please enter the number of credits for course 4.");
cred_course4 = scan.nextInt();
System.out.println("Please enter your grade for course 4 using the chart. EX: B+= 3.33");
grade_course4 = scan.nextFloat();
total_credits = cred_course1 + cred_course2 + cred_course3 + cred_course4;
grade_point1 = grade_course1 * cred_course1;
grade_point2 = grade_course2 * cred_course2;
grade_point3 = grade_course3 * cred_course3;
grade_point4 = grade_course4 * cred_course4;
total_grades_added = grade_point1 + grade_point2 + grade_point3 + grade_point4;
gpa = total_grades_added / total_credits;
gpa = Math.abs(gpa);
course1 = course1.toUpperCase();
course2 = course2.toUpperCase();
course3 = course3.toUpperCase();
course4 = course4.toUpperCase();
System.out.println("Your name is " + first_name + " " + last_name);
System.out.println("You are taking " + course1 + " which is worth " + cred_course1 + " credit hours");
System.out.println("You are taking " + course2 + " which is worth " + cred_course2 + " credit hours");
System.out.println("You are taking " + course3 + " which is worth " + cred_course3 + " credit hours");
System.out.println("You are taking " + course4 + " which is worth " + cred_course4 + " credit hours");
System.out.println("Your total credit hours is " + total_credits);
System.out.println("Your GPA is " + fmt.format(gpa));
}
}
Here is the applet that I think should work.
public void paint(Graphics page)
{
page.drawString(first_name + " " + last_name, 110, 70);
page.drawString(gmt.format(gpa), 130, 100);
}
So my question is, how to you incorporate the applet into the program?

What you posted is not an "Applet"; it's just the paint method of something that might be an AWT widget (e.g. an applet). Just use that method in a widget that you integrate into your UI.

An Applet (or JApplet) would not typically have a main(String[]) unless it is an hybrid application/applet (where the application is based around a Frame or JFrame), but that main method is focused on the command line.
There is no practical way to use the command line code in either an applet or an application. It needs to be rewritten to use a GUI.
..for my computer science class..
Please refer the instructor to Why CS teachers should stop teaching Java applets.

Related

Have tried to fix this so many times I don't know where I'm going wrong

I am very new to java and am trying to learn how to program it while working remotely which is very difficult for me. The assignment is to create an "ingredient" class that will ask for ingredients, validate the input, and then at the end print a list of ingredients. I have written and re-written this code about a dozen times and it never prints out correctly. It takes one too many loops through to get a correct output, and when the values stored in the variables during the execution print out incorrectly. This group is my last ditch effort as I am struggling so hard even though I'm putting in the work! Thanks again and take care.
package Stepping_Stones_Lab_2;
import java.util.Scanner;
import java.util.ArrayList;
public class MilestoneOne {
/**
*
*/
public static void main(String[] args) {
ArrayList<String> ingredientList = new ArrayList();
ArrayList<String> recipeList = new ArrayList();
//variable declaration
double ingredientAmount = 0.0;
double totalCalories = 0.0;
int numberCaloriesPerUnit = 0;
String recipeName;
String nameOfIngredient;
String unitMeasurement;
Scanner scnr = new Scanner(System.in);
boolean addMoreIngredients = true;
//recipie creation
System.out.print("Please enter your new recipe name: ");
recipeName = scnr.nextLine();
recipeList.add(recipeName);
//This do-while loop is requesting ingredients until such time the user terminates the requests by typing n. If neither y or n is
//used the program will return an Invalid value error
do {
System.out.print("Would you like to enter an ingredient: (y or n): ");
String reply = scnr.next().toLowerCase();
scnr.nextLine();
//the notes says use a switch but I have not been able to get a switch to work successfully despite many tries.
if(reply.equals("y")) {
System.out.print("Enter ingredient name: ");
nameOfIngredient = scnr.nextLine();
while (!nameOfIngredient.matches("[a-zA-Z_]+")){ //Validates input and loops until there is acceptable input for name
System.out.print("Error: Please enter valid name of ingredient: ");
nameOfIngredient = scnr.next();
}
ingredientList.add(nameOfIngredient);
System.out.println("Good job! The ingredient you entered is " + nameOfIngredient);
//Unit of measurement input and data validation
System.out.print("Please enter the unit of measurement (cups, ounces, etc.): ");
unitMeasurement = scnr.next();
while (!unitMeasurement.matches("[a-zA-Z_]+")){ //Validates input and loops until there is acceptable input for unit measurement
System.out.print("Error: Please enter valid unit of measurement: ");
unitMeasurement = scnr.next();
}
System.out.println("Good job! The unit of measurement for " + nameOfIngredient + " is " + unitMeasurement);
//Amount of ingredient input and data validation
System.out.print("Please enter the number of " + unitMeasurement + " of " + nameOfIngredient + " we'll need: ");
while (!scnr.hasNextDouble()){//Validates input and loops until there is acceptable input for amount
System.out.print("Error: Please enter the number of " + unitMeasurement + " of " + nameOfIngredient + " we'll need using numbers only: ");
scnr.next();
}
ingredientAmount = scnr.nextDouble();
System.out.println("Good job! The number of " + unitMeasurement + " of " + nameOfIngredient + " needs is " + ingredientAmount);
//Number of calories per cup of ingredient input and data validation
System.out.print("Please enter the number of calories per " + unitMeasurement + " of " + nameOfIngredient + ": ");
while (!scnr.hasNextInt()){
System.out.print("Please enter the number of calories per " + unitMeasurement + " of " + nameOfIngredient + " using numbers only: ");
scnr.next();
}
numberCaloriesPerUnit = scnr.nextInt();
System.out.println("Good job! The number of calories per " + unitMeasurement + " of " + nameOfIngredient + " is " + numberCaloriesPerUnit);
totalCalories = ingredientAmount * numberCaloriesPerUnit;
System.out.println(recipeName + " uses " + ingredientAmount + " " + unitMeasurement + " and has " + totalCalories + " calories.");
}
else if(reply.equals("n")){
addMoreIngredients = false;
System.out.println("Your ingredients for " + recipeName + " are as follows: ");
}
else {
System.out.println("Invalid value!!");
}
}
while (addMoreIngredients);
for (int i = 0; i < ingredientList.size(); i++) {
String ingredient = ingredientList.get(i);
System.out.println(ingredient);
}
}
}
It works for me. Look at the following transcript.
Please enter your new recipe name: recipe name
Would you like to enter an ingredient: (y or n): y
Enter ingredient name: a
Good job! The ingredient you entered is a
Please enter the unit of measurement (cups, ounces, etc.): b
Good job! The unit of measurement for a is b
Please enter the number of b of a we'll need: 2
Good job! The number of b of a needs is 2.0
Please enter the number of calories per b of a: 3
Good job! The number of calories per b of a is 3
recipe name uses 2.0 b and has 6.0 calories.
Would you like to enter an ingredient: (y or n): y
Enter ingredient name: a2
Error: Please enter valid name of ingredient: aa
Good job! The ingredient you entered is aa
Please enter the unit of measurement (cups, ounces, etc.): bb
Good job! The unit of measurement for aa is bb
Please enter the number of bb of aa we'll need: 4
Good job! The number of bb of aa needs is 4.0
Please enter the number of calories per bb of aa: 8
Good job! The number of calories per bb of aa is 8
recipe name uses 4.0 bb and has 32.0 calories.
Would you like to enter an ingredient: (y or n): n
Your ingredients for recipe name are as follows:
a
aa

How do I properly format by output variables so that they align with their title? For example Last name, first name in users, etc

Here's my code, it's at the bottom that I don't know what to do to format it properly, I tried using printf but it keeps giving me errors whenever I try to reformat it and it doesn't want to go through, does anyone have any suggestions as to how to get the users' first and last name under "users", their balance under "balance and etc?
package mybalances;
import java.util.Scanner;
import static oracle.jrockit.jfr.events.Bits.doubleValue;
/**
*
* #author carroyo108
*/
public class MyBalances {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//first user
System.out.print("Enter user 1 first name:");
String firstFirst = keyboard.nextLine();
System.out.print("Enter user 1 last name: ");
String firstLast = keyboard.nextLine();
System.out.print("User 1, Account 1 Name: ");
String firstaccountOne = keyboard.nextLine();
System.out.print("User 1, Account 1 Balance: ");
double firstbalanceOne = keyboard.nextDouble();
System.out.print("User 1, Account 2 Name: ");
String firstaccountTwo = keyboard.nextLine();
keyboard.nextLine();
System.out.print("User 1, Account 2 Balance: ");
double firstbalanceTwo = keyboard.nextDouble();
keyboard.nextLine();
System.out.print("\n");
System.out.print("User 2 First Name: ");
String secondFirst = keyboard.nextLine();
System.out.print("User 2 Last Name: ");
String secondLast = keyboard.nextLine();
System.out.print("User 2, Account 1 Name: ");
String secondaccountOne = keyboard.nextLine();
System.out.print("User 2 Account 1 Balance: ");
double secondbalanceOne = keyboard.nextDouble();
System.out.print("User 2, Account 2 Name: ");
String secondaccountTwo = keyboard.nextLine();
keyboard.nextLine();
System.out.print("User 2, Account 2 Balance: ");
double secondbalanceTwo = keyboard.nextDouble();
System.out.print("\n");
//Third user inputs
System.out.print("User 3 First Name: ");
String thirdFirst = keyboard.nextLine();
keyboard.nextLine();
System.out.print("User 3 Last Name: ");
String thirdLast = keyboard.nextLine();
System.out.print("User 3, Account 1 Name: ");
String thirdaccountOne = keyboard.nextLine();
System.out.print("User 3, Account 1 Balance: ");
double thirdbalanceOne = keyboard.nextDouble();
System.out.print("User 3, Account 2 Name: ");
String thirdaccountTwo = keyboard.nextLine();
keyboard.nextLine();
System.out.print("User 3, Account 2 Balance: ");
double thirdbalanceTwo = keyboard.nextDouble();
keyboard.nextLine();
System.out.print("\n");
double firstusertotalCost = ((firstbalanceOne + firstbalanceTwo) / 2);
double secondusertotalCost = ((secondbalanceTwo + secondbalanceTwo) / 2);
double thirdusertotalCost = ((thirdbalanceTwo + thirdbalanceTwo) / 2);
System.out.printf("Users" + " " + "Account" + " " + "Balance" + " " + "Account" + " " + "Balance" + " " + "Average" + " " + "Status\n");
System.out.printf(("%5d",10) + firstLast,firstFirst);
}
}
You can use string concatenation by overloading the '+' operator
System.out.print("Users" + firstFirst + " " + firstLast + " Account " + firstaccountOne);
Your code shows very poor practices as there is a lot of repeating code. I would suggest using a loop condition (while/for loop) and try store your inputs from the user in a data structure like an array.

Parsing a string to boolean in java

I have the following simple sales program and am having trouble creating a restart loop around the program. My primary issue is converting the boolean from a string to a boolean type, I am getting an error in Eclipse that says, "The method parseBoolean(String) is undefined for the type Boolean".
However, I have defined a boolean variable at the top, boolean tryAgain = false;
and for some reason I cannot set the user input scanner to take the True or False value without an error. The error is occurring with the last line when I try to cast the nextLine from the user to boolean.
import java.util.Scanner;
public class Sales {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user input
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
while (tryAgain) {
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (True or False)");
tryAgain = Boolean.parseBoolean(userInput.nextLine());
}
}
}
The reason it gives you trouble is that when the user enters a double then hits enter, two things have just been entered - the double and a "newline" which is \n.
The method you are calling, "nextDouble()", only reads in the double, which leaves the newline in the input stream. But calling nextLine() does read in newlines, which is why you have to call nextLine() before your code would work.
Add this line before last line .
userInput.nextLine();
Well, I couldn't get it to work with a boolean for some reason, so I changed to a do while loop. Here is the final code. Also I did use the tip for clearing out the nextLine().
import java.util.Scanner;
public class Sales2 {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user inputjea
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
String answer; //Define var type of String for do while loop to restart program
do { //Do this loop while string == (last line of code while loop)
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (yes or no)"); //Prompt user for restart
userInput.nextLine(); //Clear scanner
answer = userInput.nextLine();
}
while (answer.equalsIgnoreCase("Yes")); //Connected to do while loop
//
}
}
Scanner supports nextBoolean(). Just use it:
tryAgain = userInput.nextBoolean()

Code is skipping the next required user-input scanner prompt, also how can I format the output outside of the class I'm in?

I apologize if my question is confusing, I'll try to explain it better here.
I'm creating a Property Calculator where the user is required to enter the Rooms of the residence, the area of each room, and then the price. Which ultimately gets calculated (total area from each room * price).
I'm not too familiar with Java so I'm not sure why I'm unable to use the variable declared in the class, outside.
Here is the code, followed by the issue that is happening:
EDIT
package realestatepropvalue;
import java.util.Scanner;
public class RealEstateProbValueA3
{
public static void main(String[] args)
{
Scanner sc = new Scanner ( System.in );
System.out.println ( "Hello friend, you will enter a series "
+ "of fields that'll calculate your Real Estate Property Value.");
System.out.print ("Please enter a Street Number ");
String streetnum = sc.next();
sc.nextLine();
System.out.println ("You entered the Street Number, " +streetnum );
System.out.print ( "Please enter a Street Name ");
String streetnam = sc.nextLine();
System.out.println ("You entered the Street Name, " + streetnam + " " );
END EDIT
System.out.print ("Please enter the number of rooms! (Up to 5!) ");
int roomcount = sc.nextInt();
String[] places = new String[roomcount];
for(int i = 0; i < places.length; i++) {
places[i] = "Place Number: " + i;
}
sc.nextLine();
System.out.println("You said that there were " + roomcount + " rooms!");
System.out.print ("Please enter the types of rooms (up to " +roomcount+ ") that fill up the " + roomcount + " rooms!\n"
+ "(Rooms like Living, Dining, Bedroom1-2, Kitchen, Bathroom, etc!) \n ") ;
int squareCounter = 0;
String[] types = new String[roomcount];
for(int i = 1; i < types.length; i++) {
System.out.print ("Please enter the types of room " + places[i] + ": ");
String roomName = sc.nextLine();
types[i] = roomName;
System.out.print ("Please enter the square feet of " + roomName + ": ");
int squareFeet = sc.nextInt();
squareCounter = squareFeet + squareCounter;
System.out.println("Room name: " + roomName + " is: " + squareFeet + "square feet.");
System.out.println("The counter total: " + squareCounter );
System.out.println("What is the price per sq. feet?");
int pricePer = sc.nextInt();
int finalCalc = pricePer * squareCounter;
System.out.println( "Estimated Property value: $____" + finalCalc);
}
Here is the log:
LOG EDIT
run:
Hello friend, you will enter a series of fields that'll calculate your Real
Estate Property Value.
Please enter a Street Number 7
You entered the Street Number, 7
Please enter a Street Name Washington Street
You entered the Street Name, Washington Street
END EDIT
Please enter the number of rooms! (Up to 5!) 3
You said that there were 3 rooms!
Please enter the types of rooms (up to 3) that fill up the 3 rooms!
(Rooms like Living, Dining, Bedroom1-2, Kitchen, Bathroom, etc!)
Please enter the types of room Place Number: 1: Kitchen
Please enter the square feet of Kitchen: 50
Room name: Kitchen is: 50square feet.
The counter total: 50
What is the price per sq. feet?
50
Estimated Property value: $____2500
Please enter the types of room Place Number: 2: Please enter the square feet of :
The last line immediately skips the type of room, and asks the square feet. Why does this happen?
Thank you for any help!

Java do while look proper coding?

Merged with Java do while look proper coding return value?.
I am trying to return data from a freaky do while or the if statement loop and it will not return the items I set why?
// yesno to n for first loop through.
do {
System.out.println("Welcome Sales ID: " + salesID + " please enter the samsung TV sold: \n");
samsungProduct = scanValue.next();
System.out.println("Please enter your total TV sales amounts individually for today \n");
singleSale = scanValue.nextDouble();
totalSales = totalSales + singleSale;
totalItems = totalItems++;
System.out.println("Do you want to enter another sales total(Y/N): \n ");
yesNo = scanValue.next();
} while (!yesNo.equalsIgnoreCase("N"));
// get the items set inside of the do while loop.
// The system print out values are empty.
System.out.printf(salesID + " you entered a total of: " + totalItems + "With a total sales of $%15.2f" + totalSales);

Categories

Resources