Remove every nth employee doesn't work - java

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class vijftienpunt1 {
public static void downsize(LinkedList<String> employeeNames, int n) {
for (int i = 0; i < employeeNames.size(); i++) {
if(i%n==0) {
employeeNames.remove(i);
}
}
}
public static void main(String[] args) {
LinkedList<String> employeeNamess = new LinkedList<String>();
employeeNamess.add("Ab");
employeeNamess.add("Yo");
employeeNamess.add("Ik");
employeeNamess.add("Jij");
System.out.println(employeeNamess);
downsize(employeeNamess, 2);
System.out.println(employeeNamess);
}
}
When I run this doesn't work, it removes other nth elements, how can I fix this. I have tried more operations but it still doesn't work

Use Iterator whenever you want to remove elements from list.
try below code:
public static void downsize(LinkedList<String> employeeNames, int n) {
int i=1;
Iterator<String> iter=employeeNames.iterator();
while(iter.hasNext()){
iter.next();
if(i%n==0) {
iter.remove();
}
i++;
}
}

Related

Iterating over object of the class

In the following code, I instantiated an object of the class and wondering whether I am heading in the right direction or not?. Since it's not a collection, is there a way I can iterate through the items I am inserting using stack class object? Or is there something wrong with the solution design part?
package stack;
import java.util.LinkedList;
import java.util.Queue;
public class StackUsingQPartII {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
public int pop() {
if (q1.peek() == null) {
System.out.println("The stack is empty, nothing to return");
int i = 0;
return i;
} else {
int pop = q1.remove();
return pop;
}
}
public void push(int data) {
if (q1.peek() == null) {
q1.add(data);
} else {
for (int i = q1.size(); i > 0; i--) {
q2.add(q1.remove());
}
q1.add(data);
for (int j = q2.size(); j > 0; j--) {
q1.add(q2.remove());
}
}
}
public static void main(String[] args) {
StackUsingQPartII st = new StackUsingQPartII ();
st.push(2);
}
}
You can make the class enclosing your stack implementation return an iterator() to iterate over the elements in the queue. The iterator() functionality can simply be delegated to the underlying container class holding the stack elements.
public class StackUsingQPartII implements Iterable<Integer>{
#Override
public Iterator<Integer> iterator() {
return q1.iterator();
}
public static void main(String[] args) {
StackUsingQPartII st = new StackUsingQPartII();
st.push(2);
Iterator<Integer> it = st.iterator();
while (it.hasNext()) {
Integer i = it.next();
System.out.println(i);
}
}
}

selection sort Algorithm java

I was debugging my code and found a problem with my Selection Sort Algorithm.
The code below almost sorts it, but I cant understand why all of it is not sorted.
have tried everything but to no avail.
import java.util.Random;
public class Help
{
//private static int[] myarray=new int[20];
private static int[] array;
public static void main(String[] args)
{
array=new int[20];
fillArrayRandom(array);
sortAscending(array);
///This is the bit that does not do what it is meant to do!
for(int i=0;i<array.length;i++)
{
// System.out.printf("Testing %d%n",myarray[i]);
}
}
public static void fillArrayRandom(int[] array)
{
int i;
for(i=0;i<array.length;i++)
{
array[i]=getRandomNum();
}
}
public static int getRandomNum()``
{
Random num=new Random();
int TestNumber=num.nextInt(2000);
return TestNumber;
}
public static void sortAscending(int[] array)
{
int smallest;
for(int i=0;i<array.length-1;i++)
{
smallest=i;
for(int index=i+1;index<array.length;index++)
{
if(array[index]<array[smallest])
smallest =index;
swap(i,smallest);
}
System.out.printf("%d%n",array[i]);
}
}
public static void swap(int first,int second)
{
int temporary=array[first];
array[first]=array[second];
array[second]=temporary;
}
}
You need to swap after the inner loop has completed:
public static void sortAscending(int[] array)
{
int smallest;
for(int i=0;i<array.length-1;i++)
{
smallest=i;
for(int index=i+1;index<array.length;index++)
{
if(array[index]<array[smallest])
smallest =index;
}
if (i != smallest) swap(i,smallest);
System.out.printf("%d%n",array[i]);
}
}

Copy Lists method doesn't work

I'm trying to make a copy lists method as this one Collections.copy(,);
I want to make it my self so I made this one
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class NewMain {
public static void main(String[] args) {
String[] a1={"asdasd","sadasd","asdasd"};
List<String> l1= Arrays.asList(a1);
String[] a2=new String[3];
List<String> l2= Arrays.asList(a2);
copy(l1,l2);
}
public static void copy(List<String> copy_from,List<String> copy_to){
for(int i=0;i<=copy_from.size();i++){
System.out.print( copy_from.containsAll(copy_to));
}
}
}
I know the problem from containsAll method , but what should I use ?
for(int i=0;i<=copy_from.size();i++){
System.out.print( copy_from.containsAll(copy_to));
}
Does nothing besides a sysout statement.
You want something along the lines of:
public static void copy(List<String> copy_from,List<String> copy_to){
if (copy_from.size() > copy_to.size())
throw new IndexOutOfBoundsException("Source does not fit in dest");
} else {
for(String toCopy : copy_from) {
copy_to.add(toCopy);
}
}
}
This is a for each loop that loops over every element in your copy_from list and adds it to your copy_to list.
This will behave the same way as Collections.copy.
public static void copy(List<String> copy_from,List<String> copy_to){
if (copy_to.size() < copy_from.size()) {
throw new IndexOutOfBoundsException("copy_to is too small.");
}
ListIterator<String> fromIter = copy_from.listIterator();
ListIterator<String> toIter = copy_to.listIterator();
while (fromIter.hasNext()) {
String next = fromIter.next();
toIter.next();
toIter.set(next);
}
}
I assume that you don't want to copy elements that are already there.
Then you can do it this way:
public static void copy(List<String> copy_from,List<String> copy_to){
if(copy_to==null){throw Exception("copy_to can't be null!")}
//additional checks should be added
for(String elem : copy_from){
if(!copy_to.contains(elem)){
copy_to.add(elem);
}
}
}
This should do assuming copy_from and copy_to can grow as we add elements.
public static void copy(List<String> copy_from,List<String> copy_to) throws Exception {
//handle exception according to your wish
if (copy_from !=null && copy_to == null) {
throw new Exception("Source is not empty by Destination is null");
}
for(String string : copy_from){
copy_to.add(string);
}
}

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

I'm using Eclipse and I'm using Java. My objective it's to sort a vector, with the bogoSort method
in one vector( vectorExample ) adapted to my type of vector and use the Java sort on other vector (javaVector) and compare them.
I did the tests but it did't work, so I don't know what is failing.
*Note: there are few words in spanish: ordenado = sorted, Ejemplo = Example, maximo = maximun, contenido = content.
EjemploVector class
package vector;
import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.Iterator;
public class EjemploVector <T> {
protected T[] contenido;
private int numeroElementos;
#SuppressWarnings("unchecked")
public EjemploVector () {
contenido = (T[]) new Object[100];
numeroElementos = 0;
}
#SuppressWarnings("unchecked")
public EjemploVector (int maximo) {
contenido = (T[]) new Object[maximo];
numeroElementos = 0;
}
public String toString(){
String toString="[";
for (int k=0; k<numeroElementos;k++){
if (k==numeroElementos-1){
toString = toString + contenido[k].toString();
} else {
toString = toString + contenido[k].toString()+", ";
}
}
toString = toString + "]";
return toString;
}
public boolean equals (Object derecho){
if (!(derecho instanceof Vector<?>)) {
return false;
} else if (numeroElementos != ((Vector<?>)derecho).size()) {
return false;
} else {
Iterator<?> elemento = ((Vector<?>)derecho).iterator();
for (int k=0; k<numeroElementos;k++){
if (!((contenido[k]).equals (elemento.next()))) {
return false;
}
}
return true;
}
}
public void addElement (T elemento){
contenido[numeroElementos++]= elemento;
}
protected T[] getContenido(){
return this.contenido;
}
protected T getContenido (int k){
return this.contenido[k];
}
#SuppressWarnings("unchecked")
protected void setContenido (int k, Object elemento){
this.contenido[k]= (T)elemento;
}
EjemploVectorOrdenadoClass
package vector.ordenado;
import java.util.Arrays;
import java.util.Random;
import vector.EjemploVector;
public class EjemploVectorOrdenado<T extends Comparable<T>> extends EjemploVector<T> {
private boolean organized;
public EjemploVectorOrdenado() {
super();
organized = true;
}
public EjemploVectorOrdenado(int maximo) {
super(maximo);
organized = true; //
}
public boolean getOrdenado() {
return this.organized;
}
// Method bogoSort
public void bogoSort() {
if (!this.organized) {
if (this.size() > 0) {
Random generator;
T tempVariable;
int randomPosition;
do {
generator = new Random();
for (int i = 0; i < this.size(); i++) {
randomPosition = generator.nextInt(this.size());
tempVariable = contenido[i];
contenido[i] = contenido[randomPosition];
contenido[randomPosition] = tempVariable;
}
} while (!organized);
}
}
this.organized = true;
}
public void addElement(T elemento) {
super.addElement(elemento);
if (organized && this.size() > 1) {
T penultimo = this.getContenido(this.size() - 2);
T ultimo = this.getContenido(this.size() - 1);
organized = penultimo.compareTo(ultimo) <= 0;
}
}
}
ElementoTest class
package elementos;
import java.io.Serializable;
public class ElementoTest implements Comparable<ElementoTest>, Serializable {
private static final long serialVersionUID = -7683744298261205956L;
private static int numeroElementosTest = 0;
private int clave;
private int valor;
public ElementoTest(int i){
this.clave = i;
this.valor = numeroElementosTest;
numeroElementosTest++;
}
public String toString(){
return ("(" + this.clave + "," + this.valor + ")");
}
public boolean equals (Object derecho){
if (!(derecho instanceof ElementoTest)) {
return false;
} else {
return clave == ((ElementoTest)derecho).clave;
}
}
public char getClave(){
return this.clave;
}
public int getValor(){
return this.valor;
}
#Override
public int compareTo(ElementoTest elemento) {
if (elemento == null){
return -1;
} else if (this.equals(elemento)){
return 0;
} else if (clave < elemento.clave){
return -1;
} else {
return 1;
}
}
}
TESTS
The first it's a stupid test, because it puts elements in order so... really the methods arenĀ“t doing anything, java just compare and it gives correct
I tried to make an unsorted vector adding elements but there appears the java.lang.ClassCastException: [Ljava.... etc.
package vector.ordenado;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.Vector;
import org.junit.Before;
import org.junit.Test;
import elementos.ElementoTest;
public class EjemploVectorOrdenadoTest {
private Vector<ElementoTest> vectorJava;
private EjemploVectorOrdenado<ElementoTest> vectorExample;
#Before
public void setUp() throws Exception {
vectorJava = new Vector<ElementoTest>(100);
vectorExample = new EjemploVectorOrdenado<ElementoTest>(100);
}
#Test
public void testSortFailTest() {
for (char c = 'a'; c < 'g'; c++) {
vectorJava.addElement(new ElementoTest(c));
vectorExample.addElement(new ElementoTest(c));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
#Test
public void testSort() {
{
vectorJava.addElement(new ElementoTest(1));
vectorJava.addElement(new ElementoTest(3));
vectorJava.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(3));
vectorExample.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(1));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
}
Sorry, for the problems and thanks.
The problem is that your test class ElementoTest should implement the Comparable interface. Or you need to provide a Comparator during your comparison.
Does your class ElementtoTest implement Comparable?
If not, it needs to.
I'm suspecting it doesn't, because that's exactly what would cause this error. you'll need to add implements Comparable and then override the int compareTo(Elementtotest e) method, where you specify what criteria you'd like to order the objects based on.

Get Class Annotations from Java Source File

I'm parsing Java Source Files to collect various informations about my classes. Therefore I'm using the JavaParser, since I could not find a good alternative (good suggestions have the chance to become "answers") to parse Source Files.
I already managed to get Annotations of all methods from my class. The code looks like this:
package de.mackaz;
import japa.parser.JavaParser;
import japa.parser.ParseException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.expr.AnnotationExpr;
import japa.parser.ast.expr.MarkerAnnotationExpr;
import japa.parser.ast.expr.MemberValuePair;
import japa.parser.ast.expr.NormalAnnotationExpr;
import japa.parser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;
public class JavaSourceUtils {
public static void main(String[] args) throws Exception {
File f = new File("/home/mackaz/SourceFile.java");
inspectJavaFile(f);
}
public static void inspectJavaFile(File pFile)
throws FileNotFoundException, ParseException, IOException {
CompilationUnit cu;
FileInputStream in = new FileInputStream(pFile);
try {
cu = JavaParser.parse(in);
} finally {
in.close();
}
new MethodVisitor().visit(cu, null);
}
/**
* Simple visitor implementation for visiting MethodDeclaration nodes.
*/
private static class MethodVisitor extends VoidVisitorAdapter {
#Override
public void visit(MethodDeclaration n, Object arg) {
System.out.println(n.getName());
if (n.getAnnotations() != null) {
for (AnnotationExpr annotation : n.getAnnotations()) {
System.out.println(annotation.getClass());
// MarkerAnnotations, for example #Test
if (annotation.getClass().equals(MarkerAnnotationExpr.class)) {
System.out.println("MarkerAnnotation:" + ((MarkerAnnotationExpr)annotation).getName());
}
if (annotation.getClass().equals(NormalAnnotationExpr.class)) {
for (MemberValuePair pair : ((NormalAnnotationExpr)annotation).getPairs()) {
if (pair.getName().equals("groups"))
System.out.println("Group:\"" + pair.getValue() + "\"");
}
}
}
}
}
}
}
Now how can I get the Annotations of the class itself?
You are overriding public void visit(MethodDeclaration n, Object arg), which visits methods. You can also override public void visit(ClassOrInterfaceDeclaration n, A arg) or public void visit(ClassOrInterfaceType n, A arg), which should give you access to the information you are looking for.
This is how I solved it in the end - I added another Visitor "ClassVisitor":
private static class ClassVisitor extends VoidVisitorAdapter {
#Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
for (AnnotationExpr ann: n.getAnnotations()) {
System.out.println(ann.toString());
}
}
}
Looks like you need extend ModifierVisitorAdapter and implement
public Node visit(ClassOrInterfaceDeclaration n, A arg) {
Look at the implementation here for an idea of what you might want to do:
public Node visit(ClassOrInterfaceDeclaration n, A arg) {
if (n.getJavaDoc() != null) {
n.setJavaDoc((JavadocComment) n.getJavaDoc().accept(this, arg));
}
List<AnnotationExpr> annotations = n.getAnnotations();
if (annotations != null) {
for (int i = 0; i < annotations.size(); i++) {
annotations.set(i, (AnnotationExpr) annotations.get(i).accept(this, arg));
}
removeNulls(annotations);
}
List<TypeParameter> typeParameters = n.getTypeParameters();
if (typeParameters != null) {
for (int i = 0; i < typeParameters.size(); i++) {
typeParameters.set(i, (TypeParameter) typeParameters.get(i).accept(this, arg));
}
removeNulls(typeParameters);
}
List<ClassOrInterfaceType> extendz = n.getExtends();
if (extendz != null) {
for (int i = 0; i < extendz.size(); i++) {
extendz.set(i, (ClassOrInterfaceType) extendz.get(i).accept(this, arg));
}
removeNulls(extendz);
}
List<ClassOrInterfaceType> implementz = n.getImplements();
if (implementz != null) {
for (int i = 0; i < implementz.size(); i++) {
implementz.set(i, (ClassOrInterfaceType) implementz.get(i).accept(this, arg));
}
removeNulls(implementz);
}
List<BodyDeclaration> members = n.getMembers();
if (members != null) {
for (int i = 0; i < members.size(); i++) {
members.set(i, (BodyDeclaration) members.get(i).accept(this, arg));
}
removeNulls(members);
}
return n;
}

Categories

Resources