This is the interface
public interface Set{
public static final int MAX=10;
public void add(int e);
public Set union(Set s);
public void display();
}
SetImp
public class SetImp implements Set{
private int[] set;
private int count;
public SetImp(){
set = new int[MAX];
count = 0;
}
public void add(int e){
if(!contains(e))
set[count++]=e;
}
private boolean contains(int e){
boolean found=false;
for(int i=0;i<count;i++){
if(set[i]==e){
found=true;
break;
}
}
return found;
}
public void display(){
for(int i=0;i<count;i++)
System.out.print(set[i] + " ");
System.out.println();
}
Where I had most of my problems.
Whenever I try to unite Set s with set, the union takes effect in both s.
I tried making a temp variable but it still doesn't work.
public Set union(Set s){
for(int i=0; i<count; i++){
s.add(set[i]);
}
return s;
}
}
Your code starts with 2 sets:
Given set1.union(set2), there's set1 and set2 of course.
Given: Set set3 = set1.union(set2); there are 3 completely separate sets: set1 and set2 did not change, which means set3 is different.
Therefore, you must have 3 sets. Given that at the start of the union method there are only 2... that means you must invoke new SetImp() someplace, or this is never going to work out.
I'm sure with that hint you can figure this one out :)
Create a new SetImp and add both Sets to it.
public Set union(Set s){
final Set res = new SetImp();
for(int i = 0; i < count; i++){
res.add(set[i]);
}
for(int i = 0; i < s.count; i++){
res.add(s.set[i]);
}
return res;
}
Related
here's the code for MyArrayList
public void addLast(int number){
if(!isFull())
doubleTheArray();
element[count++] = number;
}
and here's the code for MyOrderedList
public void add(int item){
for(int i = 0; i < count; i++){
for(int j = i+1; j < count; j++){
if(element[i] > element[j]){
item = element[i];
element[i] = element[j];
element[j] = item;
}
}
}
addLast(item);
}
This is the main method
public static void main(String [] args){
MyOrderedList oList = new MyOrderedList();
oList.add(3);
oList.add(5);
oList.add(2);
oList.add(4);
oList.add(7);
oList.add(8);
oList.add(10);
System.out.println("Ordered list of items: "+ oList);
}
Can anyone help me find out what's wrong? We're not allowed to use sort so I made a solution but 2 numbers are outputted twice in the main method for MyOrderedList. We have to add the elements at the right location. Or in ascending order for add(item). isFull() is boolean method that doubles (doubleTheArray()) the array size if it is true.
In this project, I'm trying to access information from an ArrayList which contains only the dates which are Strings.
Here is part of the class I tried. If not having the whole class makes it hard to understand I can edit...
public ArrayList<String> getTicketDates(){
ArrayList<String> theDateArray= new ArrayList<>();
int i;
for (i=0; i <tickets.size(); i++){
if(tickets .get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
for(int f=0; f<theDateArray.size();f++){
System.out.println(theDateArray.get(f)+ " ");
}
return theDateArray;
}
public int getTickets(String date){
int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);
if (tix>=0){
System.out.println(occurrences);
}
return occurrences;
}
The 2nd class, I'm trying to count the amount of times one particular date occurs in the previous ArrayList, but it says that theDateArray cannot be resolved to a variable.
One method I've tried is just calling the entire method getTicketDates(), but what it does is it prints out the ArrayList triple, and the occurrences still don't work.
Your theDateArray variable scope is local to the getTicketDates() method, so you are not able to access it in the other method, so declare it as an instance variable as shown below:
public class YourTicketsClass {
//declare ArrayList as an instance variable
ArrayList<String> theDateArray= new ArrayList<>();
public ArrayList<String> getTicketDates(){
int i;
for (i=0; i <tickets.size(); i++){
if(tickets .get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
for(int f=0; f<theDateArray.size();f++){
System.out.println(theDateArray.get(f)+ " ");
}
return theDateArray;
}
public int getTickets(String date){
int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);
if (tix>=0){
System.out.println(occurrences);
}
return occurrences;
}
}
Define the array list outside of the method, then populate the list inside the method. Like this:
public class YourdataClass {
private List<String> theDateArray = new ArrayList<String>();
public ArrayList<String> getTicketDates(){
int i;
for (i=0; i <tickets.size(); i++){
if(tickets .get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
for(int f=0; f<theDateArray.size();f++){
System.out.println(theDateArray.get(f)+ " ");
}
return theDateArray;
}
public int getTickets(String date){
int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);
if (tix>=0){
System.out.println(occurrences);
}
return occurrences;
}
}/* end class */
Here are some references. http://www.javawithus.com/tutorial/scope-and-lifetime-of-variables
https://en.wikibooks.org/wiki/Java_Programming/Scope
I have a final project for my Data Structures class that I can't figure out how to do. I need to implement Radix sort and I understand the concept for the most part. But all the implementations I found online so far are using it strictly with integers and I need to use it with the other Type that I have created called Note which is a string with ID parameter.
Here is what I have so far but unfortunately it does not pass any JUnit test.
package edu.drew.note;
public class RadixSort implements SortInterface {
public static void Radix(Note[] note){
// Largest place for a 32-bit int is the 1 billion's place
for(int place=1; place <= 1000000000; place *= 10){
// Use counting sort at each digit's place
note = countingSort(note, place);
}
//return note;
}
private static Note[] countingSort(Note[] note, long place){ //Where the sorting actually happens
Note[] output = new Note[note.length]; //Creating a new note that would be our output.
int[] count = new int[10]; //Creating a counter
for(int i=0; i < note.length; i++){ //For loop that calculates
int digit = getDigit(note[i].getID(), place);
count[digit] += 1;
}
for(int i=1; i < count.length; i++){
count[i] += count[i-1];
}
for(int i = note.length-1; i >= 0; i--){
int digit = getDigit((note[i].getID()), place);
output[count[digit]-1] = note[i];
count[digit]--;
}
return output;
}
private static int getDigit(long value, long digitPlace){ //Takes value of Note[i] and i. Returns digit.
return (int) ((value/digitPlace ) % 10);
}
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
//Main Method
public static void main(String[] args) {
// make an array of notes
Note q = new Note(" ", " ");
Note n = new Note("CSCI 230 Project Plan",
"Each person will number their top 5 choices.\n" +
"By next week, Dr. Hill will assign which piece\n" +
"everyone will work on.\n");
n.tag("CSCI 230");
n.tag("final project");
Note[] Note = {q,n};
//print out not id's
System.out.println(Note + " Worked");
//call radix
Radix(Note);
System.out.println(Note);
//print out note_id's
}
}
Instead of
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
I should have used
public Note[] sort(Note[] s) { //
s = Radix(s);
return s;
}
and change the variable type of Radix from void to Note[].
I'm fairly new to Java and this may sound a bit strange.
Okay basically I'm taking in 9 values and storing them as Integers in an ArrayListScores.
I have verified that they are storing in there and all looks okay with that.
I'm developing a simple androids app.
So we take it as if I take in the 9 values in class 1 as such from text views parseInt them. This works fine that is not my issue.
Class 1
ArrayList<Integer> Scores = new ArrayList<Integer>();
Scores.add(Integer.parseInt(et1.getText().toString()));
Scores.add(Integer.parseInt(et2.getText().toString()));
Scores.add(Integer.parseInt(et3.getText().toString()));
Scores.add(Integer.parseInt(et4.getText().toString()));
Scores.add(Integer.parseInt(et5.getText().toString()));
Scores.add(Integer.parseInt(et6.getText().toString()));
Scores.add(Integer.parseInt(et7.getText().toString()));
Scores.add(Integer.parseInt(et8.getText().toString()));
Scores.add(Integer.parseInt(et9.getText().toString()));
My Problem is that I have another class which I want to do some basic calculations, just add up all the scores as such.
Class 2
public class AddNumbers {
private static AddNumbers instance;
private AddNumbers(){
}
public static AddNumbers getInstance() {
if(instance == null) {
instance = new AddNumbers();
}
return instance;
}
public int getFinalScore() {
ArrayList<Integer> Scores = new ArrayList<Integer>();
int final_score = 0;
for(int s: Scores){
final_score += s;
}
return final_score;
}
}
I was to do the basic adding up of all the scores in class 2 and send the result back to class 1 but I don't know how.
Do you really need another class for this? Why not just put this in a method in Class 1?
It would look like:
public int getFinalScore(){
You want to put in your ArrayList here. This should look like:
public int getFinalScore(ArrayList<Integer> Scores) {
Then put your for loop, and return final_score:
int final_score = 0;
for (int s: Scores) {
final_score += s;
}
return final_score;
So your final method would look like this:
public int getFinalScore(ArrayList<Integer> Scores) {
int final_score = 0;
for (int s: Scores) {
final_score += s;
}
return final_score;
}
You would call it just via getFinalScore(Scores).
Pass Scores from Class 1 as a parameter into the getFinalScore method in Class 2
public int getFinalScore(List<Score> scores) {
int final_score = 0;
for(int s: scores){
final_score += s;
}
return final_score;
}
Then use the return value as your sum in Class 1.
What I would do is make a variable/instance of the ArrayList from class 1. so first you need to make Scores public so your other class can access it:
public static ArrayList<Integer> Scores = new ArrayList<Integer>(); //add public and static
Scores.add(Integer.parseInt(et1.getText().toString()));
Scores.add(Integer.parseInt(et2.getText().toString()));
Scores.add(Integer.parseInt(et3.getText().toString()));
Scores.add(Integer.parseInt(et4.getText().toString()));
Scores.add(Integer.parseInt(et5.getText().toString()));
Scores.add(Integer.parseInt(et6.getText().toString()));
Scores.add(Integer.parseInt(et7.getText().toString()));
Scores.add(Integer.parseInt(et8.getText().toString()));
Scores.add(Integer.parseInt(et9.getText().toString()));
Then, you need to refer back to it like so:
public int getFinalScore() {
ArrayList<Integer> scores = Class1.Scores; //make a new variable referring to the Scores (Case Matters!)
int final_score = 0;
for(int s: scores){ //use the new variable
final_score += s;
}
return final_score;
}
Alternatively, you can make the new variable scores (CASE matters) public and static if you want to use it in yet another class again (if you want to, this isn't necessary). However, you still need to make the ArrayList public! The public scores would look like this:
public class AddNumbers {
private static AddNumbers instance;
public static ArrayList<Integer> scores = Class1.Scores //made the variable public and static (optional)
private AddNumbers(){
}
public static AddNumbers getInstance() {
if(instance == null) {
instance = new AddNumbers();
}
return instance;
}
//same as before
public int getFinalScore() {
ArrayList<Integer> scores = Class1.Scores; //make a new variable referring to the Scores (Case Matters!)
int final_score = 0;
for(int s: scores){ //use the new variable
final_score += s;
}
return final_score;
}
}
Alternatively again, you can make a new parameter and set it to Scores (Again, you still need to make Scores public):
public int getFinalScore(ArrayList<Integer> scores) {
scores = Class1.Scores //set local variable to public variable
int final_score = 0;
for(int s: scores){
final_score += s;
}
return final_score;
}
I am trying to have a method (duplicates) return true if a given array called x (entered by user in another method), contains duplicate values. Otherwise it would return false. Rather then checking the entire array, which is initialized to 100, it will check only the amount of values entered, which is kept track of with a global counter: numElementsInX.
What is the best way to accomplish this?
public static boolean duplicates (int [] x)
I am prompting for user data like so:
public static void readData (int [] x, int i){
Scanner input = new Scanner(System.in);
System.out.println("Please enter integers, enter -999 to stop");
while (i <= 99) {
int temp = input.nextInt();
if(temp == -999){
break;
}
else {
x[i++]=temp;
}
// else
}//end while
printArray(x,i);
}//end readData
public static void printArray(int [] x, int numElementsInX){
int n = numElementsInX;
for (int i = 0; i < n; i++){
System.out.print(x[i] + " ");
}//end for
System.out.println();
}//end printArray
I am sure there is a better way to do this, but this is how I have been taught so far.
Here is a solution that:
Compiles and executes without throwing.
Uses numElementsInX as you requested.
Returns as soon as it finds a duplicate.
This approach tests whether each member of the array has been seen before. If it has, the method can return immediately. If it hasn't, then the member is added to the set seen before.
public static boolean duplicates (int [] x, int numElementsInX ) {
Set<Integer> set = new HashSet<Integer>();
for ( int i = 0; i < numElementsInX; ++i ) {
if ( set.contains( x[i])) {
return true;
}
else {
set.add(x[i]);
}
}
return false;
}
Here's a sample program containing the above code.
this should do it.
public boolean containsDuplicates(Integer[] x) {
return new HashSet<Integer>(Arrays.asList(x)).size() != x.length
}
You dont need numElementsInX as this is the same as x.length
edit after comment from Louis. Arrays.asList does not work with int arrays.
To convert int[] to Integer try this question How to convert int[] to Integer[] in Java?
or do soemthing like this (not tested but from memory)
Integer[] newArray = new Integer[a.length];
System.arraycopy(a, 0, newArray, 0, a.length);
This certainly isn't the most efficient way, but since you don't know about Sets yet, you can use two loops:
public static boolean duplicates (int [] x){
for (int i=0; i<numElementsInX; i++){
for (int j=i+1; j<numElementsInX; j++){
if (x[j]==x[i]) return true;
}
}
return false;
}
"set.add()" returns true if the element is not already present in the set and false otherwise. We could make use of that and get rid of "set.contains()" as in the above solution.
public static boolean duplicates (int[] x, int numElementsInX) {
Set<Integer> myset = new HashSet<>();
for (int i = 0; i < numElementsInX; i++) {
if (!myset.add(x[i])) {
return true;
}
}
return false;
}
For java, return true if the array contains a duplicate value,
boolean containsDuplicates(int[] a) {
HashSet<Integer> hs = new HashSet<>();
for(int i = 0; i<a.length; i++) {
if(!hs.add(a[i])){
return true;
}
}
return false;
}