Class, interface, or enum expected error - java

I have tried just about everything I can think of to fix my error but I;m completely stumped. I keep getting a "class, interface, or enum expected" error. What am I missing?
import java.until.*;
public class FutureValues {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Lab 3 written by JENNIFER ADAME");
System.out.println();
//declare variables
double p;
double r;
double y;
double f;
System.out.print("Enter present value: ");
double p = console.nextDouble( );
System.out.print("Enter interest rate: ");
double r = console.nextDouble( );
System.out.print("Enter number of years: ");
double y = console.nextDouble( );
double f = compoundInterest(p, r, y);
System.out.print("The future value is" + f);
}
public static double compoundInterest (double p, double r, double y) {
double f = p * Math.pow(((1 + r) / 100), y);
return f;
}
}
}
If anyone could help that would be awesome!

You are adding one extra brace '}' at the end...just remove it
If wanna keep safe from these kind of errors in future,consider formatting your code properly.(Use Ctrl+shift+f for eclipse and Alt+shift+f for netbeans)

There is a mismatched brace at the end of your file.

Related

Need help adding methods in main class

Hello I'm working on a project for my java class, I'm supposed to write a code for a Algebra tutor that goes like this:
Write a program with a that displays a randomly generated problem that asks the user to solve for the y variable, takes input from the user, and prints "correct" if the user answered correctly and prints "incorrect" if not. Your main should give one problem and then exit. Use one or more methods to produce this behavior.
This is regarding the formula mx + b. So here is what I have so far, and works!
import java.util.Random;
import java.lang.Math;
import java.util.Scanner;
class Main {
public static void main(String[] arg){
double min_value = -100;
double max_value = 100;
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int)m_value * (int)x_value + (int)b_value;
if (user_answer.equals(correct_answer))
System.out.println("You are correct!");
else
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
}
}
so even tho the output is correct, I need to break down the code into smaller methods, this is where Im getting confused on how to take a piece of that code and put it in another method that once it runs it calls for that method too and gives me the same output. I been ready the material given but the more I read it the more confuse I get. If anybody has any ideas or suggestions please let me know any info will be really appreciate. Thank you
Here's a quick rundown on methods, so it's not completely done yet. Ask, if you need more help! Good luck on your homework and on becoming one of the beast developers!
public class Main {
public static void main(String[] args) {
int a = 1; // give a value of 1
methodTwo(a); // sending the int a into another method
}
// Here's method number two
static void methodTwo (int a) { // it gives a's type and value
System.out.println(a); //Gives out a's value, which is 1
}
}
Technically you've solved the problem correctly, you are using one or more methods, but perhaps what you trying to do is a common code refactor called the extract method / extract function refactor Executing this type of refactor leads to much more readable and maintainable code, and is easy to do.
As a starter, identify code that repeats or looks similar, in your case, the following lines look ripe for extract method:
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
Notice that the RHS of each line is identicial, so we can replace the explicit code with a method call like this:
double m_value = getRandomDoubleBetween(max_value, min_value);
double x_value = getRandomDoubleBetween(max_value, min_value);
double b_value = getRandomDoubleBetween(max_value, min_value);
private double getRandomDoubleBetween(double max_value, double min_value) {
return (int)(Math.random()*((max_value-min_value)+1))+min_value;
}
You can identify other areas of code that either contain repetition or perhaps some hard to understand code that would be more understandable if it was extracted into a method that had a name that reveals what the code is doing.
Please review this, you are comparing string with integer,
if (user_answer.equals(correct_answer))
This may help you:
import java.util.Scanner;
class Main {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generateRandom(max_value, min_value);
double x_value = generateRandom(max_value, min_value);
double b_value = generateRandom(max_value, min_value);
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
checkAnswer(m_value, x_value, b_value);
}
private static void checkAnswer(double m_value, double x_value, double b_value) {
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int) m_value * (int) x_value + (int) b_value;
if (user_answer.equals(String.valueOf(correct_answer))) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
user_input.close();
}
}
static int generateRandom(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)
+ 1)) + min_value);
}
}

Java loop structure that iterates over strings and works with multiple variables

Today I am working on refactoring one of my old java exercises.
It is as simple addition program that asks a user to input some numbers, then returns the sum of all of the numbers entered.
package methodparametertest;
import java.util.Scanner;
public class MethodParameterTest {
public static double adds(double a, double b, double c, double d, double e,
double f, double g) {
double sum = a + b + c + d + e + f + g;
return sum;
}
public static double getDoubleInput(String valueWanted) {
Scanner input = new Scanner(System.in);
String askFor = valueWanted;
System.out.println("Please enter a positive integer or decimal value"
+ "for your numnber of "+askFor);
double valueGiven = input.nextDouble();
return valueGiven;
}
public static void main(String[] args) {
double a = getDoubleInput("passengers");
double b = getDoubleInput("odometer_miles");
double c = getDoubleInput("fuel_gallons");
double d = getDoubleInput("miles_per_gallon");
double e = getDoubleInput("seats");
double f = getDoubleInput("wheels");
double g = getDoubleInput("lights");
System.out.println("Your total number of things: " +adds(a,b,c,d,e,f,g));
}
}
In the past, most of my program's logic was in my main method. I have made it my goal today to have as few lines as
possible in main, and package as much logic as I can into separate methods.
I still have several lines in main that use my getDoubleInput method to set the values for the variables a through g (which will then be used as parameters for my "adds" method.
I would like to alter this block and use a loop. Perhaps something that would work like this:
#Shell-like pseudocode
For i in (a b c d e f g)
For j in ("passengers", "odometer miles", "fuel gallons", "miles_per_gallon", "seats", "wheels", "lights");
do
double $i = getDoubleInput($j);
done
//OUTPUT
// double a = getDoubleInput("passengers");
// double b = getDoubleInput("odometer miles");
// double c = getDoubleInput("fuel gallons");
// double d = getDoubleInput("miles_per_gallon");
// double e = getDoubleInput("seats");
// double f = getDoubleInput("wheels");
// double g = getDoubleInput("lights");
However, I cannot find an example of how to implement this in java. Most of the loops that I have seen only iterate over numericalvalues, not a defined set of strings.
Does anyone know of a loop structure that could A: iterate over strings, and B: work with two variables ?
Don't have an adds method; just use plain old addition. Put the titles in a list and iterate that:
double sum = 0;
for (String title : Arrays.asList("passengers", "odometer miles", ...)) {
sum += getDoubleInput(title);
}
System.out.println("Your total number of things: " + sum);
Try this:
String[] strArray = Arrasy.asList(new String[] {"passengers", "odometer miles", "fuel gallons", "miles_per_gallon", "seats", "wheels", "lights"});
List<Integer> list = new ArrayList<>();
for (String str: strArray) {
list.add(getDoubleInput(str));
}
System.out.println("Your total number of things: " +adds(list));
And then modify adds to accept lists.

How do I get the program statement arguments like heightm passed down to other methods?

import java.util.Scanner ;
public class CollinsHealthCalculator {
double ACTIVITY_FACTOR = 1.375;
public static void main (String[] args) {
newHealthCalcDescription ();
Scanner keyboard = new Scanner (System.in);
System.out.println ("What is your weight in pounds? ");
double weightlb = keyboard.nextDouble ();
System.out.println ("What is your height in inches? ");
double heightin = keyboard.nextDouble ();
System.out.println ("What is your age in years? ");
double ageYears = keyboard.nextDouble ();
double WEIGHT_KILOGRAMS = weightlb / 2.2;
double HEIGHT_METERS = heightin * .0254;
double weightkg = WEIGHT_KILOGRAMS;
double heightm = HEIGHT_METERS;
double computingBMI (BMI, weightkg, heightm);
maleBMR (heightm, weightkg, ageYears);
femaleBMR (heightm, weightkg, ageYears);
showResults (BMI, caloriesm, caloriesf);
public static newHealthCalcDescription () {
System.out.println("This calculator will determine your BMI "
+ "(Body Mass Index). While also it will determine the amount "
+ "of calories needed to maintain weight.");
}
//Computing the BMI
public static void computingBMI (double BMI, double weightkg, double heightm){
BMI = weightkg/(Math.pow(heightm, 2));
}
//Computing BMR for male and female
public static void maleBMR (double heightm, double weightkg, double ageYears) {
double HEIGHT_CENTIMETERS = heightm * 100;
double heightcm = HEIGHT_CENTIMETERS ;
double BMRForMales = 13.397 * weightkg + 4.799 * heightcm - 5.677 * ageYears + 88.362;
double caloriesm = Math.round(BMRForMales * 1.375);
}
public static void femaleBMR (double heightm, double weightkg, double ageYears) {
double HEIGHT_CENTIMETERS = heightm * 100;
double heightcm = HEIGHT_CENTIMETERS ;
double BMRForFemales = 9.247 * weightkg + 3.098 * heightcm - 4.330 * ageYears + 447.593;
double caloriesf = Math.round(BMRForFemales * 1.375);
}
public static void showResults (double BMI, double caloriesm, double caloriesf) {
//Show results
System.out.printf ("%nYour BMI is: %7.1f", BMI);
System.out.println ("A BMI between 18.5 to 24.9 is considered normal.");
System.out.println ();
System.out.println ("To maintain current weight:");
System.out.print ("Men need to eat " + caloriesm);
System.out.println (" calories per day.");
System.out.print ("Females need to eat " + caloriesf);
System.out.println (" calories per day.");
}
}
I'm trying to get the code to pass down statements but I'm new to programming and have no clue on how to go about getting method passed down to another method. I've tried researching everywhere but I've had little luck in finding any help. Please help so I can make my programm functional I'm excited to learn just need help.
You can try giving the variables the global scope(outside the method). You may learn about it here.
When you declare a variable inside a method (i.e. code block), it is local to that block. So you cannot use that variable in any other method. Here the best option for you to do is to declare the variable, i.e. like weightkg etc as class variables.
You can change the return type of the methods from void to double and store the returned result and send the results to other methods.
for eg.
public static double computingBMI (double BMI, double weightkg, double heightm){
return weightkg/(Math.pow(heightm, 2));
}

Cannot read the decimal point in Scanner

import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double pi = 3.142;
double T, v, a, x, r;
System.out.println("3.Centrifuge. The rotor of an ultracentrifuge rotates at x rev/s.");
System.out.println("A particle at the top of the test tube is r meter from the rotation axis.");
System.out.println("Calculate it’s centripetal acceleration.");
System.out.printf("Enter the number of rotation in rev/s : ");
x = input.nextInt();
System.out.printf("Enter the distance in meter : ");
r = input.nextInt();
T = 1/x;
v = (2*pi*r)/T;
a = (v*v)/r;
System.out.println("\n\nAnswer");
System.out.printf("The centripetal acceleration is : %.2f m/s^2\n", a);
}
}
Hi all. This is my coding and it cannot run when I put decimal point. how to fix it?
Replace input.nextInt(); with input.nextDouble();
x = input.nextInt(); // It will simply ignore decimal values
Hence you need to use nextDouble()
x = input.nextDouble(); // This will read the entire decimal value
You read a int with
input.nextInt();
Try
input.nextDouble();
Try it.
import java.util.Scanner;
public class JavaScannerDouble {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String data = input.next();
double decimalValue = Double.parseDouble(data);
System.out.println("Decimal value : " + decimalValue);
// test of decimal value
double response = decimalValue / 0.1;
System.out.println("response : " + response);
}
}

Taking in input for Calculator program

I want the program to accept operation signs (+, -, * ,/) as input. Whenever I do that it throws an exception. Can anybody help me fix this problem and make the program accept one of these signs as input.
import java.lang.*;
import java.util.*;
public class Calculator
{
private double solution;
private static double x, y;
private static char ops;
public static interface Calculate
{
public abstract double operation(double x, double y);
}
public static class addition implements Calculate
{
public double operation(double x, double y){
return(x+y);
}
}
public static class subtraction implements Calculate
{
public double operation(double x, double y){
return(x-y);
}
}
public static class multiplication implements Calculate
{
public double operation(double x, double y){
return(x*y);
}
}
public static class division implements Calculate
{
public double operation(double x, double y){
return(x/y);
}
}
public void calc(int ops){
Scanner operands = new Scanner(System.in);
System.out.println("operand 1: ");
x = operands.nextDouble();
System.out.println("operand 2: ");
y = operands.nextDouble();
System.out.println("Solution: ");
Calculate [] jumpTable = new Calculate[4];
jumpTable['+'] = new addition();
jumpTable['-'] = new subtraction();
jumpTable['*'] = new multiplication();
jumpTable['/'] = new division();
solution = jumpTable[ops].operation(x, y);
System.out.println(solution);
}
public static void main (String[] args)
{
System.out.println("What operation? ('+', '-', '*', '/')");
System.out.println(" Enter 0 for Addition");
System.out.println(" Enter 1 for Subtraction");
System.out.println(" Enter 2 for Multiplication");
System.out.println(" Enter 3 for Division");
Scanner operation = new Scanner(System.in);
ops = operation.next().charAt(0);
Calculator calc = new Calculator();
calc.calc(ops);
}
}
The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 43
at Calculator.calc(Calculator.java:54)
at Calculator.main(Calculator.java:76)
jumpTable['+']
will be translated to the ASCII code (43) of the + sign (it's converted to a char), leaving you with a number out of the 0-4 range. You probably want to use actual numeric indices (or make sure your array can contain the highest numerical representation for your set of char values, in this case 47 by /).
ASCII table:
You can only reference jumpTable by 0..3 indices. But you're trying to reference it by '+' sign which is beyond this scope. Consider using HashMap<String, Calculate> for storing operations in such way:
Map<String, Calculate> jumpTable = new HashMap<String, Calculate>();
jumpTable.put("+", new addition());
jumpTable.put("-", new subtraction());
jumpTable.put("*", new multiplication());
jumpTable.put("/", new division());
String operation = Character.toString((char) ops);
solution = jumpTable.get(operation).operation(x, y);

Categories

Resources