Eclipse is giving me the static referencing a non-static object error when I try to call isOdd() from Number.java but since isOdd() doesn't contain any arguments, I can't call the outside method as I usually would.
NumberAnalyzer.java
import java.util.ArrayList;
import java.util.Scanner;
import com.sun.xml.internal.ws.api.pipe.NextAction;
import static java.lang.System.*;
public class NumberAnalyzer
{
private ArrayList<Number> list;
public NumberAnalyzer()
{
}
public NumberAnalyzer(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
System.out.println(list);
}
public void setList(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
}
public int countOdds()
{
int oddCount=0;
for(int i = 0; i < list.size(); i++){
if(Number.isOdd()== true){
oddCount++;
}
}
return oddCount;
}
public int countEvens()
{
int evenCount=0;
return evenCount;
}
public int countPerfects()
{
int perfectCount=0;
return perfectCount;
}
public String toString( )
{
return "";
}
}
Number.java
public class Number
{
private Integer number;
public Number()
{
}
public Number(int num)
{
number = num;
}
public void setNumber(int num)
{
number = num;
}
public int getNumber()
{
return number;
}
public boolean isOdd()
{
if(number%2==0){
return false;
}
return true;
}
public boolean isPerfect()
{
int total=0;
for(int i = 1; i < number; i++){
if(number%i==0){
total+= i;
}
}
return (number==total);
}
public String toString( )
{
String output = getNumber() + "\n" + getNumber()+ "isOdd == " + isOdd() + "\n" + getNumber()+ "isPerfect==" + isPerfect()+ "\n\n";
return output;
}
}
runner class
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.*;
public class Lab16b
{
public static void main( String args[] )
{
NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
//add more test cases
}
}
You seem to have list global. Just do
for(int i = 0; i < list.size(); i++){
if(list.get(i).isOdd()){
oddCount++;
}
}
That way you're actually getting a Number from list and can call the isOdd() method.
Note that you don't need the == true check.
Number.isOdd applys to a Number instance. As your for loop is covering the range of indices for the List (list) of Numbers, you can replace
if (Number.isOdd() == true) {
with
if (list.get(i).isOdd() == true) {
or better
if (list.get(i).isOdd()) {
Related
I have an entity that has as children several lists of objects that, although they have different classes, all have the order attribute, in several parts I end up with repeated code, for example in one part I need to order the lists by that attribute and I cannot simplify because they are of different type.
The relevant part of the entity is this:
contenido={
"educaciones":[
{
...
"orden":0
},{
...
"orden":1
}
],
"experiencias":[
{
...
"orden":0
},{
...
"orden":1
}
]
},
...
The code I would like to simplify:
if(tipo.equals("experiencias")){
List<Experiencia> iterable=contenido.getExperiencias();
for(int i = 0; i < iterable.size(); i++){
iterable.get(i).setOrden( orden.get(i) ); //orden = [0,3,5,...]
}
iterable.sort((it1,it2)-> it1.getOrden().compareTo(it2.getOrden()));
}else if(tipo.equals("educaciones")){
List<Educacion> iterable=contenido.getEducaciones();
for(int i = 0; i < iterable.size(); i++){
iterable.get(i).setOrden( orden.get(i) );
}
iterable.sort((it1,it2)-> it1.getOrden().compareTo(it2.getOrden()));
}else if...
Is there a way to create a code that is more generic and supports different objects?
Create an interface for the methods that are common between all you classes:
interface HasOrden {
int getOrden();
void setOrden(int i);
}
Each of your classes needs to implement HasOrden.
Then you can declare sortOrden function:
import java.util.ArrayList;
import java.util.List;
interface HasOrden {
int getOrden();
void setOrden(int i);
}
class Experiencia implements HasOrden {
private final String name;
int orden;
public Experiencia(String name) {
this.name = name;
}
#Override
public int getOrden() {
return orden;
}
#Override
public void setOrden(int i) {
orden = i;
}
public String toString() {
return name;
}
}
public class Eg {
static void sortOrden(List<? extends HasOrden> l, List<Integer> order) {
if (l.size() != order.size()) {
throw new RuntimeException("length mismatch");
}
for (int i = 0; i < l.size(); i++) {
l.get(i).setOrden(order.get(i));
}
l.sort((it1,it2)-> Integer.compare(it1.getOrden(), it2.getOrden()));
}
public static void main(String[] args) {
List<Experiencia> items = new ArrayList<>(List.of(new Experiencia("a"), new Experiencia("b")));
List<Integer> order = List.of(2,1);
sortOrden(items, order);
System.out.println(items);
}
}
You can call sortOrden on any list of HasOrden instances.
you can try to create a List<?> - list with a dynamic type outside of your if else block and move your duplicated code outside too and at the end of the if else block. In addition, you have to create a common class or some interface for your classes, which holds all the common field you needed
public class Main {
public static class Something {
private Integer sth;
public Integer getSth() {
return sth;
}
public void setSth(Integer sth) {
this.sth = sth;
}
}
public static class ThisClass extends Something {
private Integer num;
public ThisClass(Integer num) {
this.num = num;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
}
public static class ThatClass extends Something {
private String str;
public ThatClass(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setNum(String str) {
this.str = str;
}
}
public static List<? extends Something> sortList(Class<?> itemClass, List<? extends Something> list)
throws Exception {
for(int i = 0; i < list.size(); i++){
list.get(i).setSth(i);
}
list.sort((it1,it2)-> it1.getSth().compareTo(it2.getSth()));
return list;
}
public static void main(String[] args) {
System.out.println("Hello World");
List<? extends Something> someList = new ArrayList<>();
boolean check = true;
if(check) {
someList = Arrays.asList(new ThisClass(1),new ThisClass(1),new ThisClass(1),new ThisClass(1));
} else {
someList = Arrays.asList(new ThatClass("a"), new ThatClass("a"),new ThatClass("a"),new ThatClass("a"));
}
try {
someList = sortList(ThisClass.class, someList);
for(int i = 0; i < someList.size(); i++){
System.out.println(someList.get(i).getSth());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is what I've written so far, how do I implement prime_check into prime_array? I'm a beginner so it'd be helpful if you could keep it simple.
The question -
Write a Java function that takes as input a dynamic list and returns a dynamic list of prime numbers (you need to implement the function prime_check(int num)).
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class notes {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList <Integer> listA2=new ArrayList<Integer(Arrays.asList(5,6,7,8,10,13,17,19,20,26,12,31));
System.out.println(prime_array(listA2));
}
public static boolean prime_check(int num) {
boolean primecheck = true;
if(num <= 1) {
primecheck = false;
return primecheck;
}
else {
for (int i = 2; i<= num/2; i++) {
if ((num % i) == 0) {
primecheck = false;
break;
}
}
return primecheck;
}
}
public static ArrayList<Integer> prime_array(ArrayList<Integer> listA2) {
ArrayList <Integer> nums1=new ArrayList<Integer>();
for (int n1: listA2) {
System.out.println(prime_check(n1));
if ( = true) {
nums1.add(n1);
}
}
return nums1;
}
}
You were very close to a solution. Try with this:
public static List<Integer> prime_array(List<Integer> listA2) {
ArrayList <Integer> nums1=new ArrayList<Integer>();
for (int n1: listA2) {
if (prime_check(n1) == true) {
nums1.add(n1);
}
}
return nums1;
}
I'm doing an exercise, in which I have to create the method add, however due to p and v being defined as objects, I'm having a hard time figuring out how I can define this method in the syntax I've been given in the exercise (I'm only allowed to change the methods).
I would like to add the two inputs 5 and 17 so that it returns 22. I've done a lot of research into other questions where I've seen them write it as Positiv(p + v) but this doesn't quite work.
public class Positiv {
public static void main(String[] args) {
try {
Positiv p = new Positiv(5);
Positiv v = new Positiv(17);
p.add(v);
System.out.println(p.get());
} catch (Exception e) {
e.printStackTrace();
}
}
private int n;
public Positiv(int n) {
if (n < 0) { throw new IllegalArgumentException("exception");
}
this.n = n;
}
public static Positiv add(Positiv v)
{
return new Positiv(n + v);
}
public int get() {
return n;
}
}
In your add method:
public static Positiv add(Positiv v)
{
return new Positiv(n + v);
}
You return a whole new Positiv object. However (correct me if I'm wrong) it looks as if you just want to add the two n fields. You can do this by adding this.get to v.get:
public void add(Positiv v)
{
this.n += v.get();
}
Which will return 22
Tutorial for this
public class HelloWorld{
public static void main(String []args){
Numbers a = new Numbers(5);
Numbers b = new Numbers(10);
int num1 = a.getN();
int num2 = b.getN();
System.out.println(addTwoNumbers(num1, num2));
}
public static int addTwoNumbers(int a, int b) {
return a + b;
}
}
class Numbers {
private int n;
public Numbers(int n) {
this.n = n;
}
public int getN() {
return n;
}
}
Eclipse keeps informing of an error when I try to implement a counter for a number of instances when called by the constructor. I've been searching on the matter, but the solutions are the exact thing eclipse won't let.
The problem is in Student() { count++; } in the subclass.
Implicit super constructor Dosije() is undefined. Must explicitly invoke another constructor
Main file
import java.util.Scanner;
public class TestDosije {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String jmbg=null;
System.out.println("ime osobe: ");
String ime= in.next();
System.out.println("prezime osobe: ");
String prezime= in.next();
System.out.println("jmbg: ");
while(!(Dosije.jesteJMBG(jmbg =in.next()) )) {
}
String ime_prezime= ime + " " + prezime;
Dosije dosije = new Dosije(ime_prezime, jmbg);
System.out.println(dosije.toString());
System.out.println("broj indeksa: ");
int index= in.nextInt();
System.out.println("godina upisa: ");
int upis= in.nextInt();
System.out.println("studije: ");
int studije= in.nextInt();
Student student = new Student(dosije, index, upis, studije);
System.out.println(student.toString());
System.out.println(student.getCount());
}
}
The superclass
public class Dosije {
private String ime_prezime;
private String jmbg;
public Dosije(String ime_prezime, String jmbg) {
this.ime_prezime=ime_prezime;
this.jmbg=jmbg;
}
public Dosije(final Dosije d) {
ime_prezime=d.ime_prezime;
jmbg=d.jmbg;
}
public String getImePrezime() { return ime_prezime; }
public void setImePrezime(String ime_prezime) { this.ime_prezime= ime_prezime;}
public String getJMBG() { return jmbg; }
public void setJMBG(String jmbg) { this.jmbg= jmbg;}
public String toString() {
return ime_prezime + "\njmbg: " + jmbg;
}
public static boolean jesteJMBG(String jmbg) {
if(jmbg.length() != 13) {
System.err.println("jmbg ima 13 cifara");
return false;
}
for(int i=0;i < jmbg.length(); i++) {
if(!(Character.isDigit(jmbg.charAt(i))) ) {
System.err.println("jmbg nije broj!");
return false;
}
}
return true;
}
}
The subclass of which instances I'm trying to count
public class Student extends Dosije{
private int br_index;
private int god_upis;
private int profil_studija;
private static int count=0;
Student() {
count++; //the devil himself
}
public Student(final Dosije d, int index, int upis, int studije){
super(d);
br_index=index;
god_upis=upis;
profil_studija=studije;
}
public Student(final Student s) {
super(s);
br_index=s.br_index;
god_upis=s.god_upis;
profil_studija=s.profil_studija;
}
public void setProfil(int n) {profil_studija=n;}
public int getCount() { return count; }
public String Studije(int i) {
if(i == 0)
return "Osnovne";
else if(i == 1)
return "MSc";
else
return "PhD";
}
public String toString() {
return super.toString() + "\n" + "broj indeksa: " + br_index + "/" + (god_upis % 100) + "\n"
+ "studije: " + Studije(profil_studija);
}
}
Your Student() constructor doesn't pass compilation since the super class doesn't have a parameterless constructor, so the implicit call to super(); added by the compiler doesn't pass compilation.
You can add a public Dosije() {} constructor to prevent that compilation error.
However, you might want to increment count in the other Student constructors too, in order to count the total number of instances created, regardless of which constructor was used.
Really new to java wanted to make my separate sorting methods (they all work hopefully i did them right)
Also very new to objects and constructors hopefully what im talking about is an object
so here are the constructors
public class sort{
public int[] selectsort(int[] num)
{
int j,i,key,min;
for(j = 0; j<num.length; j++)
{
key = num[j];
min = j;
for(i=j+1; i<num.length; i++)
{
if(num[i]<num[min])
{
min = i;
}
}
num[j] = num[min];
num[min] = key;
}
return num;
}
public int[] insertsort(int[] num)
{
int j,i,key;
for(j = 1; j<num.length; j++)
{
key = num[j];
for(i=j-1; i>=0 && num[i]>key; i--)
{
num[i+1]=num[i];
}
num[i+1]=key;
}
return num;
}
public static int[] bubblesort(int[] num)
{
int i,j,ini;
for(i = num.length-1; i>1; i--)
{
for(j=0;j<i; j++)
{
if(num[j]>num[j+1])
{
ini = num[j];
num[j]=num[j+1];
num[j+1]=ini;
}
}
}
return num;
}
}
and the program/test
import java.util.Arrays;
public class sorttest{
public static void main(String[] args)
{
int[] num = new int[]{9,1,4,5,6,2,3,7,8};
System.out.println(Arrays.toString(selectsort(num)));
}
}
javac sort.java compiles but javac sorttest.java doesnt
error:
sorttest.java:9: cannot find symbol
symbol : method selectsort(int[])
location: class sorttest
System.out.println(Arrays.toString(selectsort(num)));
^
1 error
The method selectsort is not a part of the sorttest class - it's a public static method in the sort class. This means you need to qualify it by its class name:
import java.util.Arrays;
public class sorttest{
public static void main(String[] args) {
int[] num = new int[]{9,1,4,5,6,2,3,7,8};
System.out.println(Arrays.toString(sort.selectsort(num)));
}
}
Alternatively, you could use a static import:
import static sort.selectsort;
import java.util.Arrays;
public class sorttest{
public static void main(String[] args) {
int[] num = new int[]{9,1,4,5,6,2,3,7,8};
System.out.println(Arrays.toString(selectsort(num)));
}
}