I keep getting cannot find symbol but i have declared it? - java

I'm not trying to do anything too fancy here really, there is something very simple here that i'm not noticing.
a little premise, this is a simple grade converter, run the driver, enter a double numberGrade(88.7, 90, 67.2, etc) and it will then go to the service and check the statements like this that i will have for grades A-F
if (enterGrade >= 90 && enterGrade <= 100)
grade = 'A';
keep getting an error though
import java.util.Scanner;
public class CondTest
{
public static void main(String[] args)
{
System.out.print("Please enter your number grade for a letter grade! >");
Scanner scanObj = new Scanner(System.in);
Conditionals condObj = new Conditionals();
int enterGrade = scanObj.nextInt();
condObj.Conditionals(enterGrade);
}
}
and heres my method in the service class to reference
public class Conditionals
{
public double letterGrade(double enterGrade)
{
char grade = 0;
if (enterGrade >= 90 && enterGrade <= 100)
grade = 'A';
return grade;
}
}
After troubleshooting more i thought maybe changing the
condObj.conditionals(enterGrade);
to
double condObj.conditionals(enterGrade);
but no luck.
I keep recieving this same error
CondTest.java:18:error: cannot find symbol
condObj.conditionals(enterGrade);

As far as I can see, there just is no method called conditionals in your Conditionals class - only a method called letterGrade. Maybe you should call this one instead?
Change it to
condObj.letterGrade(enterGrade);
And: Scanner.nextInt() returns an int, do you have a method that accepts an int param?

Related

How to fix/ learning help understanding basic method and classes, Java code and word Problem

I'm struggling on this problem, given that I'm probably making a basic mistake or I haven't got a clue what I'm doing.
platform being a Zybook
the problem reads:
One lap around a standard high-school running track is exactly 0.25 miles. Write a program that takes a number of miles as input, and outputs the number of laps.Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
System.out.printf("%.2f", yourValue);
Your program must define and call a method:
public static double
milesToLaps(double userMiles)
It gives off a couple of example input 1.5 -> 6.00, 2.2 ->8.80 etc.
it gives you a start off of:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
}
}
Below I've edited to this point, still I don't think I know what I'm doing. However I've gotten it down to one error which states that> error: cannot find symbol numMiles.printMilesToLaps(userMiles);. I would like someone to tell me if I'm doing this someway maybe correctly and or if they can solve this error, cause I've completely redid the code multiple times, and I'm at the point of giving up and never submitting it.
also sometimes I start to remove code that's supposed to be there, but at the same time doesn't make sense to the computer ex. being (return;), but maybe you can explain it in greater detail then the zybook or its checking system.
The code itself looked a bit neater, but I was forced to change it after the multiple errors.
import java.util.Scanner;
public class LabProgram {
public static double MilesToLaps(double userMiles){
Scanner scnr = new Scanner(System.in);
userMiles = scnr.nextDouble();
System.out.printf("%.2f", (userMiles / 0.25));
}
public static void main(String[] args) {
LabProgram numMiles = new LabProgram();
numMiles.printMilesToLaps(userMiles);
}
}
I'm getting constant cannot find symbol errors, mostly on the secondary public method. I could think I could fix this, but it wouldn't line up with the question parameters.
I'm usually only using the example input values in the input terminal.
There are a few issues with your posted code. The method should be named milesToLaps (not MilesToLaps). The method takes the user's input, and does not prompt. The method should return the result, not output it itself. And, I would multiply by 4 instead of dividing by 0.25. Like,
public static double milesToLaps(double userMiles) {
return userMiles * 4;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double userMiles = scnr.nextDouble();
System.out.printf("%.2f%n", milesToLaps(userMiles));
}
Please go through some basic java tutorials(JavaTpoint, Toutrialspoint etc.) where you can get a basic understanding of class, object, methods how these things works.
public static double MilesToLaps(double userMiles)
{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a number");
userMiles = scnr.nextDouble();
double x = (userMiles / 0.25);
return x;
}
public static void main(String[] args)
{
//LabProgram numMiles = new LabProgram(); this object not require because your calling method MilesToLaps() is static.
double result = MilesToLaps(5); // here in this method you need to pass a double type value.
System.out.println("user miles :"+ result);
}

How to compare three values from text field and if any are below/above a certain value display a message?

Hi i'm trying to write a programme similar to a BMI calculator tutorial i followed and completed successfully last fortnight.
However I'm now trying to do a health programme that compares a users temperature/blood pressure and heart beat, and if any are below or above certain values to warn the user via console message.
for example
if
temperature <35 or >39 display a warning message or
heart rate <60 or >150 display a warning message or
blood pressure <100 or >150 display a warning message.
hI am unsure how to convert and compare the value as it says "Operator '<' cannot be applied to 'java.lang.String', 'int'". I have the user input the value in a text field and understand that it is cannot compare text fields, so i tried to convert it to a float using Float.parseFloat(temperatureStr); but that didn't seem to work. Is there something that can change String temperatureStr = temperature.getText().toString(); into an interger so I am able to compare it to a number and then display a warning message?
I am not sure but if i understand you correctly you try to implement something like this:
class UserClassName {
int bodyTemp;
int bloodPressure;
int heartSkip;
public void getUsersValues() {
Scanner body, temp, blood;
body = new Scanner(System.in);
temp = new Scanner(System.in);
blood = new Scanner(System.in);
System.out.println("Your temp ..");
String intputTempAsString = body.nextLine();
try {
bodyTemp = Interger.parseInt(inputTempAsString);
catch {
throw new Exception("Your warning her");
}
// Do this for ever Number or Value you wanna have and it should work
}
// Methods to compare the input
public boolean checkHeartSkiptsFrequncy() {
return heartSkip > 60 && heartskip < 150;
}
public boolean checkBodyTemp() {
return heartSkip > 35 && heartskip < 39;
}
public boolean checkBlood() {
return heartSkip > 100 && heartskip < 150;
}
public boolean checkHealth() {
if(!chechHeartSkipFrequncy) {
System.out.println("The Frequceny of you Heartbeat ....");
else if(!checkBodyTemp) {
System.out.println("Your body Temp is bad...");
else if(!checkBlood) {
System.out.println("Your blood ....");
else {
System.out.println("Everything is fine")
}
I think this is what you are looking for. I know that is not 100% perfect but i hope this it will help you to solve your problem.
This code is also no complete solution for your problem but i tried to cover all important aspekts.
If you have any questions or improvment for me than reply to this post.
Have a nice Day and good luck man.

Difficulty exiting "user input" method called in main Java

I am trying to bring in some numerical values by way of Scanner(System.in). I am calling a class with my method from main and having a difficult time exiting the method, my questions are looping.
I am sure this is a simple issue but I am having a heck of a time finding a solution.
Here is the method:
public static Object userInput(double nutWidth, double lastFretWidth, double scaleLength, int numFrets) {
boolean dataCheck = true;
try {
while (dataCheck == true) {
System.out.println("What is the width at the nut?");
NutWidth = key.nextDouble();
System.out.println("What is the width at the last fret?");
LastFretWidth = key.nextDouble();
System.out.println("What is the scale length?");
ScaleLength = key.nextDouble();
System.out.println("How many frets will your guitar have?");
NumFrets = key.nextInt();
dataCheck = false;
}
} catch (InputMismatchException e) {
System.out.println("Enter a integer.");
key.nextInt();
}
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
}
Here is my main:
public static void main(String[] args) {
FingerBoard.userInput(0, 0, 0, 0);
FingerBoard.UserData();
}
Any help is greatly appreciated-Mike
You have written an infinite recursion. The line
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
will call the same method again after finishing the previous method. It looks to me like you want to store the values in a data structure and return that, which would require calling a constructor something like this:
return new UserInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
You would have to write the data structure UserInput yourself. If you haven't gotten to writing classes and data structures yet, you probably want your variables to be static fields. If you are doing that, change the return type to be void and remove the return statement entirely.
Additional comments not related to your problem. You don't need the arguments to your method. They are never used. You probably also want to put the try/catch inside of the while loop. That way an invalid input will prompt for new input, rather than setting things to 0.

For Loop Not Terminating

I'm trying to get back into Java - it's been about 5 years since I studied the basics and I've been lost in the .Net world since.
I'm trying to create a student class below, however the for loop for reading in the integers into the array gets stuck when the program runs.
From my previous knowledge, and from research, the loop seems to be constructed properly and I can't seem to figure out where it's going wrong.
I'm sure it's something silly - as always but I was wondering if someone could point me in the right direction? :)
import java.util.*;
import acm.io.*;
public class Student {
// instance variables
private int studNumber; //Must be between (and including) 0 and 99999999. If input value invalid default to 0.
private String studName;
private int marks[];
/*
* Constructor Student Class
*/
public Student(int studNumber, String StudName, int marks[]) {
// initialise instance variables
if (studNumber >=0 && studNumber<= 99999999) {
this.studNumber= studNumber;
} else {
this.studNumber = 0; //default value
}
this.studName= StudName; // no validation
this.marks = marks;
IOConsole console = new IOConsole();
for (int i = 0; i <= 6; i++) {
marks[i] = console.readInt();
}
}
}
I think that the problem lies here:
for (int i = 0; i <= 6; i++)
{
marks[i] = console.readInt();
}
The only instance where I found a reference to IOConsole was here and it does not seem to be something which is part of the standard Java framework.
If you just need to scan numbers from console, you can use the Scanner class and the use the nextInt() method like below:
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 6; i++)
{
marks[i] = input.nextInt();
}
The loop seems correct. Is it possible the console.readInt() call is blocking, which keeps you stuck in the loop (the IOConsole class is not part of the standard JDK, and I am not familiar with it)
readInt() is waiting for user input
from http://jtf.acm.org/javadoc/student/acm/io/IOConsole.html#readInt%28%29:
Reads and returns an integer value from the user
The problem is with console.readInt(), where another non-stop loop is executing or some other problem with that method
I believe the problem lies in the readInt() part. It's unusual to read input from the Console in a constructor for initializing the attributes, delegate that task to another part of your code and move it outside the constructor.

Can anyone help me modify my code in Java?

Okay to make this clearer this is what i need done to my entire program. I need main to restore any calculators that are in the file "calc.bak" before presenting the user with a menu and main should save all calculators that exist in that same file (overwrite as appropriate) just before exiting. I also need to give the user the option to create a brand new calculator, name it, and add a function to it from an already existing collection (which are my Add, multiply, and divide). I also need the user to create their own function by designing and naming a combination of any pair of functions. The ouput of the first function would necessarily be input to the second function. For example, the user can create a new function called "addmult" that calls the add function (which prompts for two numbers and adds them) and establishes the sum as one of the operands for the multiply function (which would have to prompt for its second operand).
The sample out put should look like this:
Welcome to the Calculator Configurator
restore a calculator from a file
create a calculator from scratch
let me create a calculator you can use
2
OK. so you want to create one yourself.
What is the name of your calculator? Fred
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add(1)
Multiply(2)
Divide(3)
Pair of functions(4)
input (2)
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add
Multiply
Divide
Pair of functions
1
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add
Multiply
Divide
Pair of functions
4
Provide a name for this pair:
BothAddAndMult
Provide a description for this pair:
multiplies and then adds
Which function should be first?
Multiply(0)
Add(1)
0
Which function should be first?
Multiply
Add
1
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add
Multiply
Divide
Pair of functions
4
Provide a name for this pair:
MultAfter
Provide a description for this pair: multiplies last after a multiply and add
Which function should be first?
Multiply
Add
BothAddAndMult
2
Which function should be first?
Multiply
Add
BothAddAndMult
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add
Multiply
Divide
Pair of functions
0
I am a calculator named Fred
quit
clear memory
multiply two numbers
add two numbers
multiplies and then adds
multiplies last after a multiply and add
Can someone help me reach this output?
Here is my code so far
CalcConfig.java
import java.util.Scanner;
// program to model a configurable calculator
public class CalcConfig {
public static void main(String [] args)
{
System.out.println("Welcome to the Calculator Configurator");
Scanner kbd = new Scanner(System.in);
CalcFunction [] funs = {
new Add(kbd, "add two numbers"),
new Multiply(kbd, "Multiply two numbers"),
new Divide(kbd, "divide two numbers")};
Calculator calc = new Calculator(funs);
calc.go(kbd);
}
}
Calculator.java
//my Calculator class
import java.util.Scanner;
// models a configurable calcuator
public class Calculator {
private CalcFunction [] functions;
private double memory = 0;
private boolean clear = true;
public Calculator(CalcFunction [] functions)
{
this.functions = functions;
}
public void go(Scanner kbd)
{
int choice = 0;
do
{
System.out.println(this);
choice = kbd.nextInt();
if (choice == 0) return; // choice is to quit
if (choice == 1)
{
clear = true;
continue;
}
if (choice < 0 || choice >= 5)
{
System.out.println("error");
continue;
}
if (!clear)
{
System.out.print("use memory [" + memory + "] (y or n)? ");
String ans = kbd.next();
if (ans.equals("n")) clear = true;
}
if (clear)
memory = functions[choice-2].doit();
else
memory = functions[choice-2].doit(memory);
clear = false;
System.out.println(memory);
} while(choice != 0);
}
public String toString()
{
String out = "0. quit\n1. clear memory\n";
for (int i=0; i<functions.length; i++)
out += (i+2) + ". " + functions[i] + "\n";
return out;
}
}
CalcFunction.java
//my CalcFunction class
import java.util.Scanner;
// generic class to model a function in a calculator
public abstract class CalcFunction {
private Scanner kbd;
private String description;
public CalcFunction(Scanner kbd, String description)
{
this.kbd = kbd;
this.description = description;
}
public abstract double doit();
public abstract double doit(double memory);
// get a string from the user
protected String getString(String prompt)
{
System.out.print(prompt);
return kbd.next();
}
// get a number from the user
protected double getNum(String prompt)
{
System.out.print(prompt);
while(!kbd.hasNextDouble())
{
System.out.print("Invalid: need a number: ");
kbd.next(); // discard invalid input
}
return kbd.nextDouble();
}
public String toString()
{
return description;
}
}
Add.java
//just one of my functions(Add)
import java.util.Scanner;
// class to encapsulate adding two numbers
public class Add extends CalcFunction {
public Add(Scanner kbd, String description)
{
super(kbd, description);
}
public double doit()
{
double n1 = this.getNum("Enter a number: ");
return this.doit(n1);
}
public double doit(double first)
{
double n2 = this.getNum("Enter a second number: ");
double answer = first + n2;
return answer;
}
}
Please help if you can. Thanks!
Pseudo-code:
// 1 maps to add, 2 to subtract, etc
while(cur_func = scanner.read != sentinal value) {
switch(cur_func) {
1:
//toss add into the functions set
break
.
.
.
}
}
toArray your set and build the calc
If you want the user to be able to dynamically add calculator functions to a calculator, then you will need something like this:
public void addCalcFunction(CalcFunction newCalcFunction) {
this.functions.add(newCalcFunction);
}
...but that will require this.functions to be modified to a Collection<CalcFunction>
If you want the user to refer to these functions by name, then you'll need to map them:
private Map<String, CalcFunction> functions;
...
public void addCalcFunction(String functionName, CalcFunction newCalcFunction) {
this.functions.put(functionName, newCalcFunction);
}
Using a Map will require you to make further changes, but I'm sure you can figure those out.

Categories

Resources