java polymorphism and interface implementation - java

I'm a 2nd Year Student and we're currently studying Java. I'm quite confused on how to do the two on the title especially here in the exercise that was provided for us. Hoping to get inputs and help. Thank you!
Question: Create an interface named Comparison whose method can be used to compare two
Time objects. The methods will include isGreater, isLess, and isEqual. Create another class that will implement these methods.
My code so far:
import java.util.*;
interface Comparison {
boolean isGreater(Time x, Time y);
boolean isLess(Time x,Time y);
boolean isEqual(Time x, Time y);
}
public class Time implements Comparison {
int am, pm;
public boolean isGreater(Time x, Time y) {
if (am > pm) {
System.out.print("True");
}
else
System.out.print("False");
}
public boolean isLess(Time x,Time y) {
if (am < pm) {
System.out.print("True");
}
else
System.out.print("False");
}
public boolean isEqual(Time x, Time y) {
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Enter your first number: ");
int x = new Time();
System.out.println("Enter your second number: ");
int y = new Time();
}
}
thank you for your help!

if I correctly understand your query that you are trying to compare 2 different values of time if it is the only case then please refer the below code else please explain bit more about your requirement so i could correct the source code to help you.
as per your source code AM and PM are unrelated with time. we can pass time in 2 ways.
create own time class and used it.
use dateTime/Date/calendar classes which provide time values.
Step : 1 => create Main class.
Step : 2 => create an interface outside the class. make time data type to long.
interface Comparison {
boolean isGreater(long xTime, long yTime);
boolean isLess(long xTime, long yTime);
boolean isEqual(long xTime, long yTime);
}
Step :3 => create a TimeManager[anyname] class to implement comparison interface. implement the interface methods.
class TimeManager implements Comparison {
#Override
public boolean isGreater(long xTime, long yTime) {
return xTime > yTime ? true : false;
}
#Override
public boolean isLess(long xTime, long yTime) {
return xTime < yTime ? true : false;
}
#Override
public boolean isEqual(long xTime, long yTime) {
return xTime == yTime ? true : false;
}
}
Step :4 => write calling statement into main method and pass time using date object from java.utils
public static void main(String[] args) {
System.out.println("Enter your first number: ");
long x = new Date().getTime();
System.out.println("Enter your second number: ");
long y = new Date().getTime();
}
i hope this would help you.

Java compiler does not allow 2 public outer(top level) classes in the same java file
If a java file has a top level public class, then the file name should match the top level public class name
the comparison of am and pm seems unrelated to Time as per the sample code
in real code, Time references need to be checked for null values
A method with return type boolean should return a boolean value
Sample code
public boolean isGreater(Time x, Time y) {
if (x == null && y == null) {
return true; // you need to decide whether this is true or false
} else if (x == null || y == null) {
return false;
}
return x.getTime() > y.getTime(); // assumes getTime() returns a number
}

Related

AssertionError - imaginary and real numbers adder

I'm getting error:
java.lang.AssertionError: expected: learning.java.advancedoop2.MyComplex<(2.0+10.0i)> but was: learning.java.advancedoop2.MyComplex<(2.0+10.0i)>
Expected :learning.java.advancedoop2.MyComplex<(2.0+10.0i)>
Actual :learning.java.advancedoop2.MyComplex<(2.0+10.0i)>
I'm now working on MyComplex Class like shown on 3.1:
http://www.ntu.edu.sg/home/ehchua/programming/java/J3f_OOPExercises.html#zz-2
Here's a part of the code that's relevant:
package learning.java.advancedoop2;
public class MyComplex {
private double real = 0.0;
private double imag = 0.0;
public MyComplex() {
}
public MyComplex add(MyComplex right) {
this.imag += right.imag;
this.real += right.real;
return this;
}
}
I tried to make tests, and when I ran them, error that I've got is upside, here's part of my test code:
#Test
public void add() {
MyComplex myComplexFirst = new MyComplex(1, 5);
MyComplex myComplexSecond = new MyComplex(1, 5);
MyComplex myComplexThird = new MyComplex(myComplexFirst.getReal() + myComplexSecond.getReal(), myComplexFirst.getImag() + myComplexSecond.getImag());
myComplexFirst.add(myComplexSecond);
MyComplex newComplex = myComplexFirst;
assertEquals(newComplex, myComplexThird);
}
Did you override the equals method in your custom class ?
If you didn't, the default behavior is to compare the references. That would explain the error message you get.
It is confusing because you have overriden the toString method which displays both instances to have the same values.
You need to override the equals method so that java knows how to compare two MyComplex Objects. Right now it doesn't know that you want to compare the objects based on the real and imag values.
#Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
// Check if o is an instance of MyComplex
if (!(o instanceof MyComplex)) {
return false;
}
// typecast o to MyComplex so that we can compare data members
MyComplex c = (MyComplex) o;
// Compare the data members and return accordingly
return Double.compare(real, c.getReal()) == 0
&& Double.compare(imag, c.getImag()) == 0;
}

java program with methods and boolean

import java.util.Scanner ;
public class ProcessNumbers
{
public static void main( String[] args )
{
Scanner in = new Scanner(System.in) ;
System.out.print("Please enter an integer between 6 and 12, inclusive: ") ;
int num = in.nextInt() ;
boolean result = shouldProcess(num);
String result1 = String.valueOf(result) ;
}
public static boolean shouldProcess(int n)
{
if (n>=6 && n<12)
{
return true;
}
else
{
return false;
}
}
public static boolean processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
return result2 ;
}
}
now I am getting the output which is partially right but has forgot the yes or no output in the second method
Please enter an integer between 6 and 12, inclusive:
when it should also include the yes or not output
You are sending in a boolean value in the method parameter of processInput but you are catching it as a String. You need to change it to boolean. Further, you want to check if its value is true with equal signs like below:
public static void processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
}
EDIT 2:
Also, you need to change String result1 = String.valueOf(result); to processInput(result);
EDIT 3:
If you want the number printed too that you just entered and then you want a "yes" or "no", then between int num = in.nextInt(); and boolean result = shouldProcess(num);, add this line: System.out.println(num);
There's apparently some code missing, so I'm guessing this is just part of the full thing. So I will only tackle your output issue.
I won't talk about the code in: public static boolean processInput(boolean result2), because you're not running it anywhere in your main method public static void main( String[] args ) anyway.
Now, in your code at:
public static boolean shouldProcess(int n)
if you look at your code, you are assigning the value of the boolean to the new String result1, so result1 now has the new value, but you are not running its output anywhere, so there's no way the program can guess you want to output that value. You need to assign the output:
System.out.print(result1);
However, if you only want to output the boolean, there's no need to assign that boolean value to a new String and then output the new String, you could just:
System.out.print(result);
Unless you're going to use that value somewhere else where creating a new variable would arguably be a good choice.
Also, it seems you want to return either a "Yes" or "No" on your class: public static boolean processInput(boolean result2).
Remember a class that does not return a value, but rather executes a code, has to be written as void. In other words, your:
public static boolean processInput(boolean result2)
should really be:
public static void processInput(boolean result2)
Because if not, you are just making your program return result2;, which in this case can only be either true or false. By adding void to the class, makes the class understand it will be executing your System.out.print code, rather than returning a value for you to use. But also, depends on what you want to afterwards.

Turning a for loop to recursive method for prime numbers

I need to convert the code below to a recursive method without using global variables and using only one parameter.I Searched the topics already there is no code with one parameter and doesnt use the global variables.
public boolean isPrime(int x){
for(int i=2;i<x;i++)
if(x%i==0) return false ;
return true;
}
Ok, as for your requirements:
Without using global variables.
Using only one parameter.
And, based on:
it come up in one of my university exams
There a couple of aspects to take into account:
If you pass an instance of a Class you are passing only one variable, and as Classes can have multiple variables inside...
They do not state if you can call multiple functions inside, so, again, this is a hint or clue, of what can you do. So, two solutions for you:
Solution 1 (Using Classes)
class RecursVar {
int x;
int i = 2;
RecursVar(int x) {
this.x = x;
}
}
public boolean isPrimeRecurs(int x){
return isPrime(new RecursVar(x));
}
boolean isPrime(RecursVar recursVar) {
if(recursVar.x % recursVar.i == 0)
return false;
if (++recursVar.i >= recursVar.x)
return true;
return isPrime(recursVar);
}
Solution 2 (Cleaner approach without using Classes but based in that the function that can have only one parameter is isPrime )
boolean isPrime(int x) {
return checkForPrime(x, 2);
}
boolean checkForPrime(int x, int i) {
if (i >= x) return true;
if (x % i == 0) return false;
return checkForPrime(x, ++i);
}
Again, this solutions are based on that many exams require a little creativity and maybe that was the aim of this case.
This cases should not be used in production, they are slow and
prune to make honor to this site (StackOverFlow) with a sweet
java.lang.StackOverflowError
It's an interesting problem.
If you can use java 8, you can solve the problem as followed (note that the case isPrime(2) needs to be checked with an additional if condition):
package test;
import java.util.function.Function;
public class Test {
public static void main(String[] args) {
System.out.println(isPrime(13));
}
private static Function<Integer, Boolean> fun;
public static boolean isPrime(int x) {
fun = i -> {
if (i > 2) return (x%i != 0) && fun.apply(i-1);
else return (x%i != 0);
};
return fun.apply(x-1);
}
}
One of my schoolmates' topic accually recieve a solution here it is if you interested its quite brilliant
https://stackoverflow.com/questions/35660562/finding-prime-numbers-recursively-with-using-only-one-parameter?noredirect=1#comment59001671_35660562

Need help getting my Java Rock-Paper-Scissors game to compile [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been trying to get this code to work for the past week now, and every time I make one change I end up with more bugs. Can anyone help figure out where I've gone wrong?
The code is split up into two files: a runner class, and a class with all the methods.
import java.util.Scanner;
import static java.lang.System.*;
public class RPSRunner
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String response = "";
String player = "";
RockPaperScissors game = new RockPaperScissors();
System.out.print("What is your name? : ");
player = keyboard.next();
out.print("type in your prompt [R,P,S] :: ");
response = keyboard.next();
game.setPlayers();
game.convertUserInput(response);
game.setPlayerChoice(response);
game.computerThink();
game.determineWinner();
}
}
The method class:
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Random;
public class RockPaperScissors
{
private String playerName; //used to set player's name
private int playChoice; //player's choice as a number
private int compChoice; //computer's choice as a number
private int playerNumber;
Random rand = new Random(); //allows useage of random methods
public RockPaperScissors()
{
//sets everything to null, prepare for incoming calculations
playerName = "";
}
public RockPaperScissors(String player)
{
playerName = player;
}
public void setPlayers(String player)
{
//good ol mutator method
playerName = player;
}
public String convertUserInput(String response)
{
//Convert R, P, S to integer using switch case
//If invalid input, set to -1
switch(response) {
case "R": playChoice = 0;
break;
case "P": playChoice = 1;
break;
case "S": playChoice = 2;
break;
default: playChoice = -1;
}
}
public boolean setPlayerChoice(String response)
{
//TODO set playChoice to convertUserInput
//return (playChoice != -1)
playChoice = convertUserInput(response);
return(playChoice != -1);
}
public int computerThink()
{
//Use Math.random from 0-2 inclusive
//return it all in one statement so
//return Math.random(whatever);
return rand.nextint(2);
}
public String determineWinner()
{
String winner="";
compChoice = computerThink();
switch(compChoice) {
case 0:
if(playChoice == 1){
winner = playerName;
} else if(playChoice == 2) {
winner = "Computer";
} else if(playChoice == 0) {
winner = "Tie";
}
case 1:
if(playChoice == 1) {
winner = "Tie";
} else if(playChoice == 2) {
winner = playerName;
} else if(playChoice == 0) {
winner = "Computer";
}
case 2:
if(playChoice == 1) {
winner = "Computer";
} else if(playChoice == 2) {
winner = "Tie";
} else if(playChoice == 0){
winner = playerName;
}
} //closes the switch
return winner;
}
}
This is my first major program, so I apologize for any glaring errors or incorrectly-interpreted concepts. I think my major issue lies in the return types, but I'm not positive.
Looking through your code, it is a bit of a mess, so I'll go through step by step.
game.setPlayers();
game.convertUserInput(response);
game.setPlayerChoice(response);
game.computerThink();
game.determineWinner();
You call ALL of these, yet some have return types and are called in previous functions already. For example, convertUserInput.
Your convertUserInput function sets the playChoice variable, declares it returns a String but actually returns nothing. This is called with your clump of functions above, but is then also called by setPlayerChoice, which replaces the playChoice set in the call with, well, nothing. Because nothing is returned you get a compile error.
computerThink returns an int, but you call it above without setting the returned value to anything, then determineWinner is called, which WOULD work had it not been for the above problems.
There is quite a bit wrong with your code. A few obvious ones: you have parameterized your setPlayers method of the RockPaperScissors class to accept a string, but when you invoke it, you dont provide any value, thats a compile time issue. In the RockPaperScissors class you have a method convertUserInput whose method signature says it will return a string, but there are no code paths which return a value in that method. I would do a few more simple tutorials to try to wrap your head around basic OOP concepts then come back to this once you understand basic stuff like, What is an Object? What is a method signature? and most importantly, read and interpret the compile time errors.
It's a little strange that you know your problem lies with the return types but don't know how to fix it. Are you just reading the error message but don't know what its actually saying?
The return type is declared in the first line of a method, the method declaration. The method is expected to return the return type or you will receive a compile-time error.
Some Examples
//these are method declarations
// the return type is before the name of the method
public void setPlayers(String player) {} //return type "void" - this method should not return anything
public String convertUserInput(String response) { // return type "String" - this method NEEDS to return a String
return "A String";
}
Matching method calls
//You need to match the return type with how you call the method
String myPlayers = setPlayers("player"); //WON'T COMPILE - setPlayers returns void, not String
setPlayers("player"); // this is okay, nothing is returned, return type void
String convertedInput = convertUserInput("response"); // this is okay, return type String, which is what convertedInput will be.
convertUserInput("response"); // this is also okay, even though it returns a String we don't have to assign it to a variable. Though in this example calling the method like this is pretty much useless.
int convertedInput = convertUserInput("response"); //WON'T COMPILE - convertUserInput returns String, not an int.

How do I go about writing a loop that's supposed to be boolean yet the answer can be an integer using JOptionPane?

How do I go about writing a loop that's supposed to be boolean, yet the answer can be an integer using JOptionPane?
boolean promptMenu( int menu )
This will represent the core of your code.
Should be in the body of a loop inside main().
Returns true if it should continue running.
Returns false if it is time to quit.
Notice that promptMenu takes in an int parameter:
0 - Prints the Main Menu.
So far this is what I got:
import javax.swing.JOptionPane;
public class BankSystem {
//Fields
static boolean question = true;
static String q ;
static int qt;
//Methods
public static void main(String[]args)
{
while(question = true)
{
promptMenu (qt) ;
}
}
static int promptMenu( int qt )
{
q = JOptionPane.showInputDialog ("Gen's Bank" + "\n \n Print main menu? 0-> YES\n\n") ;
qt = Integer.parseInt(q);
if (qt != 0)
{
question = false;
}
return (qt);
}
}
If you press anything that isn't 0 it still loops. Any Suggestions would help.
Read the question carefully. The question asks you for a method:
boolean promptMenu( int menu )
What you have written is a different method:
int promptMenu( int menu )
You instructor wants you to write a method returning a boolean but you are writing a method that returns an int. You are not answering the question that was asked.
To return a boolean you need:
return true;
return false;
or something like:
boolean boolVar;
boolVar = // Your code here.
return boolVar;
What you got:
public static void main(String[]args)
{
while(question = true)
{
promptMenu (qt) ;
}
}
What you need:
public static void main(String[]args)
{
while(question == true)
{
promptMenu (qt) ;
}
}
If you want to check conditions you have to use one of the following parameters (<, <=, >, >=, !=, ==). One single = is used to assign values to a variable.

Categories

Resources