So I have a super class called Factorial and two subclasses called Fibonacci and Arithmetic. In my main super class which I call the method using a polymorphic array from my main class, I have an input box inquiry that I want to only show up once, but instead it shows up multiple times. Is there anyway I can stop this? My main class is called PolyMorphism. I know it's tedious but it's the way I made the program and want it to be :p
public class Polymorphism {
public static void main(String[] args) {
Factorial arrayObject[] = new Factorial[3];
arrayObject[0] = new Factorial();
arrayObject[1] = new Fibonacci();
arrayObject[2] = new Arithmetic();
for(int x=0;x<arrayObject.length;++x){
arrayObject[x].sequence();
}
public class Factorial extends JFrame {
//this input box shows up 3 times when I launch.
public final String valueInput = JOptionPane.showInputDialog("Please enter a number between 1 and 20.");
public void sequence(){
System.out.println("Factorial:");
System.out.println(fact(Integer.valueOf(valueInput)));
public static long fact (int n){
if (n <= 1){
return 1;
}else
return n * fact(n-1);
}
public class Fibonacci extends Factorial {
public void sequence(){
int inputValue = Integer.parseInt(valueInput);
System.out.println("Fibonacci Sequence");
/**for (int value = 0; value < inputValue; value++){
System.out.println(fibonacciSequence(value));
} **/
System.out.println(fibonacciSequence(inputValue));
}
public static long fibonacciSequence(int v) {
// TODO Auto-generated method stub
if(v == 0) {
return 0;
}else if (v <= 2){
return 1;
}
long fibonacci = fibonacciSequence(v - 1) + fibonacciSequence(v-2);
return fibonacci;
}
}
The comment with the problem is under the Factorial class, and disregard the JFrame for now.
In your Factorial class, you have this:
public final String valueInput = JOptionPane.showInputDialog("Please enter a number between 1 and 20.");
Which means every time you create an instance of it or a subclass, that input dialog will pop up.
The answer is: Don't do that.
Put it in a method and call the method when you want the input dialog to show.
Each Factorial instance (of which you have three) has its own valueInput property, so the behavior is as expected. You could make this field static (and therefore shared), but it's still not clear what you're trying to accomplish.
It's most likely the case that you should be separating the input display from the Factorial implementation entirely.
Related
I am calling a method from another class. The method contains an integer array. I am trying to stay away from inputting the index manually.
I am trying to search for numbers within a range.
example:
ArrayList: {1,5}, {5,10}, {10,15}
Input: enter 3
Process: search for number within range
output: 1,5
The driver class is storing the objects from the main class called Numbers into ArrayList. The main class have an accessor call getNumbers. getNumbers contains an integer array with 2 elements. The driver is calling getNumbers to validate the entry that users input.
The code below works but I'm told it's consider bad coding to code entering the indexes. I want to know how to output the array from getNumber method without knowing the array length of getNumber?
example of what I have:
for(int i = 0; i < example.size(); i++)
//number is the integer that is inputted.
if(example.get(i).getNumbers()[1] > number &&
example.get(i).getNumbers()[0] <= numbers)
System.out.println(example.get(i));
Should I add another for loop?
example of what I am thinking of:
for(int i = 0; i < example.size(); i++)
for(int j = 0; j < example.get(i).getNumbers.length; j++){
if(example.get(i).getNumbers()[j] > number &&
example.get(i).getNumbers()[j] <= numbers)
System.out.println(example.get(i));
}
}
Edit: Changed how I worded some things and fixed the code of what I think I should do.
The code below works but I'm told it's consider bad coding to code
entering the indexes. I want to know how to output the array from
getNumber method without knowing the array length of getNumber ?
If you don't want to do the validations with array indexes for your first element and second element in the array, then you can solve the problem by modifying your Numbers class as shown below:
(1) Define two int variable members (currently you have only one)
(2) Add a method isInLimits(int input) to validate the range
(3) Override toString() which can be used to print the object as String
Numbers class (modified):
public static class Numbers {
private int firstElement;
private int secondElement;
public int getFirstElement() {
return firstElement;
}
public void setFirstElement(int firstElement) {
this.firstElement = firstElement;
}
public int getSecondElement() {
return secondElement;
}
public void setSecondElement(int secondElement) {
this.secondElement = secondElement;
}
//checks the input is in the range of this object elements
public boolean isInLimits(int input) {
if(input >= firstElement && input < secondElement) {
return true;
} else {
return false;
}
}
#Override
public String toString() {
return "{"+firstElement+","+secondElement+"}";
}
}
Usage of Numbers Class:
public static void main(String[] args) {
int userInput = 10; //get it from user
List<Numbers> example = new ArrayList<>();
//Add Numbers objects to example list
for(int i=0;i< example.size();i++) {
Number numberTemp = example.get(i);
//call Numbers object's isInLimits
if(numberTemp.isInLimits(userInput)) {
System.out.println(numberTemp);
}
}
}
I have an assignment that tells me to do the following:
Create a method named IsPrime(), which accepts a positive integer as a parameter. If a number if prime, the method should return true. (A prime number is evenly divisible only by 1 and itself). Incorporate this method into a class named MyMathMethods. Create a main() method in a separate class called MainFile, which will test IsPrime() by asking the user for a number using an input dialog and will then report whether that number is prime or not.
How do I connect these two files?
here is my code:
package x;
import java.util.Scanner;
public class MyMathMethod
{
public static boolean isPrime(int num)
{
int result=0;
System.out.println("enter no");
Scanner s = new Scanner(System.in);
num =s.nextInt();
long sqrt = (int) Math.sqrt(num);
for(long divisor = 2; divisor <= sqrt; divisor++)
{
if(num % divisor == 0)
{
// This only needs to happen once
// for this number to NOT be prime
return false;
}
}
// If we get here, the number is prime.
return true;
}
}
Another File is
import x.*;
package y;
public class MainFile {
public static void main(String [] args) {
boolean isNumberPrime;
int num;
MyMathMethod methods = new MyMathMethod();
isNumberPrime = methods.isPrime(num);
{
if(num=true)
System.out.println(num + " is Prime Number");
else
System.out.println(num + " is not Prime Number");
}
}
}
Thanks in advance.
Do you want to call the method isPrime() from your main in another class?
When they're a in the same package, you have to create a new instance of your class MyMathMethods and call the method isPrime(). when they're in different class, you must import the missing class and do the same as above. If you don't import it manually, probably your IDE will do it for you or ask for it.
the first file:
package x;
public class MyMathMethods {
public boolean isPrime(int number) {
//your code here
return false;
}
}
the second:
package y;
import x.* //importing all files from the package x
//if your class MyMathMethods is in the same package, you don't need that
public class MainFile {
public static void main(String [] args) {
int number = 20;
boolean isNumberPrime;
MyMathMethods methods = new MyMathMethods();
isNumberPrime = methods.isPrime(number); //here the result if it's prime
}
}
EDIT: I'll try to fix your code.
If you want to have your method static, you can call it:
MyMathMethods.isPrime(numer);
without the need to create a new instace.
The next issue: why are you passing to the funtion a variable that is not initialized (num) and try to get this value from the input in this method? Well, that's not a good practise. I would rather suggest to get the input from the user in main (directly in main on in another function called up in main) and then pass the value to isPrime().
package y;
import x.*
public class MainFile {
public static void main(String [] args) {
int num;
Scanner s = new Scanner(System.in);
num =s.nextInt();
if(MyMathMethods.isPrime(num)) {
//if true, your code;
} else {
//false, your code;
}
}
}
package x;
public class MyMathMethod {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Your algoritm failed for many numbers, e.g. 0, 1, 2. Well, for this values it doesn't even returned any value. Please always protect your method against any possible wrong parameters.
I made a test program because I am trying to get back into Java after working in PL/SQL. I created a class Numbers that contains an integer, a getter and a setter. I have another class Test that is creating an instance of Numbers, and also adds that instance to a List. I created a for loop that loops two times and sets the value of the integer in Numbers equal to i. I then add that instance of Numbers to the List numbersList. I then do a print screen of the value that was added to the List. I do a total of 3 prints, one print the first time through the loop that prints the first position in the List, then I print two times during the second time through the loop,the first position in the List again, and the second position in the List. I was expecting to get 0,0,1 as the result. I am getting instead 0,1,1 as the result and I cannot figure out why. I am not changing anything in the first position in the List (numbersList[0]) during the second time through the loop, all I am doing is adding an instance of Numbers into the second position in the list (numbersList[1]).
import java.util.ArrayList;
import java.util.List;
public class Tests {
static int x;
public static void main(String[] args) {
List<Numbers> numbersList = new ArrayList<Numbers>();
Numbers numbers = new Numbers();
Numbers numbers2 = new Numbers();
for (int i = 0; i < 2; i++) {
if (i == 0) {
numbers.setVariable(i);
numbersList.add(numbers);
System.out.println(numbersList.get(0).getVariable());
}
if (i > 0) {
numbers2.setVariable(i);
numbersList.add(numbers2);
System.out.println(numbersList.get(0).getVariable());
System.out.println(numbersList.get(1).getVariable());
}
}
}
}
public class Numbers {
public static int a = 5;
public static void setVariable(int b) {
a = b;
}
public static int getVariable() {
return a;
}
}
public static int a = 5 means that all instances of Numbers share the same variable because of the static keyword.
Therefore, when you do numbers2.setVariable(i);, the variable is also changed for numbers. Hence the 0,1,1
If you want instance variables remove the static keywords from Numbers.
Your class Numbers has no instance fields (everything is static, or class level).
It should look something like (and overriding toString() is a good idea),
public class Numbers {
public int a = 5;
public void setVariable(int b){
a = b;
}
public int getVariable(){
return a;
}
#Override
public String toString() {
return String.valueOf(a);
}
}
By overriding toString() you can more easily print instances of Numbers. For example,
System.out.println(numbersList);
It's a requirement of my school assignment that I use "this" in the following program. However, I can't quite figure out where I could put this. I keep getting a "non-static variable this cannot be referenced from a static context" error.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String args[])
{
System.out.println("Enter the upper limit for the prime numbers computation: ");
int upperLimit = new Scanner(System.in).nextInt();
int count = 0;
for(int number = 2; number<=upperLimit; number++)
{
if(isPrime(number))
{
System.out.println(number);
count++;
}
}
System.out.println("Number of primes generated: " + count);
}
public static boolean isPrime(int number)
{
for(int i=2; i<number; i++)
{
if(number%i == 0)
{
return false;
}
}
return true;
}
}
The Java keyword this refers to the instance of your class that invoked an instance method. A static method is general to its class, and so you cannot reference any instance (non-static) variables from within it. You can only access instance variables like this from within an instance method, that is, a method that is not defined as static.
So, you would need to create an instance method (of which there are none in your class), in order to use this.
This is nothing more than a reference to the object on which the method was called. Static methods on the other hand can operate without any instance of the class even exisiting, therefore they can't have reference to any object. That's why you can't use this in static method. If you really need this, you have to remove static keywords from your functions and use instance variables in those functions anyhow.
public class PrimeNumber
{
public int count = 0;
public int upperLimit;
public static void main(String args[])
{
PrimeNumber pn = new PrimeNumber();
System.out.println("Enter the upper limit for the prime numbers computation: ");
pn.upperLimit = new Scanner(System.in).nextInt();
pn.doCheck();
System.out.println("Number of primes generated: " + pn.count);
}
public void doCheck() {
for (int number = 2; number <= this.upperLimit; number++)
{
if (this.isPrime(number))
{
System.out.println(number);
count++;
}
}
}
public boolean isPrime(int number)
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
}
I have a class in java for methods. Basically this class receives an array of integer numbers, adds the numbers & subtracts them too, returns the sum and the subtraction. I declared the variables at the top (not in a particular method). When the subtraction and the addition are done they're assigned to their respective variables (automatically, of course), BUT when the method is finished doing its job the values are deleted, so when I call a method of the subtraction/addition the result is a 0.
As far as I know the values shouldn't be empty because they're not initialized inside a method but outside all methods, so the scope shouldn't have ended. Any help, please ?
//Class of the methods
package chap3;
import javax.swing.JOptionPane;
/**
*
* #author jtech
*/
public class SimpleArithmeticMethods
{
int sum;
int subtraction;
public void sum_Difference(int[] nums)
{
int[] inpNums = nums;
sum = inpNums[0] + inpNums[1];
subtraction = inpNums[1] - inpNums[0];
}
public void getSum()
{
JOptionPane.showMessageDialog(null,"The sum is: "+sum, "Result.", JOptionPane.INFORMATION_MESSAGE);
}
public void getDifference()
{
JOptionPane.showMessageDialog(null,"The difference is: "+subtraction, "Result.", JOptionPane.INFORMATION_MESSAGE);
}
}
The class from which I run
package chap3;
import javax.swing.JOptionPane;
/**
*
* #author jtech
*/
public class SimpleArithmetic
{
public static void main(String[] args)
{
String[] strInptNums = new String[2];
int[] inptNums = new int[2];
SimpleArithmeticMethods obtainSum = new SimpleArithmeticMethods();
SimpleArithmeticMethods obtainDifference = new SimpleArithmeticMethods();
SimpleArithmeticMethods workSum_Difference = new SimpleArithmeticMethods();
for (int counter = 0; counter <= 1; counter++)
{
strInptNums[counter] = JOptionPane.showInputDialog(null, "Input a number, smallest first", "Input Data.", JOptionPane.QUESTION_MESSAGE);
inptNums[counter] = Integer.parseInt(strInptNums[counter]);
}
workSum_Difference.sum_Difference(inptNums);
obtainSum.getDifference();
obtainDifference.getDifference();
}
}
You're calling the sum_Difference() method on one object, and display the results using another object.
That's like storing a message in a bottle, and then looking if the message is in another bottle. Use the same object to call all three methods.