<Identifier> Expected- Having major difficulty, New to coding - java

class Maths{
// Attributes of maths
private int num1;
private int num2;
//Constructor
public Maths ***- This is where the error is***
{
add = a;
subtract = s;
multiply = m;
divide = d;
}
//Get me some Accessors
public String getAdd()
{
return add;
}
public string getSubtract()
{
return subtract;
}
public String getMultiply()
{
return multiply;
}
public String getDivide()
{
return divide;
}
}
}
Alright so I'm new to programming, Absolutely newborn. I'm really not sure what to do for this. I need to "Write a class called Maths. It has 2 attributes called num1 and num2. It has a constructor. It will have methods called Add(), subtract(), multiply() and divide().(Hint: integer division use modulus operator). Most of these methods return the result.
Write all the getters and setters and a toString() method."

In Maths constructor you have forgotten parenthesis ()
Do like this
public Maths()
{
add = a;
subtract = s;
multiply = m;
divide = d;
}

constructor has the same name as class and parenthesis.
this is what you need to put there.
public Maths()
{
add = a;
subtract = s;
multiply = m;
divide = d;
}

Related

OOP in Java: problem with constructor and methods

I am new to Java and I am trying to write a class with constructors and methods that adds and divides two numbers, and also compares if one object is larger or equal than the other. But I am getting an error: The method plus(int) in the type Compare is not applicable for the arguments (Compare). what's wrong?
Here's the code:
public class Compare {
// fields
private int number;
private int plus;
private double div;
// constructor
public Compare (int n) {
number = n;
}
public int plus (int x) {
return this.number + x;
}
public int div (int x) {
return this.number / x;
}
public boolean isLargerThan (int x) {
return this.number > x;
}
public boolean isEqualTo (int x) {
return this.number == x;
}
public static void main(String[] args) {
Compare n1 = new Compare(9);
Compare n2 = new Compare(4);
Compare sum = n1.plus(n2);
Compare div = n1.div(n2);
boolean check1 = sum.isLargerThan(n1);
boolean check2 = div.isLargerThan(n2);
boolean check3 = div.isEqualto(sum);
}
}
The requirement is to create sum and div objects using Compare constructor that will be equal to n1 plus n2, with plus method or division as applicable.
It may be that here you want a new Compare, containing the sum.
public Compare plus (int x) {
return new Compare(number + x);
}
public Compare plus (Compare x) {
return new Compare(number + x.number);
}
This also is implied by expecting a Compare object, not an int as shown.
With that Compare would become immutable, which is very good, as you then can share objects in different variables without problems (changing one variable's value changing other variables' values).
#Override
public String toString() {
return Integer.toString(number);
}
public int intValue() {
return number;
}
The issue here is for the "plus", "div", "isLargerThan" and "isEqualTo" methods in "Compare" class the argument/return type is of type "int". But in "main" function you are passing the object and expecting object of type "Compare".
To fix it either change the argument/return type to "Compare" for those methods in "Compare" class or pass the "int" value as parameter and get "int" value in "main" function.
The plus and div methods take an int and return an int and you are trying to receive their output in a Compare object. Also, isLargerThan takes an int and not a Compare.
Problem is here :
Compare sum = n1.plus(n2);
Compare div = n1.div(n2);
methods : plus and div return int value not an objet of Class Compare.
public int plus (int x) {
return this.number + x;
}
public int div (int x) {
return this.number / x;
}
Add getter method in Compare Class.
public int getNumber(){
return number;
}
Use below code and try to run:
public static void main(String[] args) {
Compare sum = new Compare(9);
Compare divObj = new Compare(4);
sum.plus(n2);
divObj.div(n2);
boolean check1 = sum.isLargerThan(sum.getNumber());
boolean check2 = divObj.isLargerThan(divObj.getNumber());
boolean check3 = divObj.isEqualto(sum.getNiumber());
}

Return Comparator's compare method using a double?

So I have a class to compare the rating of a film. It implements the comparator class as seen below:
public class FilmComparator implements Comparator<Film> {
private Map<Film, List<Rating>> ratings;
public FilmComparator(Map<Film, List<Rating>> ratings) {
this.ratings = ratings;
}
#Override
public int compare(Film o1, Film o2) {
double average1 = average(o1);
double average2 = average(o2);
return average2 - average1; // I cant do this because it need to return an int
}
private double average(Film f) {
int sum = 0;
for (Rating r : ratings.get(f)) {
sum += r.getValue();
}
return sum / ratings.get(f).size();
}
}
As you can see, the average might not always be an integer. I am wondering how I would be able to have a more accurate compare. For example, I am having issues when the average returns 3.6 for one object but 3.0 for the other. To the compare method, the are the same but I need to show a difference. Is this possible?
Simple, let Double do the work for you. Do
return Double.compare(average1, average2); // or swap if desired

Java Code Questions

I want to implement a class which includes a student's name, their GPA, grade level, and their final score. We had to create a Tester along with the initial class creates 2 different students, prints their grade level, GPA, their name, and the calculated final test score.
Formula to calculate final test score = .60 * written + .40 * handsOn
Any help would be appreciated, I can't get this program down and I've been trying for quite a while now.
Here is my code:
Tester:
public class IntroToJavaTester
{
public static void main()
{
IntroToJava j1 = new IntroToJava("Joe", 11, 3.2);
System.out.println(j1.getName());
System.out.println(j1.getGradeLevel());
System.out.println(j1.getGPA());
System.out.println(j1.getFinalScore(written, handsOn));
IntroToJava j2 = new IntroToJava("Jim", 11, 3.2);
System.out.println(j2.getName());
System.out.println(j2.getGradeLevel());
System.out.println(j2.getGPA());
System.out.println(j2.getFinalScore( written,handsOn));
}
}
Here is the IntroToJava class:
public class IntroToJava
{
private String name;
private int glev;
private double gpa;
private double finalscore;
private double written = 80;
private double handsOn = 90;
public IntroToJava(String a, int b, double c, double d, double e)
{
name = a;
glev = b;
gpa = c;
written = d;
handsOn = e;
}
public String getName()
{
return name;
}
public int getGradeLevel()
{
return glev;
}
public double getGPA ()
{
return gpa;
}
public double getFinalScore(int written, int handsOn)
{
finalscore = .60*written+.40*handsOn;
return finalscore;
}
}
Your IntroToJava constructor is defined with 5 arguments and you're calling it with only 3 in IntroToJavaTester.
The two arguments you're omitting appear to correspond to the fields written and handsOn.
You've defined getFinalScore to take two arguments with the same names but a different type.
I suspect what you probably really want is for getFinalScore to take no arguments but use these two fields.
Or perhaps getFinalScore is supposed to just be a getter for the field finalScore which doesn't seem to be set or used anywhere, but has a suspiciously similar name.

Constructor isn't printing as expected

public class Fraction
{
public Franction(int n, int d)
{
int num = n;
int denom = d;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
Hello, I'm trying to learn Java... The book I'm working out of suggests that the output of the code above should print "Fraction = 5/10", but when I try it I just receive "Fraction = Fraction#33469a69" which I assume is printing the reference to where it is stored? I understand how it is suppose to work with the constructor I just don't receive the expected output. Any help would be greatly appreciated... Thanks!
To get the desired output, you need to overload toString() method in the Franction class. This method is used to determine textual representation of the object. By default, it is ClassName#hashCode.
Also, you probably would like to store the values you receive in the constructor as fields. Right now, you store the numerator and denominator in constructor's local variables, that are destroyed as soon as the constructor exits.
Try something like this:
public class Fraction
{
private final int num
private final int denom;
public Franction(int n, int d)
{
this.num = n;
this.denom = d;
}
#Override
String toString()
{
return String.format("%d/%d", num, denom);
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
You need to override the toString method for the same
public String toString(){
StringBuilder stringToReturn = new StringBuilder();
stringToReturn.append(this.num);
stringToReturn.append("/");
stringToReturn.append(this.denom);
return stringToReturn.toString();
}
You have to override the toString() function in your Fraction class.
As per docs of toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
Fraction#33469a69 is the textual representation of Fraction class.
To get the required output, write the logic in overridden toString method in Object class and return the string there.
A simple toString implementation looks like
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.someMemeber); //will be in String format
result.append(this.someMemeber);
return result.toString();
}
Try this
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1.getNum() + "/" + f1.getDenom());
}
}
Alternative (Better way to do this)
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
#Override
public String toString(){
return (f1.getNum() + "/" + f1.getDenom());
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1 );
}
}
You need to study more about encapsulation , the Object class and the toString() method.
Happy Coding :)
Try the following:
public class Fraction {
private final int num;
private final int denom;
public Fraction(int num, int denom) {
this.num = num;
this.denom = denom;
}
#Override
public String toString() {
return num + "/" + denom;
}
public static void main(String[] args) {
Fraction f1 = new Fraction(5, 10);
System.out.println("Fraction = " + f1);
}
}
You have to store the values in the object you create. Then override the toString method of Object to get your desired output.
Output:
Fraction = 5/10
All you are doing is printing out the Object.
If you want to print the contents of the Object you will to create a toString method in you class.
see http://www.javapractices.com/topic/TopicAction.do?Id=55

Random math questions generator for Android

Any help or advice would be greatly appreciated. I'm trying to create a simple game which generates ten different, random questions. The questions can contain 2, 3 or 4 integers. So something like this: 55 2 − 4 − 101, 102/3/3, 589 − 281, 123 + 5 6 + 2.
The question will be displayed in a textview and then the user can take a guess, entering values into an edittext and then upon clicking a key on a custom keypad I have created it will check the answer, and then display the next question in the sequence of 10.
I know how to create random numbers, just struggling to work out how to create a whole question with random operators (+, -, /, *).
Big thank you to anyone who has the time to construct a reply.
A little of spare time produced a complete example for your case. Create new RandomMathQuestionGenerator.java file and it is cooked for compilation.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class RandomMathQuestionGenerator {
private static final int NUMBER_OF_QUESTIONS = 10;
private static final int MIN_QUESTION_ELEMENTS = 2;
private static final int MAX_QUESTION_ELEMENTS = 4;
private static final int MIN_QUESTION_ELEMENT_VALUE = 1;
private static final int MAX_QUESTION_ELEMENT_VALUE = 100;
private final Random randomGenerator = new Random();
public static void main(String[] args) {
RandomMathQuestionGenerator questionGenerator = new RandomMathQuestionGenerator();
List<Question> randomQuestions = questionGenerator.getGeneratedRandomQuestions();
for (Question question : randomQuestions) {
System.out.println(question);
}
}
public List<Question> getGeneratedRandomQuestions() {
List<Question> randomQuestions = new ArrayList<Question>(NUMBER_OF_QUESTIONS);
for (int i = 0; i < NUMBER_OF_QUESTIONS; i++) {
int randomQuestionElementsCapacity = getRandomQuestionElementsCapacity();
Question question = new Question(randomQuestionElementsCapacity);
for (int j = 0; j < randomQuestionElementsCapacity; j++) {
boolean isLastIteration = j + 1 == randomQuestionElementsCapacity;
QuestionElement questionElement = new QuestionElement();
questionElement.setValue(getRandomQuestionElementValue());
questionElement.setOperator(isLastIteration ? null
: Operator.values()[randomGenerator.nextInt(Operator.values().length)]);
question.addElement(questionElement);
}
randomQuestions.add(question);
}
return randomQuestions;
}
private int getRandomQuestionElementsCapacity() {
return getRandomIntegerFromRange(MIN_QUESTION_ELEMENTS, MAX_QUESTION_ELEMENTS);
}
private int getRandomQuestionElementValue() {
return getRandomIntegerFromRange(MIN_QUESTION_ELEMENT_VALUE, MAX_QUESTION_ELEMENT_VALUE);
}
private int getRandomIntegerFromRange(int min, int max) {
return randomGenerator.nextInt(max - min + 1) + min;
}
}
class Question {
private List<QuestionElement> questionElements;
public Question(int sizeOfQuestionElemets) {
questionElements = new ArrayList<QuestionElement>(sizeOfQuestionElemets);
}
public void addElement(QuestionElement questionElement) {
questionElements.add(questionElement);
}
public List<QuestionElement> getElements() {
return questionElements;
}
public int size() {
return questionElements.size();
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (QuestionElement questionElement : questionElements) {
sb.append(questionElement);
}
return sb.toString().trim();
}
}
class QuestionElement {
private int value;
private Operator operator;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
#Override
public String toString() {
return value + (operator == null ? "" : " " + operator.getDisplayValue()) + " ";
}
}
enum Operator {
PLUS("+"), MINUS("-"), MULTIPLIER("*"), DIVIDER("/");
private String displayValue;
private Operator(String displayValue) {
this.displayValue = displayValue;
}
public String getDisplayValue() {
return displayValue;
}
}
Run and preview. Hope this helps.
Thanks to:
Generating random number in
range
Retrieving random
element from array
Create an array char[] ops = { '+', '-', '/', '*' } and create a random int i in range [0,3], and chose ops[i]
You will need to take care that you do not generate a divide by zero question.
You can make it even more generic by creating an interface MathOp and creating 4 classes that implement it: Divide, Sum , ... and create an array: MathOp[] ops instead of the char[]
Using this, it will also give you much easier time to check the result later on...
Put your operators in an array (4 elements), generate a random integer from 0 to 3, and pick the operator that is at this index in the array.
Do that each time you need to have a random operator, i.e. after every number of your question except the last one.
Make an array that has one entry for each of the operators. Then generate a random number between 0 and the length of the array minus 1.
So since each operation is binary you can just worry about figuring out the base case and then building up your expressions from there.
An easy way would just to select a random number an correlate that which operation will be used.
int displayAnswer(int leftSide, int rightSide, int operation {
int answer;
string operation;
switch(operation) {
case 1:
operation = "+";
answer = leftSide + rightSide;
break;
case 2:
operation = "-";
answer = leftSide - rightSide;
break;
case 3:
operation = "*";
answer = leftSide * rightSide;
break;
case 4:
operation = "/";
answer = leftSide / rightSide:
break;
}
textView.setText(leftSide + operation + rightSide);
return answer;
}

Categories