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'");
}
}
}
Related
This is my code right now:
import java.util.Scanner;
import java.util.*;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
public class IceCreamData
{
// method to calculation volume
public static void printCylinderVolume(double cylinderRadius, double cylinderHeight){
double cylinderVolume = Math.PI * Math.pow(cylinderRadius, 2) * cylinderHeight;
return cylinderVolume;
}
// method to calculate number of ice cream scoops
public static double printNumScoops(double cylinderVolume){
double numScoops = (cylinderVolume * 0.004329) * 30;
System.out.println("The number of scoops is " + cylinderVolume);
}
// the main method
public static double main(String[] args) throws FileNotFoundException, IOException
{
//input the file and scanner and output file
File input = new File("project4Data.txt");
Scanner in = new Scanner(input);
PrintWriter out = new PrintWriter("scoopResults.txt");
//declaring variables outside of while-loop in order to run
String iceName; // name of the ice cream
double cylinderRadius; // cylider radius
double cylinderHeight; // cylinder height
int expirationYear; // expiration year
// while-loop to determine number of scoops in a container of ice cream
while(in.hasNext())
{
iceName = in.next(); // ice cream name
cylinderRadius = in.nextDouble(); // radius of the cylinder
cylinderHeight = in.nextDouble(); // height of the cylinder
//while-loop
while(cylinderRadius > 0 && cylinderHeight > 0 && expirationYear <= 2018){
System.out.println(iceName);
printCylinderVolume(cylinderRadius, cylinderHeight);
printNumScoops(cylinderVolume);
}
}
}
}
I am trying to return the cylinder volume from the printCylinderVolume method to the main method, so that I can use it in the printNumScoops method. Right now I am getting an error saying that cylinderVolume is an unexpected return value, and another error saying that the printNumScoops method can't find cylinderVolume. Is cylinderVolume initialized/declared in the right places and does it need to be returned/stored in the main method differently to work?
Your method should return a double, not a void:
public static double printCylinderVolume(double cylinderRadius, double cylinderHeight) {
// Here --^
double cylinderVolume = Math.PI * Math.pow(cylinderRadius, 2) * cylinderHeight;
return cylinderVolume;
}
You may want to consider renaming the method, though, since it doesn't actually print anything, it just returns the calculation. calcCylinerVolume could be a more appropriate name.
You have incorrect way in creating a method. For example, in this following method:
public static void printCylinderVolume(double cylinderRadius, double cylinderHeight){
// ^
// the method need void return
double cylinderVolume = Math.PI * Math.pow(cylinderRadius, 2) * cylinderHeight;
return cylinderVolume;
// But, you're returning double
}
You're creating a method with void return. but at the end of the method you are returning a double.
And in the following code:
// the main method
public static double main(String[] args) throws FileNotFoundException, IOException {
...
}
If you're trying to create a main method, then the above code is incorrect. main method should return a void like this:
public static void main(String[] args) {
...
}
Please read more about Defining a method in https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
I am currently learning Java and following some online tutorials. One of the assignments is to compute the body age of a person by getting their various scores, getting the average of these scores and then applying a formula to it to get the total. I can do it with one big class, but the assignment then asks to go further and split everything into different classes. My program currently looks like this:
import java.util.Scanner;
public class fit2 {
public static void main(String[] args) {
int average, bodyAge;
average = average2();
System.out.println(average);
bodyAge = fitAge();
System.out.println(bodyAge);
}
public static int fs() {
int fs;
System.out.println("Enter first number: ");
Scanner bucky = new Scanner(System.in);
fs = bucky.nextInt();
return fs;
}
public static int ss() {
int ss;
System.out.println("Enter second number: ");
Scanner bucky = new Scanner(System.in);
ss = bucky.nextInt();
return ss;
}
public static int average2() {
int first, second, average;
first = fs();
second = ss();
average = (first + second) / 2;
return average;
}
public static int fitAge() {
int fitAge, average;
average = average2();
fitAge = average * 8 / 5 + 10;
return fitAge;
}
}
My idea was to have different methods for each part of the program - two methods to get the users scores and then pass these into a averageing method, which would then pass it into a final method which would apply the formula, then passing it back it into the Main class, which would print that age out as well as the Average age.
I read somewhere that you shouldnt get user input in classes but get it in main and pass it into the average class using parameters -- can anyone advise on this?
Thanks.
Try something like this (as suggested by my comment on the question):
import java.util.Scanner;
public class fit2 {
public static void main(String[] args) {
System.out.println("Enter first number: ");
Scanner bucky = new Scanner(System.in);
int fs = bucky.nextInt();
System.out.println("Enter second number: ");
bucky = new Scanner(System.in);
int ss = bucky.nextInt();
int average = average2(fs, ss);
int bodyAge = fitAge(average);
System.out.println(average);
System.out.println(bodyAge);
}
public static int average2(int first, int second) {
int average;
average = (first + second) / 2;
return average;
}
public static int fitAge(int average) {
int fitAge;
fitAge = average * 8 / 5 + 10;
return fitAge;
}
}
I believe I understand your question - you are unsure of where to place user input in your program.
In a small program like this, it may be wise to place user input in the main() method, solely because you gather user input, delegate input to methods that perform computation on the data that is "under the hood" of the program, and then return the value back to the user.
In your specific instance, this seems like a wise decision, as your program is small and a standard console-based application. This may not always be the case in the future, depending on the program you are writing.
Realistically, it doesn't matter all too much if it runs as intended, but for simplicity sake (remember KISS) putting user input in your main() method is probably a good idea.
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.
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);
}
}
I have created a simple class which calculates the win/loss percentage and returns the amount of necessary consecutive wins to obtain the desired win/loss percentage of the given input from the user, based on the given values of wins, loss, and desired win/loss. However, whilst running the program, I notice the output gives an exceedingly large number in the place of what should be a relatively small number (the number of wins needed). I am not certain what error I have made that created this, but I'm certain it's relative to the while loop located in my howManyToWinLoss() method, or perhaps some error I've made in the tester class's output. At any rate, they are both located below, and I appreciate the assistance:
public class WinLossCalculator
{
private int win;
private int loss;
private int totalGames;
private double desiredWinLoss;
private double winLoss;
private int gamesToDWL;
public WinLossCalculator(int w, int l, double dwl)
{
win = w;
loss = l;
totalGames = w + l;
desiredWinLoss = dwl;
}
public double winPercent()
{
return winLoss = (double)win/(double)totalGames;
}
public double lossPercent()
{
return (double)loss/(double)totalGames;
}
public int howManyToWinloss()
{
int x = 0;
while(winLoss < desiredWinLoss)
{
winLoss = (win+x)/(win+x+loss);
if(winLoss < desiredWinLoss)
{
x++;
}
}
return gamesToDWL = x;
}
}
and
import java.util.*;
public class WinLossTester
{
public static void main(String []args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the amount of matches you've won: ");
int wins = in.nextInt();
System.out.print("\nEnter the amount of matches you've lost: ");
int losses = in.nextInt();
System.out.print("\nEnter your desired match win percentage (eg. 75.4): ");
double desiredWLP = in.nextDouble();
System.out.println();
WinLossCalculator one = new WinLossCalculator(wins, losses, (desiredWLP / 100));
one.winPercent();
one.howManyToWinloss();
System.out.printf("Win percentage: %6.1f", (one.winPercent()*100));
System.out.print("%");
System.out.printf("\nLoss percentage: %5.1f", (one.lossPercent()*100));
System.out.print("%");
System.out.println("\nVictories required to reach desired W/L percent (without loss): " + one.howManyToWinloss());
}
}
Additionally--I feel as though my tester class's output section is a little ugly, might anyone have any suggestions concerning formatting or cleaning up the code in the output section?
Ok, apparently it has to do with me not casting the first line in my for loop to double like this winLoss = (double)(win+x)/(double)(win+x+loss); I don't know why that broke it, but, that's why it was broken.