import java.util.Scanner;
I am trying to turn this into a GUI program, and what I kind of came up with gives me a lot of errors, so if anyone could help me figure that out, that would be great.
public class Problemtwo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the side: ");
double side = input.nextDouble();
double area = 3 * 1.73205 * side * side / 2;
System.out.println("The area " + area);
}
}
This is the GUI I tried to create
import java.swing.JOptionPane;
import java.lang.Math;
public class GUI_Problemtwo {
public static void main(String[] args) {
double side;
double area;
StringsideString = JOptionPane.showInputDialog("Enter the side: ");
return;
}
// Convert string to double
double side = Double.parseDouble(sideString);
double side = input.nextDouble();
// Compute the area
double area = 3 * 1.73205 * side * side / 2;
// Display results
String output = "The area is " + area;
}
I just know that I'm really doing something wrong. Also I have another GUI that I'm able to input into a dialog box, but I can't get it to pull up any output in a dialog box, it just looks like it doesn't even stop running...
import javax.swing.JOptionPane;
import java.io.*;
public class GUI_Account {
public static void main(String[] args)throws IOException {
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
double bal=0;
int month,i;
// Prompts user to enter a number of months
String MString = JOptionPane.showInputDialog("Enter number of months: ");
if (MString == null) {System.out.println("User prompt cancelled");
return;
}
month=Integer.parseInt(kb.readLine());
for(i=0;i<month;i++) {
bal=(bal+100)*1.00417;
}
// Convert string to double
double M =Double.parseDouble(MString);
// Display results in dialog box
String output = "The amount is " + bal; JOptionPane.showMessageDialog(null, output);
}
}
Related
This question already has answers here:
Scanner Exception Retry
(2 answers)
Closed 3 years ago.
So, I need help with this code. This code will make the user input a double value like double radius. and calculate the area and perimeter of the circle. But I need to check if the radius is correct or not like, if the radius is negative or not and if the user enters a char or a string with it. so if the user enters 34.5gd the code should output "Invalid entry, please try again" and use a loop to input the value again.
I can get the negative part and using JOptionPane I am to get a dialogue box saying "Invalid entry, please try again", but I am unable to check the input for a char or string.
This code is for the driver class
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class CircleValidationApp1
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
String line;
Scanner input = new Scanner (System.in);
System.out.println("Enter the radius");
Circle obj = new Circle();
NegativeDoubleException obj1 = new NegativeDoubleException();
line = input.next();
obj1.Checkradius(line);
if(obj1.Checkradius(line)==true)
{
System.out.println("valid input");
}
else
{
JOptionPane.showMessageDialog(frame, "Error, Please try again");
line = input.next();
}
input.close();
}
}
This class should handle the input and throw the exception.
import javax.swing.JFrame;
public class NegativeDoubleException
{
Double radius;
String line;
Boolean flag = radius instanceof Double;
Circle obj = new Circle();
JFrame frame = new JFrame();
public void getvalue(String r){
r=this.line;
}
public void setvalue(String r){
getvalue(r);
}
public Boolean Checkradius(String r){
Boolean flag = false;
try
{
radius = Double.parseDouble(line);
flag = true;
}catch( NumberFormatException e)
{
flag = false;
}
return flag;
}
}
it is very easy you will surround the code that wants from the user to enter a number
with try...catch statement
like this
try{
//the code that wants from the user to enter the radius
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Invalid entry, please try again");
}
and when any Exception happens it will give the invalid entry message and you can close the message and write a new raduis without crashing the program
first problem : you must make variable line double not String and in the setters and getters methods of radius you make the setter double and it must be void
and the getter must be double and in the getter you will writereturn radius
and you will do the following changes
public class Circle2 {
double radius;
double area ;
double perimeter;
public void setradius(double r)
{
this.radius=r;
}
public double getradius(){
return radius;
}
public void perimeter()
{
System.out.println(2*3.14*radius);
}
public void area(){
area = Math.PI*radius*radius;
System.out.println(area);
}
}
note : I use the pi method in the math class to get more accurate resultsMath.PI
second : I make some changes on your main class
public class mainc {
public static void main(String[] args) throws IOException {
double l;
Circle2 obj = new Circle2();
Scanner s;
s = new Scanner(System.in);
l = s.nextDouble();
obj.setradius(l);
obj.perimeter();
obj.area();
to make anexception if someone didnot enter a number you will surround all the code in the main by try and catch
you will do that
public class mainc {
public static void main(String[] args) throws IOException {
double l;
Circle2 obj = new Circle2();
Scanner s;
try{
s = new Scanner(System.in);
l = s.nextDouble();
obj.setradius(l);
obj.perimeter();
obj.area();
}catch(Exception e){
System.out.println(e);
System.out.println("enter a number");
s = new Scanner(System.in);
l = s.nextDouble();
}
}
}
we added the s = new Scanner(System.in); and the l = s.nextDouble(); again because if an exception happened it will continue doing there work and dont close
I'm starting to learn java and I have a trouble with one of my programme.
I'm trying to obtain the inductance of an antenna depending on the type of antenna enter by the user.
The problem is that I have the dialog box and I enter the input, but after that my code stop and it didn't do the loop. I have been looking over the web and I can't find why my input is not acceptable by the if statement.
This is part of my code:
import javax.swing.*;
//import javax.swing.JOptionPane;
public class Antenna_Inductance {
public static void main(String[] args) {
// first we will define all the variable use of the problem set
// for the lime antenna
double M;
int N1;
int N2;
double R1;
double R2;
// now we can start to programmed the main code
String Type= JOptionPane.showInputDialog("Type of Antenna");
// this is where the code stop and i don't know why
if (Type == "line") {
String input_rmin= JOptionPane.showInputDialog("Enter minimum distance for r");
double rmin = Double.parseDouble(input_rmin);
String input_rmax= JOptionPane.showInputDialog("Enter maximum distance for r");
double rmax = Double.parseDouble(input_rmax);
I = 0.01;
for (r=rmin; r==rmax ;r+=0.05) {
B_line = (mu*I)/(2*pi*r);
System.out.println("Inductance for line antenna =" + B_line);
}
So, i could really use some help on this one. Thank you and have a nice day
If i got your question right, this should be what you are looking for:
import javax.swing.*;
//import javax.swing.JOptionPane;
public class Antenna_Inductance {
public static void main(String[] args) {
// first we will define all the variable use of the problem set
// for the lime antenna
double M;
int N1;
int N2;
double R1;
double R2;
// now we can start to programmed the main code
String type = (String) JOptionPane.showInputDialog(new JFrame(),
"Enter Antenna or what ever:", "titleForJInputDialog" , JOptionPane.DEFAULT_OPTION);
// this is where the code stop and i don't know why
System.out.println("Input of JOptionPane: " + type);
if (type.equals("line")) {
System.out.println("Input of JOptionPane is the same like 'line'");
}
}
}
I created a module that's called within another module, and it looks something like this:
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere (itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
but, I'm getting the error of "illegal start of expression" with the line where I make the method header for the second module. It looks constructed correctly.
Complete code as follows:
//This program will find the area or volume of a circle or sphere, respectively.
import javax.swing.JOptionPane;
public class Java_Chapter_9
{
public static void main(String args[])
{
//Declarations
String itemShape; //type of shape
String runProgram; //user control
Double itemRadius; //radius of tem
Double finalAnswer; //calculation for final answer
//End Declarations
showGreeting (); //Call greeting module
runProgram = JOptionPane.showInputDialog("Please enter 'Y' to run the program, or 'N' to quit"); //giving user control
while (runProgram.equalsIgnoreCase("y")) //loop for continuous use
{
itemShape = getItemShape (); //calling itemShape module
itemRadius = getItemRadius (); //calling itemradius module
finalAnswer = calculateAnswer (itemRadius, itemShape); //calling the module for calculation with paramaters
runProgram = JOptionPane.showInputDialog("Enter 'Y' to input more, or 'N' to Quit");
}
showGoodbye ();
////////////////////////////////////////////////// starting modules
public static void showGreeting () //greeting module
{
System.out.println("Welcome to the program");
System.out.println("This program will show you the area or volume of a shape");
}
///////////////////////////////////////////////// seperating modules
public static String getItemShape ()
{
String typeOfShape;
typeOfShape = JOptionPane.showInputDialog("Please enter 'C' for a Circle, or 'S' for a Sphere"); //getting input for shape
return typeOfShape; //returning to method
}
////////////////////////////////////////////////// seperating modules
public static double getItemRadius ()
{
double radiusOfItem; //variable withing scope of module
String radiusOfItemInput;
radiusOfItemInput = JOptionPane.showInputDialog("Please enter the radius of the item in inches: ");
radiusOfItem = Double.parseDouble(radiusOfItemInput);
return radiusOfItem;
}
////////////////////////////////////////////////// seperating modules
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere(itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
}
public static void showGoodbye ()
{
System.out.println("Thank you for using the program. Goodbye.");
}
Specifically, I appear to be having problems in general calling the modules, but none of the text is overly clear and how to make a module fit within the main method, which is where I'm struggling.
There are a lot of errors in your code.
Remove the ; in function. ; is not needed for function.
public static double calculateAnswerSphere(double itemRadius); // remove ;
After showGoodBye() method is being called, you miss to add a close brackets.
You have a typo in this line
system.out.print
It should be System.out.print and so on...
I'm beginning to learn more about Java and I'm trying to code a Gratuity calculator that takes user Input, and shows how much a tip would be at %10 and %20 of the total. I'm getting a single "Cannot make a static reference to the non-static method" error that I can't resolve.
Gratuity class:
public class Gratuity{
//variables
private double total = 0;
private double grat1 = 0;
private double grat2 = 0;
public Gratuity(float value){
total = value;
}
start getters and setters
public double getTotal() {
return total;
}
//method to do the calculations
public void calcGrat(){
grat1 = total * .10;
grat2 = total * .20;
}
public double getGrat1(){
return grat1;
}
}
And the class with the main method:
import java.util.InputMismatchException;
import java.util.Scanner; //import package to use the scanner input function
//TestGrat main class contains method
public class TestGrat {
Scanner keyboard = new Scanner(System.in);
//method to prompt user for total, double is total
public void askForInput(){
try{
System.out.println("Enter the total amount of your bill");
total = keyboard.nextDouble();
}
catch(InputMismatchException e){
System.err.printf("Error, please try again. Program will now close");
System.exit(0);
}
}
public Scanner getKeyboard() {
return keyboard;
}
public void setKeyboard(Scanner keyboard) {
this.keyboard = keyboard;
}
//main method
public static void main(String[] args){
// asks for input in float form
float value = askForInput();
//Creating the gratCalc object and storing value as a float (total)
Gratuity gratCalc = new Gratuity(value);
// get the total value and set as float
float tot = (float)gratCalc.getTotal();
// converting the float value into string
System.out.println("You have entered: " + Float.toString(tot));
gratCalc.calcGrat(); //sets grat
// Displaying the options to user
System.out.println("Below are the tips for %10 as well as %20 ");
//getting the value and then displaying to user with toString
float getNum = (float) gratCalc.getGrat1();
float getNum1 = (float) gratCalc.getGrat2();
// using the value of getNum as float to put into toString
System.out.println( "For %10: " + Float.toString(getNum));
System.out.println(" For %20: " + Float.toString(getNum1));
}
}
Any help would be appreciated. Thanks!
askForInput() is inside your class TestGrat. However, in main() you are calling it directly, as if it was static. You probably meant:
TestGrat test = new TestGrat();
float value = test.askForInput();
askForInput() is also returning void, so you probably want to fix that too.
I need some help with a program for my programming class. It's a recursive program that takes a subtotal and a gratuity rate given by the user that outputs the full total and the gratuity cost. This is what I've got so far, and for some reason it just doesn't work:
import java.io.*;
import java.until.Scanner;
public class gratuity {
private double total;
private double subTotal;
private double gratRate;
private double newSubTotal;
private double newGratRate;
public static void main(String[] args) {
System.out.print("Enter the subtotal: ");
System.out.print("Enter the gratuity rate: ");
Scanner scan = new Scanner(System.in);
Scanner myScan = new Scanner(System.in);
double subtotal = scan.nextDouble();
double gratRate = myScan.nextDouble();
System.out.println("The Gratuity is: " + newSubtotal);
System.out.println("The Total is: " + Total);
}
public static double computeGratRate() {
double newGratRate = (gratRate/100);
return newGratRAte;
}
public static double computeNewSub() {
double newSubTotal - (subTotal * newGratRate);
return newSubTotal;
}
public static double computeTotal() {
double total = (newSubTotal + newGratRate);
return total;
}
}
If anyone would help me figure out how to fix it, I would be very grateful! Thank you!
A few things.
You are creating new variables called "subtotal" and "gratRate" in Main. These values override the member variables of the class.
Your problem won't compile anyway, because...
All your methods are static, which is OK, but these static methods are accessing non-static variables. Make all your member variables of this class static. (Or make everything outside of Main not static and then have "Main" be a stub to just create an instance of the gratuity class.
You need to import java.util.Scanner, not java.until.Scanner.
This line is a compiler error:
double newSubTotal - (subTotal * newGratRate);
I think you mean:
double newSubTotal = (subTotal * newGratRate);
That should be enough hints for now.... keep trying.
Did you mean:
import java.util.Scanner;
public class Gratuity {
private double subTotal;
private double gratRate;
public static void main(String[] args) {
Gratuity gratuity = new Gratuity();
System.out.print("Enter the subtotal: ");
Scanner scan = new Scanner(System.in);
gratuity.setSubTotal(scan.nextDouble());
System.out.print("Enter the gratuity rate: ");
Scanner myScan = new Scanner(System.in);
gratuity.setGratRate(myScan.nextDouble());
System.out.println("The new GratRate is: " + gratuity.getNewGratRate());
System.out.println("The New Sub is: " + gratuity.getNewSub());
System.out.println("The Total is: " + gratuity.getTotal());
}
public double getNewGratRate() {
return gratRate/100;
}
public double getNewSub() {
return getNewGratRate() * subTotal;
}
public double getTotal() {
return getNewSub() + getNewGratRate();
}
public double getSubTotal() {
return subTotal;
}
public void setSubTotal(double subTotal) {
this.subTotal = subTotal;
}
public double getGratRate() {
return gratRate;
}
public void setGratRate(double gratRate) {
this.gratRate = gratRate;
}
}