I've been trying to create a class which determines if a set of integers within an arraylist is a subset of another arraylist.
However, I receive an "error: incompatible types: ArrayList cannot be converted to int" whenever I try to compile and it appears that "return members" is causing it.
Could someone tell me what is wrong with "return members"? Any help would be greatly appreciated.
// Define the Set class
import java.util.ArrayList;
class Set {
private ArrayList<Integer> members;
public Set()
{
members = new ArrayList<Integer>();
}
public int getMembers()
{
return members;
}
public void setMembers()
{
this.members = members;
}
// toString() method
public String toString()
{
return "Set A is a subset of set B.";
}
// Return true if 'this' is a subset of 'set',
// otherwise return false.
public boolean isSubset(Set set)
{
for(int i = 0; i < this.members.size(); i++)
if(!members.contains(this.members.get(i)))
return false;
return true;
}
}
This method is your issue:
public int getMembers()
{
return members;
}
Wrong return type, change it to:
public ArrayList<Integer> getMembers()
{
return members;
}
Also your setMembers() does not do anything, set's itself to itself. It should be changed to:
public void setMembers(ArrayList<Integer> newMembers)
{
this.members = newMembers;
}
you are making mistake in first place.change return type in getMenbers(). you are returning an Object type and you specified it to return an int(primitive).
a typical method can only return the specified type. hope it helps
Related
This is my assignment, I'm working on the step 3:
I need to implement a method called getItems() that takes a boolean value and returns a new ArrayList with items having the property that match the given value.
So far When I print it out it just shows the whole list in the array list, not only the objects having true property.
My code:
import java.util.ArrayList;
public class Shoppinglist9_6_pt2 {
ArrayList<Item> shoppingList = new ArrayList<>();
public Shoppinglist9_6_pt2(ArrayList<Item> shoppingList) {
this.shoppingList = shoppingList;
}
public void showList() {
for ( Item item : shoppingList){
System.out.printf("\nItem:%s Ct:%s", item.getName(),
item.getCt());
}
}
public ArrayList<Item> getItems(boolean gotIt) {
gotIt = true;
for (Item item : shoppingList){
if(item.getGotIt() == gotIt){
showList();
}else{
gotIt = false;
}
}
// Todo: return an ArrayList of item that
// match the gotIt true or false value.
// For example if set to True, then return
// an ArrayList of Item with gotIt=True.
return new ArrayList<Item>();
}}
public class Item {
private String name;
private int ct;
private boolean gotIt;
}
public Item(String name, int ct,boolean gotIt) {
this.name = name;
this.ct = ct;
this.gotIt = gotIt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCt() {
return ct;
}
public void setCt(int ct) {
this.ct = ct;
}
public boolean getGotIt(){
return gotIt;
}
public void setGotIt(boolean gotIt) {
this.gotIt = gotIt;
}
#Override
public String toString() {
return "Item :" +
"name='" + name + '\'' +
", ct=" + ct +
"Got it=" + gotIt;
}
}
This is my main:
public class inClass_Shopping_9_6_pt2 {
public static void main(String[] args) {
Shoppinglist9_6_pt2 sl = new Shoppinglist9_6_pt2();
sl.addItem( "Banana", 6,true);
sl.addItem("Coconut", 2,false);
sl.addItem("Apple", 12,true);
sl.getItems(true);
}
}
Also, you might observe the method gotIt() is grayed out & says parameters can be converted to a local varaible, same with the return. 'Item' in ArrayList<Items> is grayed out and says explicit type argument item can be replaced with <>, but this is the template my professor had sent us, and we need to follow it.
You have the new instance variable, you have the getters and setters, just the getItems method does not yet do the job...
You want to get a list with all the entries of the shopping list that have the attribute gotIt either true or false depending on the gotIt variable. How can you use the gotIt variable to get all the items you want?
Normally one would choose different names for the parameter of getItems, so it doesn't collide with the attributes name
You need to perform the following steps:
create a new ArrayList.
iterate through the sopping list and add each item with gotIt property matches the provided boolean value into the newly created ArrayList.
return the list.
That's how it might look like:
public ArrayList<Item> getItems(boolean gotIt) {
ArrayList<Item> items = new ArrayList<>();
for (Item item : shoppingList) {
if (item.getGotIt() == gotIt) {
items.add(item);
}
}
return items;
}
Note: although according to the assignment requirements you have to use ArrayList as a type in your code, it's not good practice to make the code dependent on concrete implementations. See What does it mean to "program to an interface"?
I know I have join party late, and my answer is not different from Alexandar.
I'm not offering a lot of assistance, still you can try using lambdas.
For instance
public ArrayList<Item> getItems(boolean gotIt) {
ArrayList<Item> items = new ArrayList<>();
shoppingList.forEach(item -> {
if(item.getGotIt() == gotIt) items.add(item);
});
return items;
}
For print,
sl.getItems(false).forEach(System.out::println);
I tried a lot to fix this class but it didn't work. I want to make a hotel(Array) and check and fill it with people defined in another class, but I need to add ,remove, check for empty items and return their indexes using methods inside the hotel class. the problem is when I change the array inside a method I couldn't return the changed value and when I tried adding other class members trying to work it out I ended with indexOutOfboundryException. Could you pleas take a look at the code and tell me if you see the mistakes why I couldn't return the changed value and why I get index out of boundry
Many thanks in advance!
package com.company;
public class Hotel1 {
private int numberOfRooms1; // Number of rooms
private Person[]bookingList1=new Person[numberOfRooms1];// booking list with initial length of the number of rooms
private int uniqueId1;
private Person person1;
private int currentIndex;
private boolean isEmpty=true;
public int getNumberOfRooms1() {
return numberOfRooms1;
}
private Ticket ticket1;
public Hotel1(int numberOfRoomss1) {// The constructor has one attribute which is the number of the rooms
this.numberOfRooms1 = numberOfRoomss1;
}
//check in method
public Boolean isEmpty(){
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
if (!bookingList1[currentIndex].equals(null))
isEmpty=false;
else isEmpty= true;
}
return isEmpty;
}
public int findEmptyRooms(){
if (isEmpty)
{
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
return currentIndex;
}
return currentIndex;
}
return currentIndex;
}
public Person checkIn1(Person person){
if (isEmpty==true){
return bookingList1[findEmptyRooms()]=person;
}
else {
System.out.println("There is no empty rooms");
return null;
}
}
}
Aarrghh so many bugs in few lines...
Sorry to be rude but please review the logic of your code, i don't all understand...
For example :
public int findEmptyRooms(){
if (isEmpty)
{
for (currentIndex=0;currentIndex
}
What this function is supposed to do ?!
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
return currentIndex;
}
Simply always retuns bookingList1.length + 1
(so that's why the call to checkIn1 throws an indexOutOfboundryException)
Another example :
public Boolean isEmpty(){
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
if (!bookingList1[currentIndex].equals(null))
isEmpty=false;
else isEmpty= true;
}
return isEmpty;
}
Is completely buggy, if you have an element in the array with null followed by non null elements, the isEmpty will returns false
I think you should reconsider all your code before posting the question to stack overflow
Thank you all for your answers that help me refactor the whole code and make it better and get it work just in case you want to see how it became just take a look`package com.company;
public class Hotel1 {
private int numberOfRooms1;// number of rooms
Person rooms[];
public Hotel1(int numberOfRooms1){ //the constructor
this.numberOfRooms1=numberOfRooms1;
Person[]rooms=new Person[numberOfRooms1];
this.rooms=rooms;
}
//Private method to check if the array has an empty place
private boolean isEmpty(){
boolean isEmpty =false;
for (int i=0;i<rooms.length;i++){
if (rooms[i]==null){
return true;
}
}
return isEmpty;
}
//Check in
public Person[] checkIn(Person person){
if (isEmpty()){
for (int i=0;i<rooms.length;i++){
if (rooms[i]==null){
rooms[i]=person;
return rooms;
}
else continue;
}
}
else {
System.out.println("There is rooms left for "+person.getFirstName()+" Sorry!");
}
return rooms;
}}
I've been working on trying to implement an immutable set from scratch, so I'm not using HashSet or java.util.Set
I have this method in my Empty class to add an element to an empty set:
public Set<T> add(T x) {
return new Element<T>(x, new Empty<T>());
}
And in another class called Element, I have the following constructor:
public Element(T element, Empty<T> empty) {
assert(element != null);
assert(empty != null);
this.element = element;
this.set = empty;
}
EDIT: here is my other Element constructor used for adding an element to a set.
public Element(T x, Set<T> set) {
this.element = x;
this.set = set;
}
But when I try to add an element it fails and the set is still empty.
I've used a similar code when creating an immutable Binary Search Tree and it worked fine so I assumed that I could do the same but for an immutable Set.
I was just wondering if the problem was with my add method or my constructor
Thank you
The size method:
for the Empty class
/**
* returns number of elements in the set
* #return size - number of elements in the set
*/
public int size(){
return -1;
}
for the element class:
#Override
public int size() {
if (set.isEmpty() == true) {
return -1;
} else {
return set.toList().size();
}
}
the toList() method:
#Override
public List<T> toList() {
List<T> list = new ArrayList<T>();
int i;
for(i = 0; i < set.size(); i++){
list.set(i, element);
}
return list;
}
reading over this part I realise that the problem with returning the size may be from the toList method I wrote, but I don't think that should have an effect on adding an element to the set?
toString - Element Class:
#Override
public String toString() {
return "Set = [" + set + "]";
}
toString - Empty class:
public String toString() {
return "";
}
And the JUnit Test for Add:
EDIT: realised that the set was immutable and so tried to make a new set that was equal to the empty set with the added value - to store the change but kept getting the same NullPointerException error.
#Test
public final void testAdd() {
Set<Integer> set1;
set1 = set.add(1);
int i = 20;
set.add(i);
assertSame("Last element should be the newly added name object", i, set.toList().get(set.size()-1));
assertEquals("Set size should be two", 2, set.size());
}
The assertSame gives a NullPointerException (so I'm guessing this means that the add didn't work and the set is still empty); and if I comment it out to test the next line the assertEquals says that set.size() is -1 (empty)
Almost everything in your existing code is flawed. Your Element's ctor does not make sense, size() and toList() are implemented in weird way, even the unit test is flawed in basic Java.
Some pseudo code
interface Set<T> {
Set<T> add(T v);
int size();
boolean contains(T v);
}
class Element<T> extends Set<T> {
T value;
Set<T> next;
public Element<T>(T element, Set<T> next) {...}
public Set<T> add(T value) {
if contains(value) { // already in set
return this;
}
return new Element(value, this);
}
public int size() {
return next.size() + 1;
}
public boolean contains(T value) {
return (this.value.equals(value) || next.contains(value));
}
}
public class Empty<T> extends Set<T> {
public Set<T> add(T value) {
return new Element(value, this);
}
public int size() {
return 0; // come on! 0 means empty, not -1!
}
public boolean contains(T value) {
return false;
}
}
Having reviewed my code, I realised where I was making the mistake.
Aside from the messy code in other areas, the add(T x) method was not working as expected due to the fact that I did not import the Empty or Element class to the Demo set or the JUnit test and, as mentioned by #shmosel, my toString method wasn't working properly because I did not include the element field and so was not going to output anything.
The following is my Demo code showing how I've added the import line. Furthermore, the constructor for Element works fine too. Again, I just needed to import the class for an Empty set for it to work.
package immutable.set;
import immutable.set.Empty;
public class DemoSet {
public static void main(String[] args) {
Set<Integer> set, set1, set2;
set = new Empty<Integer>();
System.out.println(set.isEmpty());
set1 = set.add(1).add(2);
set2 = set.add(3);
System.out.println(set1.toString());
System.out.println(set1.isEmpty());
System.out.println(set2.toString());
System.out.println(set2.isEmpty());
}
}
And it does print out the expected outcome.
Thank you for you help everyone.
So I'm taking a basic course in Java at university. I'm trying to create a class Bachelorstudents containing an arraylist of class Bachelorstudent (respectively plural and singular of "bachelorstudents" in english) which contains a HashMap of course (key) and marks (value).
My problem is the infamous "non-static method cannot be referenced from a static context".
"Bachelorstudent"-class:
public class Bachelorstudent{
private String navn;
private int studentNummer;
private HashMap<String, Integer> karakterListe = new HashMap<>();
public Bachelorstudent(String navn, Integer studentNummer){
setNavn(navn);
setStudentNummer(studentNummer);
}
public Bachelorstudent(){
}
public void setKarakter(String fagkode, Integer karakter){
karakterListe.put(fagkode, karakter);
}
public HashMap<String, Integer> getKarakter(){
return karakterListe;
}
public int snitt(){
Integer snittKarakter = 0;
int counter = 0;
if(!karakterListe.isEmpty()){
for(Integer karakter : karakterListe.values()){
snittKarakter += karakter;
counter++;
}
}else{
return 6;
}
return snittKarakter /= counter;
}
public int getKarakterer(){
Integer karakterer = 0;
if(!karakterListe.isEmpty()){
for(Integer karakter : karakterListe.values()){
karakterer += karakter;
}
}else{
return 0;
}
return karakterer;
}
public void setNavn(String navn){
this.navn=navn;
}
public String getNavn(){
return navn;
}
public void setStudentNummer(int studentNummber){
this.studentNummer=studentNummer;
}
public int getStudentNummer(){
return studentNummer;
}
}
"Bachelorstudenter"-class:
public class Bachelorstudenter{
private ArrayList<Bachelorstudent> bachelorStudenter = new ArrayList<>();
public Bachelorstudenter(){
}
public void karakterSnitt(){
for(Bachelorstudent bachelorstudenter : bachelorStudenter){
Bachelorstudent student = new Bachelorstudent();
for(Bachelorstudent bachelorstudent : Bachelorstudent.getKarakter()){ //<-- Non-static method error.
}
}
}
public Boolean eksisterer(Bachelorstudent student){
boolean finnes = false;
for(Bachelorstudent bachelorstudent : bachelorStudenter){
if(bachelorstudent.getNavn().equals(student.getNavn())){
finnes = true;
}
}
return finnes;
}
public Boolean nyBachelorstudent(Bachelorstudent student){
if(!eksisterer(student)){
bachelorStudenter.add(student);
return true;
}
else{
System.out.println("Eksisterer i systemet fra før");
return false;
}
}
}
I have tried several things, such as calling an instance of class Bachelorstudent (as seen above), tried inheritance (not sure if I did this right, but what I did didn't work). How can I call on the .getKarakter() method in class Bachelorstudenter?
Edit: Just to clarify. The point of this method is to get the average of every mark of every bachelorstudent. I have a method in Bachelorstudent which does this, but I need the equivalent in Bachelorstudenter, which will find the average of every mark of every course of every student.
You need to use an object to call a non-static method.
In your example, you need to use the object of the current iteration to invoke the method:
for(Bachelorstudent bachelorstudenter : bachelorStudenter){ // Iterate over the bachelorStudenter list.
bachelorstudenter.getKarakter(); // Use the bachelorstudenter of this iteration.
}
In this method I get string as input and according to the string name I need to return value sometimes its string sometime int ,double,int64 ,bool etc
Since its dynamic type i don't know how to define it in the method return type
and how to add to it the value and how to call to this method that the return type is dynamic ,any idea?
public static ? SwitchInput(String TypeName) {
if (TypeName == "java.lang.String" ) {
Return = "A";
}
else if (TypeName == "int" ) {
Return = 1;
}
else if (TypeName == "double") {
Return = 1.00
}
etc for bool and all the other types
}
Object will be your best bet, unless returned type shares an Ancestor
Example :
public static Object switchInput(String typeName) {
if ("java.lang.String".equals(typeName)) {
return "A";
}
else if ("int".equals(typeName)) {
return 1i;
}
else if ("double".equals(typeName)) {
return 1.0d
}
}
Another example with generics
static <T> T switchInput(String typeName){
if ("java.lang.String".equals(typeName)) {
return "A";
}
else if ("int".equals(typeName)) {
return 1i;
}
else if ("double".equals(typeName)) {
return 1.0d
}
}
String str = MyClass.switchInput("java.lang.String")
I have not tested that, this is a simpler version of my first thought about generics
To know what the return type is, you have to find a container where all these types fit in. Obviously, this is Object. You'd have to convert the primitive types to the corresponding object (like int to Integer).
A better approach would be to create a new container class, which holds a generic type <T>. Like
public class SwitchDemo {
public static SwitchInputType<?> switchInput(String typeName) {
if (typeName.equals("java.lang.String")) {
return new SwitchInputType<String>(new String("A"));
} else if (typeName.equals("int")) {
return new SwitchInputType<Integer>(new Integer(312));
}
return null;
}
public static class SwitchInputType<T> {
private T type;
public SwitchInputType(T type) {
super();
this.type = type;
}
public T getType() {
return type;
}
public void setType(T type) {
this.type = type;
}
}
public static void main(String[] args) {
SwitchInputType<?> sit1 = SwitchDemo.switchInput("java.lang.String");
System.out.println(sit1.getType());
SwitchInputType<?> sit2 = SwitchDemo.switchInput("int");
System.out.println(sit2.getType());
}
}
As an ugly solution to your problem, you could set your method to run the type Object. (as Boolean, Integer, Double are all subtypes)
You would have to ensure though that you then inferred the correct type afterwards when using the returned value (using instanceof) and recast it to the correct type.
Can I ask though why you need such a method? This is abusing the notion of a method definition slightly.
public static Object SwitchInput(String TypeName) {
if (TypeName.equals("java.lang.String") ) {
Return = new String("A");
}
else if (TypeName.equals("int") ) {
Return = new Integer(1);
}
else if (TypeName.equals("double")) {
Return = new Double(1.00) ;
}
etc for bool and all the other types
}
And using this code snippet to infer what type it is further on down in your code
if(returned_value instanceof Double)
etc.