I'm a newbie coder here currently taking a computer science class based on java. I'm having issues with a program I'm supposed to be writing and I can't seem to figure it out regardless of what I look up, so I'm asking on here.
The instructions say: Create a class. Create a method within the class called printDimensions() that displays the dimensions of a letter-size(8.5x11 inches) sheet of paper in millimeters. There are 25.4 millimeters per inch (constant value). Use constants and comments in the method. It also says (make use of printf to limit the number of decimal places in your method.
As of right now I am stuck in the middle of using the print statement and the return value for the method. I also have a tester that I am using to test the code, but I'm getting BOTH the print statement AND the return value, which I don't believe is correct.
public class Task01
{
// final dimensions of the paper
private double dimensions;
// width of the paper which is 8.5
private double paperWidth;
// length of the paper which is 11
private double paperLength;
public Task01(){
dimensions = 0;
paperLength = 0;
paperWidth = 0;
}
public double printDimensions()
{
final double LENGTH = 11; // inches
final double WIDTH = 8.5; // inches
final double MM_PER_INCH = 25.4; // millimeters per inch
paperLength = LENGTH * MM_PER_INCH;
paperWidth = WIDTH * MM_PER_INCH;
System.out.printf("The dimension are: " + paperLength + " x " + paperWidth);
return dimensions;
}
}
For the tester, I have a seperate class that I use to call the methods I create by creating a new object for that task.
public class Tester
{
public static void main(String[] arg)
{
System.out.println("The task begins now: ");
// creating a new object for the task
Task01 task01 = new Task01();
System.out.println(task01.printDimensions());
}
}
Change this line:
public double printDimensions()
To this
public void printDimensions()
then remove the return statement at the end of that method
You have two options. You can remove the line System.out.printf("The dimension are: " + paperLength + " x " + paperWidth); from the printDimensions methods. Then your tester class just create an instance of Task01 and call the method in a print statement which would look something like this:
public static void main(String[] args) {
Task01 t = new Task01();
System.out.println(t.printDimensions);
}
The other option as already stated is to change the method type to void rather than double and remove the return statement. Then call it like this:
public static void main(String[] args) {
Task01 t = new Task01();
t.printDimensions();
}
Related
This code does not run when I try to compile it, I am sure it is because I
defined my function/method incorrectly, so it would be much appreciated if
someone can correct my code and also tell me what is wrong with it.
I know C++ so I tried to define the function like how I would define it
normally in Cpp but with a few tweaks. I really don't know what I am doing
right now.
class Calculator {
public static void main(String[] arguments) {
float Celcius;
float Farenheit = 32;
final float k = 5 / 9;
System.out.println("This is the temperature in degrees celsius: " +
Converter(Farenheit));
public float Converter(float Farenheit) {
return 5 / 9 * (Farenheit - 32);
}
}
}
So the comments noted the key issues. The method cannot be within main. 5/9=0 in Java. Here is a little program I just checked on jdoodle.com. It does what you said in what might be typical Java style (though for sure there are possible improvements and things with which to quibble). For learning Java (which is not the same as for experienced users for development), bluej is an interesting IDE with which to start (specifically because it doesn't do all the work for you). But StackOverflow does not want judgment questions like that, so ignore if you wish.
public class Calculator {
public double converter(double Farenheit) {// convention converter lower case because not a class name
return 5.0 / 9 * (Farenheit - 32); //note 5.0 ensures real number arithmetic, not integer
}
public static void main(String[] arguments) {
Calculator calculator = new Calculator();// make a calculator object, alternative would be to declare converter static
double Farenheit = 32;
System.out.println("This is the temperature in degrees celsius: " +
calculator.converter(Farenheit));
}
}
Your method public float Converter(float Farenheit) is written inside main method . This is not allowed in JAVA . You can however write a anonymous class inside a method and calls its methods .
The correct code is :
class Calculator {
private static final float k = 5.0f / 9;
public static void main(String[] arguments) {
float Celcius;
float Farenheit = 32;
System.out.println("This is the temperature in degrees celsius: " +
Converter(Farenheit));
}
public static float Converter(float Farenheit) {
return k * (Farenheit - 32);
}
}
Please note I have modified Converter method to a static one . We cannot call non static methods from static context in JAVA(as main is static here) . If Converter would have been non static then we would have to create an object of the Calculator class.
Calculator c = new Calculator();
c.Converter(Fahrenheit);
You can declare k as class level variable if it is to be used across multiple methods and has a constant value .
private static final float k = 5.0f / 9;
So I created Saving class, created also setters and getters. Now I need u method, which will calculate the total amount of deposits.
public class Saving {
private double deposits;
private double totalAmountOfDeposits;
public double getDeposits()
{
return deposits;
}
public void setDeposits(double deposits)
{
this.deposits = deposits + deposits;
}
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
}
When I use this class in the program I got a wrong calculation. The program just add first value of deposit to the first value.
import java.util.Scanner;
public class SavingDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Saving save = new Saving();
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
}
}
And here is the output:
Deposit amount
12
Deposit amount
34
Deposit amount
56
The total amount has been deposited is 24.0
As you can see its just added 12 to 12. Just want to mention that I'm totally new in programming. Les than a month.
I see two problems in your code. Take a look at the commented line. The reason you are seeing 12 + 12 is because that is exactly what you are instructing the JVM to do.
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
Secondly, it looks like you may have a design flaw in your implementation of the Saving class.
You'll want to brush up on variable scope
If you take a look at your implementation on your total:
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
You have the total starting at 0 every time this method getTotalAmountOfDeposits() is called. the total variable in this method is local to it's method. So what you currently have is a method variable
You'll want to do some research into class variable. This will maintain that the instance of the object will have this variable assigned through the life cycle of the instantiated object.
When you have variables of the same name, you can get the instance variable with this keyword.
So when dealing with your setter
public void setSomething(double something) {
this.something // class variable
something // method variable
}
If you want your object to maintain state, you can set it on your object itself, and have your set deposit modify that state. Some pseudo code to get you moving forward.
public class Saving {
private double totalAmountOfDeposits; // you can modify this value with public methods
public void setDeposit(_) {
// Setter implementation
// increment totalAmountOfDeposits;
public double getTotalAmountOfDeposits(_)
// return totalAmountOfDeposits;
}
You should write a method
public void addDeposits(double deposits)
{
this.deposits = this.deposits + deposits;
}
and change setDeposits to
public void setDeposits(double deposits)
{
this.deposits = deposits;
}
after this call addDeposits to add deposits
To eliminate confusion within the Saving Class change the argument name for the setDeposits() method to double newDeposit instead of double deposits which is also a class field name. Although the construct is legal it does make it a wee bit confusing. Inside the setDeposits() method use:
this.deposit+= newDeposit;
As a matter of fact, you can get rid of the deposits field altogether since you also have the field named totalAmountOfDeposits. Use that instead:
this.totalAmountOfDeposits+= newDeposit;
You might also want a clearDeposits() method in your Saving Class:
public void clearDeposits() {
this.totalAmountOfDeposits = 0.0;
}
Your getTotalAmountOfDeposits() method within the Saving Class doesn't really make any sense either. Since you are always summing deposits anyways you can just return what is held within the totalAmountOfDeposits field:
public double getTotalAmountOfDeposits() {
return totalAmountOfDeposits;
}
The above method is would now of course be very mush the same as the getDeposits() method which could be changed to getTotalDeposits(). You can then change the getTotalAmountOfDeposits() method name to getTotalNumberOfDeposits() and add a additional class field named numberOfDeposits:
private double totalAmountOfDeposits;
private int numberOfDeposits = 0;
public double getTotalDeposits() {
return totalAmountOfDeposits;
}
public int getTotalNumberOfDeposits() {
return numberOfDeposits;
}
and in your setDeposits() method add the code line:
numberOfDeposits++;
So that it would look something like:
public void setDeposits(double newDeposit) {
totalAmountOfDeposits+= newDeposit;
numberOfDeposits++;
}
If you do add a clearDeposits() method to your Saving Class then don't forget to add the code line: numberOfDeposits = 0; into that method as well. It might now look something like:
public void clearDeposits() {
totalAmountOfDeposits = 0.0;
numberOfDeposits = 0;
}
You also have some issues within your main() method of your SavingDemo Class. Take a real close look at each call you make to the setDeposits() method for each value the User supplies. Each User supplied value goes into a specific double type variable name. Is that what you are passing to the setDeposits() method? ;)
Once you've got all that taken care of you can display to console:
System.out.println("The total amount has been deposited is " +
save.getTotalDeposits() + " by making " +
save.getTotalNumberOfDeposits() + " deposits.");
I need to write a program and, in one step of it, I need to construct a function that calculates the number of rabbits.
The problem is that Eclipse shows a message saying that the variable I created "cannot be resolved to a variable" and I don't understand why it happens. Can someone help me?
Here is part of my code
I am showing all my code because it would get bigger and it is not needed, in order to solve this problem
class Rabbits {
static int nbRabbits = initRabbits; // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
static int nbFoxes = initFoxes; // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
int rabbits = 0;
public static int calculateRabbits(int rabbits, int foxes, double AttackRate) {
for (int i = 0; i < Duration; ++i) {
rabbits = nbRabbits;
nbRabbits *= (1.0 + Rabbits_growth_rate - AttackRate * nbFoxes);
}
return nbRabbits;
}
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
// Enter initial population
int initFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
int initRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits
// SOME MORE CODE HERE
} // end main
} // end of class
initRabbits and initFoxes are variables entered by the user when I call enterPopulation method.
I'm new to Java and, unfortunately, I cannot change the logic of this code. For example, I cannot put the calculateRabbits method inside the main neither change the begin or the end of the code.
initRabbits only exists within the main method. That is it's scope.
You are attempting to statically reference something it can't see. You are attempting to populate nRabbits before a value for innitRabbits exists. This is impossible.
Your trying to assign a value to your nb variables from a variable that hasn't been created yet. Skip making four variables and just assign the nbs to 0 outside of your main class, then give them the value you want inside it. They will then retain that value outside of the main class and be visible.
static int nbRabbits = 0;
static int nbFoxes = 0;
//in main class
nbFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
nbRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits
I am having issues with the output of my code. Seems I am missing something in my method that I created... I had instructions to return the total number of inches. I places totInches after return and get an error stating that totInches is not a variable. Not certain what is missing here as I am only supposed to be creating a method. Most of this code was written and the only portion I was supposed to created was the second convertToInches method.. Any advice?
import java.util.Scanner;
public class FunctionOverloadToInches {
public static double convertToInches(double numFeet) {
return numFeet * 12.0;
}
public static double convertToInches(double numFeet, double numInches) {
return totInches * 12.0;
}
public static void main (String [] args) {
double totInches = 0.0;
totInches = convertToInches(4.0, 6.0);
System.out.println("4.0, 6.0 yields " + totInches);
totInches = convertToInches(5.9);
System.out.println("5.9 yields " + totInches);
return;
}
}
The variable totInches is not defined in the scope of your function:
public static double convertToInches(double numFeet, double numInches) {
return totInches * 12.0;
}
The only variables you can use in this function are the ones you create and the ones defined as formal parameters: numFeet and numInches. So you have to come up with an equation that takes numFeet and converts it to inches, taking into account the additional inches provided in numInches.
You declared the double variable "totInches" inside of your main method, but you are trying to access it inside of your "convertToInches" method. When declaring a variable in a particular method, that variable is ONLY accessible by that method. Your "convertToInches" knows of only two variables: numFeet and numInches, which you passed to it in the parameter. It then looks at your return statement, sees "totInches" and has no idea what it is.
I also don't understand what this is trying to do...
public static double convertToInches(double numFeet, double numInches) {
return totInches * 12.0;
}
Why are you passing it the double variables numFeet and numInches? The function isn't using them. I also don't understand why you need both the number of feet AND the number of inches if the method, by its name, is trying to convert something into inches.
public static double convertToInches(double numFeet, double numInches) {
return (numFeet * 12) + numInches;
This takes into account any variable amount entered by user for height of 5 feet 7 inches or 6 feet even
I'm trying some Java recently and look for some review of my style. If You like to look at this exercise placed in the image, and tell me if my style is good enought? Or maybe it is not good enought, so You can tell me on what aspect I should work more, so You can help me to improve it?
exercise for my question
/*
* File: MathQuiz.java
*
* This program produces Math Quiz.
*/
import acm.program.*;
import acm.util.*;
public class MathQuiz extends ConsoleProgram {
/* Class constants for Quiz settings. */
private static final int CHANCES = 3;
private static final int QUESTIONS = 5;
private static final int MIN = 0;
private static final int MAX = 20;
/* Start program. Number of questions to ask is assigned here. */
public void run() {
println("Welcome to Math Quiz");
while(answered != QUESTIONS) {
produceNumbers();
askForAnswer();
}
println("End of program.");
}
/* Ask for answer, and check them. Number of chances includes
* first one, where user is asked for reply. */
private void askForAnswer() {
int answer = -1;
if(type)
answer = readInt("What is " + x + "+" + y + "?");
else
answer = readInt("What is " + x + "-" + y + "?");
for(int i = 1; i < CHANCES+1; i++) {
if(answer != solution) {
if(i == CHANCES) {
println("No. The answer is " + solution + ".");
break;
}
answer = readInt("That's incorrect - try a different answer: ");
} else {
println("That's the answer!");
break;
}
}
answered++;
}
/* Produces type and two numbers until they qualify. */
private void produceNumbers() {
produceType();
produceFirst();
produceSecond();
if(type)
while(x+y >= MAX) {
produceFirst();
produceSecond();
}
else
while(x-y <= MIN) {
produceFirst();
produceSecond();
}
calculateSolution();
}
/* Calculates equation solution. */
private void calculateSolution() {
if(type) solution = x + y;
else solution = x - y;
}
/* Type of the equation. True is from plus, false is for minus. */
private void produceType() {
type = rgen.nextBoolean();
}
/* Produces first number. */
private void produceFirst() {
x = rgen.nextInt(0, 20);
}
/* Produces second number. */
private void produceSecond() {
y = rgen.nextInt(0, 20);
}
/* Class variables for numbers and type of the equation. */
private static boolean type;
private static int x;
private static int y;
/* Class variables for equation solution. */
private static int solution;
/* Class variable counting number of answered equations,
* so if it reaches number of provided questions, it ends */
private static int answered = 0;
/* Random generator constructor. */
RandomGenerator rgen = new RandomGenerator();
}
One thing I noticed was that all of your methods take no parameters and return void.
I think it would be clearer if you use method parameters and return values to show the flow of data through your program instead of using the object's state to store everything.
There are a few things you should do differently, and a couple you could do differently.
The things you should do differently:
Keep all fields together.
static fields should always be in THIS_FORM
you've used the static modifier for what clearly look like instance fields. (type,x,y,solution, answered). This means you can only ever run one MathsQuiz at a time per JVM. Not a big deal in this case, but will cause problems for more complex programs.
produceFirst and produceSecond use hardcoded parameters to nextInt rather than using MAX and MIN as provided by the class
There is no apparent need for answered to be a field. It could easily be a local variable in run.
Things you should do differently:
There is a small possibility (however tiny), that produceNumbers might not end. Instead of producing two random numbers and hoping they work. Produce one random number and then constrain the second so that a solution will always be formed. eg. say we are doing and addition and x is 6 and max is 20. We know that y cannot be larger than 14. So instead of trying nextInt(0,20), you could do nextInt(0,14) and be assured that you would get a feasible question.
For loop isn't really the right construct for askForAnswer as the desired behaviour is to ask for an answer CHANCES number of times or until a correct answer is received, whichever comes first. A for loop is usually used when you wish to do something a set number of times. Indeed the while loop in run is a good candidate for a for loop. A sample while loop might look like:
int i = 1;
boolean correct = (solution == readInt("What is " + x + "+" + y + "?"));
while (i < CHANCES && !correct) {
correct = (solution == readInt("Wrong, try again."));
i++;
}
if (correct) {
println("Well done!");
} else {
println("Nope, the answer is: "+solution);
}
Looks like a very clean program style. I would move all variables to the top instead of having some at the bottom, but other than that it is very readable.
Here is something I'd improve: the boolean type that is used to indicate whether we have an addition or subtraction:
private void produceType() {
type = rgen.nextBoolean();
}
produceType tells, that something is generated and I'd expect something to be returned. And I'd define enums to represent the type of the quiz. Here's my suggestion:
private QuizType produceType() {
boolean type = rgen.nextBoolean();
if (type == true)
return QuizType.PLUS;
else
return QuizType.MINUS;
}
The enum is defined like this:
public enum QuizType { PLUS, MINUS }
Almost good I have only a few improvements:
variables moves to the top
Inside produceNumbers and your while you have small repeat. I recommend refactor this
Small advice: Code should be like books - easy readable - in your run() method firstly you call produceNumber and then askForAnswer. So it will be better if in your code you will have the same order in definitions, so implementation askForAnswer before produceNumber. But it isn't necessary
Pay attention to have small methods. A method shouldn't have much to do - I think that askForAnswer you could split to two methods