The Java code did not show the result that I want - java

I am new to Java and actually this code is to ask the user for 2 numbers for the conversion from inch to centimeter and vice versa. But when I built it, it said "error: cannot find symbol" and I still cannot figure it out although I kept checking the code. Below is my code:
import java.util.Scanner;
import java.util.DecimalFormat;
public class Practical2Q2 {
public Practical2Q2() {}
public static void inchToCentimeter(double a) {
System.out.println("Inches " + "Centimeters");
System.out.print("\n");
for (double i = 1.0; i <= a; i++) {
double cm = i * 2.54;
System.out.println(i + " " + df.format(cm));
}
}
public static void centimeterToInch(double b) {
System.out.print("\n");
System.out.println("Centimeters " + "Inches");
System.out.print("\n");
for (double i = 5.0; i <= b; i += 5) {
double inch = i / 2.54;
System.out.println(i + " " + df.format(inch));
}
}
public static void main(String args[]) {
Scanner newScanner = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Please enter 2 numbers :\n" + "Number a for the conversion from inch to centimeter,\n"
+ "while number b for the conversion from centimeter to inch");
System.out.println("Number a : ");
double c = newScanner.nextDouble();
System.out.println("Number b : ");
double d = newScanner.nextDouble();
inchToCentimeter(c);
centimeterToInch(d);
}
}
Could you please state the wrong part?

You've created DecimalFormat df in the main method, it means that you can't access to it outside the method. I'v edited your code and i've created the field DecimalFormat df outside the main method.
I also changed the for loop inside the centimetersToInch() method, now it prints out all the values like in the inchToCentimeters() method.
Here's the code:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
static DecimalFormat df;
public static void inchToCentimeter(double a)
{
System.out.println("Inches " + "Centimeters");
System.out.print("\n");
for (double i = 1.0; i <= a; i++)
{
double cm = i * 2.54;
System.out.println(i + " " + df.format(cm));
}
}
public static void centimeterToInch(double b)
{
System.out.print("\n");
System.out.println("Centimeters " + "Inches");
System.out.print("\n");
for (double i = 1.0; i <= b; i++)
{
double inch = i / 2.54;
System.out.println(i + " " + df.format(inch));
}
}
public static void main(String args[])
{
Scanner newScanner = new Scanner(System.in);
df = new DecimalFormat("0.00");
System.out.println("Please enter 2 numbers :\n" + "Number a for the conversion from inch to centimeter,\n"
+ "while number b for the conversion from centimeter to inch");
System.out.println("Number a : ");
double c = newScanner.nextDouble();
System.out.println("Number b : ");
double d = newScanner.nextDouble();
inchToCentimeter(c);
centimeterToInch(d);
}
}

Your variable df is local only to your main method. Methods inchToCentimeter and centimeterToInch are unaware of this variable. Either make it a global variable or pass it as arguements to these methods.

Your df variable is not in there. Add the following line in your code.
static DecimalFormat df = new DecimalFormat("0.00");
Declare df variable as instance variable.

Related

How do I fix this error: Result cannot be resolved to a variable

I typed up this java program calculating simple interest in Eclipse.
import java.util.Scanner;
public class PercentageCalculator
{
public static void main(String[] args)
{
double x = 0;
double y = 0;
Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the value of x: ");
x = scanner.nextDouble();
System.out.println("Enter the value of y: ");
y = scanner.nextDouble();
System.out.println();
System.out.println("Calculating percentage: (x % of y): ");
System.out.println(x + " % of" + y + "is " + result);
System.out.println();
}
}
But when I tried to run it, it gave me this message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
result cannot be resolved to a variable
at PercentageCalculator.main(PercentageCalculator.java:19)
What does this mean and how can I fix it?
Declare you result variable
double result = 0;
then calculate the percentage and assign it to your result variable.
result = your calculation;
then print it
System.out.println(x + " % of" + y + "is " + result);
Hope this will help :)
You have not declare the result variable
double result=0;

Formatting java text with void method

I have looked and cant find the information I am looking for. My code is functioning as I expect it to but I have one bit of code that I would like to improve.
The problem is that I can not call a void method within a print statement like this:
System.out.print("Water is a " + printTemp(temperature) + " at" + temperature + " degrees.";
printTemp(temperature is a void method so this won't work, as a result I found a work-around but it is not ideal:
System.out.print("\nWater is a ");
printTemp(temperature);
System.out.print(" at");
System.out.printf(" %.0f", temperature);
System.out.print(" degrees.\n");
here is the full code:
import java.util.Scanner;
public class printTemp {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the temperature: ");
Double temperature = input.nextDouble();
// takes the state of the water from the printTemp method and
// the temperature to return a formatted output to the user
System.out.print("\nWater is a ");
printTemp(temperature);
System.out.print(" at");
System.out.printf(" %.0f", temperature);
System.out.print(" degrees.\n");
}
public static void printTemp(double temperature) {
String returnMessage = "null" ;
if (temperature < 32 )
returnMessage = "solid";
else if (temperature > 212)
returnMessage = "gas";
else
returnMessage = "liquid";
System.out.printf(returnMessage);
}
}
This is for school thus there are conditions that must remain, printTemp MUST be a void method and the variable temp must remain a DOUBLE.
What about to put the following code snippet
...
System.out.print("Water is a " + returnMessage + " at" + temperature + " degrees.");
to the printTemp method as the last line? Then in the main outputs nothing and you just write:
...
printTemp(input.nextDouble());
Use a class variable to hold the Temperature String word and use the void method to set it.
public class PrintTemp {
private static String TempStr = "";
public static void main(String[]args) {
[...]
printTemp(temperature);
System.out.print("Water is a " + TempStr + " at" + temperature + " degrees.");
}
public static void printTemp(double temperature) {
if (temperature < 32 )
TempStr = "solid";
else if (temperature > 212)
TempStr = "gas";
else
TempStr = "liquid";
}
}
Sorry for the delay guys!
Here is the solution.
import java.util.Scanner;
public class printTemp {
public static void main(String[]args) {
//Read in the temperature from the user
Scanner input = new Scanner(System.in);
System.out.print("\nPlease enter the temperature: ");
//Call and insert the input into the printTemp method.
printTemp(input.nextDouble());
}
public static void printTemp(double temperature) {
//Decide whether the water is in a soild, liquid or gaseous sate.
String returnMessage = "null";
if (temperature < 32 )
returnMessage = "solid";
else if (temperature > 212)
returnMessage = "gas";
else
returnMessage = "liquid";
//Print to the user.
System.out.print("\nWater is a " + returnMessage);
System.out.printf(" at %.0f degrees.%n\n", temperature);
}
}
UPDATE
public class PrintTemp {
public static void main(String[] args) {
double temperature = 35;
StringBuilder returnMessage = new StringBuilder();
printTemp(temperature, returnMessage);
System.out.print("Water is a " + returnMessage + " at " + temperature + " degrees.");
}
public static void printTemp(double temperature, StringBuilder returnMessage) {
if (temperature < 32)
returnMessage.append("solid");
else if (temperature > 212)
returnMessage.append("gas");
else
returnMessage.append("liquid");
}
}
This is the easiest way to have printTemp modify the message without actually returning it and without using additional classes / beans.
But this does work only for objects (not primitive type) and amongst objects it does not work for Strings because in Java they are treated as a special case. (That is why I had to use a StringBuilder, StringBuffer would work too)

Numbers to an extreme (Java)

EDIT: HERE IS A SCREENSHOT OF THE OUTPUT
https://www.dropbox.com/s/93d09a627se3b1u/Screenshot%202015-09-16%2019.08.19.png?dl=0]
I was recently asked to make a program that can calculate and display...
1 / (1!) + 1 / (2!) + . . . 1 / (n!)
using the Scanner utility. I seem to be having a lot of trouble with this. the program itself works, but it somehow gives the same answer no matter what number I input. Here's what I have so far (And yes, it is purposely incomplete, I'm stumped).
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math.E);
}
public static void Math(Double E)
{
Double product = 1.0;
int x = 0;
while (E > 0)
{
product = product * E;
E--;
}
Can anyone give me a way to finish/solve this problem? Thanks a ton.
~Andrew
EDIT: This code works fine for just finding the extreme. I will work on a way to add the preceding components of the equation to this, but It's a bit tricky for me.
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math(n));
}
public static Double Math(Double E)
{
Double product = 1.0;
while (E > 0)
{
product *= E;
E--;
}
return product;
}
}
You are confused with too much Math.
You've got your method Math with a parameter E and the Java Math class with a constant E. You're mixing them up.
Try
public static double factorial(double v)
{
double product = 1.0;
while (v > 0)
{
product *= v;
v--;
}
return product;
}
Your code:
System.out.println("e = " + Math.E);
Math.E is a constant - it will always print the euler number hence your output.
To call the the method correctly it should be
System.out.println("e = " + math(e)"
Input 1 - Output 1
Input 2 - Output 1.5
Input 3 - Output 1.66666667
import java.util.Scanner;
class MyClass
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . + 1/(n!)\nWhat is the value of n?");
double n = input.nextDouble();
double solution = doMath(n);
System.out.println("e = " + solution);
}
public static double doMath(double n) {
double ret = 0;
// the number of terms we add
for (int i = 1; i <= n; i++) {
ret += calcFaculty(i);
}
return ret;
}
// calculate every single term
public static double calcFaculty(double d){
double calc = 1;
for (int i = 1; i <= d ; i++) {
calc = calc* 1/i;
}
return calc;
}
}
Hi Andrew the program always return the same number
e = 2.718281828459045
Because the line System.out.println("e = " + Math.E); is not calling the method Math but calling to the class java.lang.Math. I dont know if is this what you find dubious.

My Java program seems to get...stuck (?) at a point during execution. I'm baffled.

So, I'm trying to create a driver for my method. I apologize in advance, I know very little about what I'm talking about. What the program does, is it calculates sine, cosine, and the exponential function by means of taylor series for a number that the user inputs. The use of Math.pow and Math.fact were not allowed. My compiler isn't giving me any errors, and I'm all out of ideas at this point. In addition, the scanner doesn't seem to stop accepting input after I press enter. It continues to take numbers, but doesn't do anything else. It gives an exception when I type a letter. High possibility of ID10T error. I know that the output isn't well formatted yet, but that's because I haven't had a chance to see it yet. If someone could help me figure this out, I would be very greatful. Thanks in advance!
-An aspiring code monkey
Driver (Lab4.java)
/*
This program is being created to solve Lab 4.
*/
import java.util.*;
public class Lab4
{
public static void main(String[] args)
{
String again, more = "y";
while (more.toUpperCase().charAt(0) == 'Y')
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Input X: ");
Function number = new Function();
double x = number.x();
System.out.println("x = " + x);
Function sine = new Function();
double mySin = sine.funcSine();
Function cosine = new Function();
double myCos = cosine.funcCos();
Function expo = new Function();
double myExp = expo.funcExp();
System.out.println("\t\t\t\tLibraryResult My Result");
System.out.println("\n\t\tsin(" + Function.x() + ")" + " = " + "\t\t\t" + Math.sin(Function.x()) + "\t" + mySin);
System.out.println("\n\t\tcos(" + Function.x() + ")" + " = " + "\t\t\t" + Math.cos(Function.x()) + "\t" + myCos);
System.out.println("\n\t\texp(" + Function.x() + ")" + " = " + "\t\t\t" + Math.exp(Function.x()) + "\t" + myExp);
System.out.println("\n\t\t\tDo more (Y/N) ? ");
more = keyboard.next();
String junk = keyboard.nextLine();
}
}
}
Method (Function.java)
/*
This class provides the information for the parent to use in order to solve Lab 4.
*/
import java.util.*;
public class Function
{
Scanner keyboard = new Scanner(System.in);
public static int number;
private double temp = 1;
private double last = 1;
public static double x()
{
Scanner keyboard = new Scanner(System.in);
double x = keyboard.nextDouble();
return x;
}
public static double pow(double value, double power)
{
if(power == 0)
{
return 1;
}
double result = value;
for(int i = 0; i < power -1; i++)
{
result = result * value;
}
return result;
}
public static double getFact()
{
while (number < 0)
{
number =(number * -1);
}
double factorial = 1;
if (0 == (number % 1))
{
do
{
factorial = factorial * number;
--number;
} while (number >= 1);
}
else //Stirling's Approximation
{
double e = 2.718281828459;
double part1 = Math.sqrt(2 * 3.141592653589 * number);
double part2a = (number / e);
double part2b = (pow(part2a,number));
factorial = (part1 * part2b);
}
return factorial;
}
public static double funcSine()
{
int place = 0;
double next = x()*1;
for(number = 3; number <= 30; number = number + 2)
{
next = next + ((pow((-1),place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double mySin = next * 1;
return mySin;
}
public static double funcCos()
{
int place = 0;
double next = 1;
for(number = 2; number <= 30; number = number + 2)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myCos = next * 1;
return myCos;
}
public static double funcExp()
{
int place = 0;
double next = 1 + x();
for(number = 1; number <= 30; number++)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myExp = next * 1;
return myExp;
}
}
Check the syntax of your while loop:
while (more.toUpperCase().charAt(0) == 'Y')
Think about when the program will ever not satisfy this expression.
Also you have multiple Scanners all over your code. ITs not clear why you need to keep reading inout over and over again.

BMI calculator errors

While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java

Categories

Resources