I have these two classes:
import java.util.ArrayList;
import java.util.Arrays;
public class Giocatore {
private String nome;
private ArrayList<Cartella> cartelle;
public Giocatore(String nome, int numeroCartelle) {
this.nome = nome;
for (int i = 0; i < numeroCartelle; i++) {
cartelle.add(new Cartella().creazioneCartella());
}
}
#Override
public String toString() {
return "Giocatore" + " nome=" + nome + ", cartelle=" + cartelle + "]";
}
}
and
import java.util.Random;
public class Cartella {
private int[] cartella;
public Cartella() {
cartella = new int[15];
}
public int[] creazioneCartella() {
Random random = new Random();
int n = random.nextInt(90 + 1) + 1;
for (int i = 0; i < cartella.length; i++) {
if (i > 0) {
for (int j = 0; j < i; j++) {
if (n == cartella[j]) {
n = random.nextInt(90 + 1) + 1;
j--;
}
}
}
cartella[i] = n;
}
return cartella;
}
public void stampaCartella() {
for (int i = 0; i < cartella.length; i++) {
System.out.print(cartella[i] + " ");
}
System.out.println();
}
public int[] getCartella() {
return cartella;
}
public void setCartella(int[] cartella) {
this.cartella = cartella;
}
}
i used the class Cartella as an arraylist in Giocatore, now i want to add an array into that arraylist using the method creazioneCartella(), but every time the compiler suggest me to change the method creazioneCartella into an element of Cartella. How can i add that array into that list? i've tried different methods like Arrays.asList(array) but nothing
Related
I am trying to develop java program for finding the shortest path with genetic algorithm in weighted graph. I am having difficulties in coding based on this algorithm. Can someone show me sample codes for this problem. Any language is okay. Any information like libraries or others that might be helpful for this problem is also okay. Most important thing right now is to test the time to find the shortest path based on this algorithm and I need to find out before due date for my assignment. So if anyone can help me,please.
I was coding based on java and I have difficulties mostly in cross over and mutation process. And also defining fitness function is also a problem.
Here is a Java example of a shortest path genetic algorithm
package ga;
import java.util.ArrayList;
import java.util.Arrays;
public class GA {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//computation time
long start = System.nanoTime();
//population size
int populationSize = 30;
//Number of Cities
int numCities = 15;
//Mutation rate
double mutationRate = 0.05;
//Crossover Rate
double crossoverRate = 0.8;
//Choose File path or if false randomly created Path
boolean useFile = false;
//Name the file to be used
String fileName = "Data.txt";
//Current Number of Generations
int numberOfGenerations = 0;
//Stop Condition
int stopAt=2500;
//Population
Population pop;
//use GA or Brute Force
boolean GAuse=true;
//Selecting File mode or Random Mode
if (useFile == false) {
pop = new Population(populationSize, numCities, crossoverRate, mutationRate);
} else {
FileReader file = new FileReader(fileName);
numCities=file.getNumCities();
crossoverRate=file.getCrossoverRate();
mutationRate=file.getMutationRate();
populationSize=file.getCities().length;
Path p = new Path(file.getNumCities());
p.setPath(file.getCities());
pop = new Population(populationSize, numCities, p,crossoverRate ,mutationRate );
}
if(GAuse==true){
//Sorting the population from Finess / Evaluating
pop.FitnessOrder();
//Prints each path ID/Cost/Fitness/City order(with coordinates)
for (int i = 0; i < pop.getPopulation().length; i++) {
System.out.println("Path ID: "+i+" | Cost: "+pop.getPopulation()[i].getCost()+" | Fitness: "+pop.getPopulation()[i].getFitness()+"%");
System.out.print("Path is: ");
for (int j = 0; j < pop.getPopulation()[i].getPath().length; j++) {
System.out.print(pop.getPopulation()[i].getPath()[j].getId() +"("+pop.getPopulation()[i].getPath()[j].getX()+","+pop.getPopulation()[i].getPath()[j].getY()+") ");
}System.out.println("\n -----------------------------------------------------");
}
//Start looking for possible solution
while (numberOfGenerations !=stopAt) {
//Select / Crossover
while (pop.Mate() == false);
//Mutate
for (int i = 0; i < pop.getNextGen().length; i++) {
pop.getNextGen()[i].setPath(pop.Mutation(pop.getNextGen()[i].getPath()));
}
//Setting the new Generation to current Generation
pop.setPopulation(pop.getNextGen());
pop.setDone(0);
//Sorting the new population from Finess / Evaluating
pop.FitnessOrder();
//Incremente number of Generations
numberOfGenerations++;
}
//Prints out the fitness of each path
double valor=0;
for (int i = 0; i < pop.getPopulation().length; i++) {
valor += pop.getPopulation()[i].getFitness();
System.out.println("Value of Fitness: "+pop.getPopulation()[i].getFitness()+"%");
}
System.out.println("");
System.out.println("Total Fitness: "+valor+"%");
System.out.println("\n-----------------------------------------------");
//Prints each path ID/Cost/Fitness/City order(with coordinates)
for (int i = 0; i < pop.getPopulation().length; i++) {
System.out.println("Path ID: "+i+" | Cost: "+pop.getPopulation()[i].getCost()+" | Fitness: "+pop.getPopulation()[i].getFitness()+"%");
System.out.print("Path is: ");
for (int j = 0; j < pop.getPopulation()[i].getPath().length; j++) {
System.out.print(pop.getPopulation()[i].getPath()[j].getId() +"("+pop.getPopulation()[i].getPath()[j].getX()+","+pop.getPopulation()[i].getPath()[j].getY()+") ");
}System.out.println("\n -----------------------------------------------------");
}
}
else{//USING BRUTE FORTE METHOD
FileReader file = new FileReader(fileName);
ArrayList<City> cities = new ArrayList<City>();
for (int i = 0; i <file.getNumCities(); i++) {
cities.add(file.getCities()[i]);
}
ArrayList<City> best = new ArrayList<City>();
Permutations permu = new Permutations();
permu.permutations(cities);
System.out.print("The shortest path is: ");
for (int i = 0; i < permu.getBest().size(); i++) {
System.out.print(permu.getBest().get(i).getId()+"("+permu.getBest().get(i).getX()+","+permu.getBest().get(i).getY()+")");
}
System.out.println("");
System.out.println("It would Cost: "+permu.getCost());
}
long elapsedTime = System.nanoTime() - start;
System.out.println("Algorithm took: "+elapsedTime+" nano seconds to find a solution");
}
}
package ga;
import java.util.ArrayList;
public class Permutations {
private int cost=999999;
private ArrayList<City> best;
public void permutations(ArrayList<City> list){
permutations(null, list, null);
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public ArrayList<City> getBest() {
return best;
}
public void setBest(ArrayList<City> best) {
this.best = best;
}
public ArrayList<City> permutations(ArrayList<City> prefix, ArrayList<City> suffix, ArrayList<ArrayList<City>> output){
if(prefix == null)
prefix = new ArrayList<City>();
if(output == null)
output = new ArrayList<ArrayList<City>>();
if(suffix.size() == 1){
ArrayList<City> newElement = new ArrayList<City>(prefix);
newElement.addAll(suffix);
int costNow=cost(newElement);
if(costNow<this.cost){
best=newElement;
this.cost=costNow;
}
return best;
}
for(int i = 0; i < suffix.size(); i++){
ArrayList<City> newPrefix = new ArrayList<City>(prefix);
newPrefix.add(suffix.get(i));
ArrayList<City> newSuffix = new ArrayList<City>(suffix);
newSuffix.remove(i);
permutations(newPrefix,newSuffix,output);
}
return best;
}
public int cost(ArrayList<City> path){
int cost=0;
int i=0;
while(i<path.size()-1){
cost+=path.get(i).distance(path.get(i+1).getX(),path.get(i+1).getY());
i++;
}
cost+=path.get(path.size()-1).distance(path.get(0).getX(), path.get(0).getY());
return cost;
}
}
package ga;
import java.util.Random;
public class Path implements Comparable {
private City [] path;
private int numCities;
private int cost;
private int fitness;
public Path(int numCities) {
this.numCities = numCities;
CreatePath();
cost =0;
calculateCost();
fitness =0;
}
public void calculateCost(){
cost=0;
int i=0;
while(i<numCities-1){
cost+=path[i].distance(path[i+1].getX(),path[i+1].getY());
i++;
}
cost+=path[path.length-1].distance(path[0].getX(), path[0].getY());
}
public int getFitness() {
return fitness;
}
public void setFitness(int fitness) {
this.fitness = fitness;
}
public int getCost() {
return cost;
}
public void setCost(int distance) {
this.cost = distance;
}
/* Overload compareTo method */
public int compareTo(Object obj){
Path tmp = (Path) obj;
if(this.cost < tmp.cost){
return 1;
}
else if(this.cost > tmp.cost){
return -1;
}
else{
return 0;
}
}
public void CreatePath(){
path= new City[numCities];
for (int i = 0; i < path.length; i++) {
path[i]=new City(i,RandomNum(1, 99),RandomNum(1, 99));
}
}
public int RandomNum(int min, int max){
return min+ (new Random()).nextInt(max-min);
}
public City[] getPath() {
return path;
}
public void setPath(City[] path) {
this.path = path;
calculateCost();
}
public int getNumCities() {
return numCities;
}
public void setNumCities(int numCities) {
this.numCities = numCities;
}
}
package ga;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
public class FileReader {
private int numCities;
private double mutationRate;
private City[] cities;
private int curLine;
private StringTokenizer st;
private int arrayCount;
private int x, y;
private double crossoverRate;
private String fileName;
public FileReader(String fileName) {
numCities = 0;
mutationRate = 0;
City[] cities = new City[0];
curLine = 1;
arrayCount = 0;
this.fileName=fileName;
read();
}
public int getNumCities() {
return numCities;
}
public void setNumCities(int numCities) {
this.numCities = numCities;
}
public double getMutationRate() {
return mutationRate;
}
public void setMutationRate(double mutationRate) {
this.mutationRate = mutationRate;
}
public City[] getCities() {
return cities;
}
public void setCities(City[] cities) {
this.cities = cities;
}
public int getCurLine() {
return curLine;
}
public void setCurLine(int curLine) {
this.curLine = curLine;
}
public StringTokenizer getSt() {
return st;
}
public void setSt(StringTokenizer st) {
this.st = st;
}
public int getArrayCount() {
return arrayCount;
}
public void setArrayCount(int arrayCount) {
this.arrayCount = arrayCount;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void read() {
try {
BufferedReader in = new BufferedReader(new java.io.FileReader("./"+fileName));
String line;
try {
while ((line = in.readLine()) != null) {
if (curLine == 1) {
st = new StringTokenizer(line, "=");
st.nextToken();
numCities = Integer.parseInt(st.nextToken());
cities = new City[numCities];
} else if (curLine == 2) {
st = new StringTokenizer(line, "=");
st.nextToken();
mutationRate = Double.parseDouble(st.nextToken());
}else if(curLine==3){
st = new StringTokenizer(line, "=");
st.nextToken();
crossoverRate = Double.parseDouble(st.nextToken());
}
else {
st = new StringTokenizer(line, "|");
st.nextToken();
String a = st.nextToken();
StringTokenizer stmp = new StringTokenizer(a, "=");
stmp.nextToken();
x = Integer.parseInt(stmp.nextToken());
String l = st.nextToken();
stmp = new StringTokenizer(l, "=");
stmp.nextToken();
y = Integer.parseInt(stmp.nextToken());
cities[arrayCount] = new City(arrayCount, x, y);
arrayCount++;
}
curLine++;
}
} catch (Exception e) {
}
} catch (FileNotFoundException e) {
System.out.println("File not found!!");
}
}
public double getCrossoverRate() {
return crossoverRate;
}
public void setCrossoverRate(double crossoverRate) {
this.crossoverRate = crossoverRate;
}
}
package ga;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public class Population {
private int populationSize;
private int numCities;
private Path[] population;
private double crossoverRate;
private City[] child1;
private City[] child2;
private double mutationRate;
private Path[] nextGen;
private int done;
public Population(int populationSize, int numCities, double crossoverRage, double mutationRate) {
this.populationSize = populationSize;
this.numCities = numCities;
population = new Path[populationSize];
this.crossoverRate = crossoverRage;
this.mutationRate = mutationRate;
this.nextGen = new Path[populationSize];
Path p = new Path(numCities);
done = 0;
CreatePopulation(p);
}
public Population(int populationSize, int numCities, Path path, double crossoverRage, double mutationRate) {
this.populationSize = populationSize;
this.numCities = numCities;
this.crossoverRate = crossoverRage;
population = new Path[populationSize];
this.mutationRate = mutationRate;
this.nextGen = new Path[populationSize];
done = 0;
CreatePopulation(path);
}
public void CreatePopulation(Path p) {
int i = 0;
while (i < populationSize) {
City[] tmpCity = new City[numCities];
for (int j = 0; j < tmpCity.length; j++) {
tmpCity[j] = p.getPath()[j];
}
Collections.shuffle(Arrays.asList(tmpCity));
Path tmpPath = new Path(numCities);
tmpPath.setPath(tmpCity);
population[i] = tmpPath;
i++;
}
}
public int SelectParent() {
int total = 0;
//Selecting parents
int totalCost = calculateTotalFitness();
int fit = RandomNum(0, totalCost);
int value = 0;
for (int i = 0; i < population.length; i++) {
value += population[i].getFitness();
if (fit <= value) {
return i;
}//if(fit<=value){
}
return -1;
}
public boolean Mate() {
//Generate a random number to check if the parents cross
int check = RandomNum(0, 100);
int parent1 = SelectParent();
int parent2 = SelectParent();
while (parent1 == parent2) {
parent2 = SelectParent();
}
//check if there is going to be a crossover
if (check <= (crossoverRate * 100)) {
int crossoverPoint = RandomNum(0, population[parent1].getPath().length - 1);
child1 = new City[numCities];
child2 = new City[numCities];
//crossing over
for (int i = 0; i < crossoverPoint; i++) {
child1[i] = population[parent2].getPath()[i];
child2[i] = population[parent1].getPath()[i];
}
for (int i = crossoverPoint; i < numCities; i++) {
child1[i] = population[parent1].getPath()[i];
child2[i] = population[parent2].getPath()[i];
}
//Rearrange childs considering city repetition
int cityChild1;
int cityChild2;
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < crossoverPoint; i++) {
cityChild1 = child1[i].getId();
cityChild2 = child2[i].getId();
//Get the positions of repeated values
for (int j = crossoverPoint; j < numCities; j++) {
if (cityChild1 == child1[j].getId()) {
list1.add(j);
}
if (cityChild2 == child2[j].getId()) {
list2.add(j);
}
}
}
//Find the missing values
for (int i = 0; i < numCities; i++) {
boolean found = false;
//Fixing Child1
for (int j = 0; j < numCities; j++) {
if (population[parent2].getPath()[i] == child1[j]) {
found = true;
break;
}
}
if (found == false) {
child1[list1.remove(list1.size() - 1)] = population[parent2].getPath()[i];
}
found = false;
//Fixing Child2
for (int j = 0; j < numCities; j++) {
if (population[parent1].getPath()[i] == child2[j]) {
found = true;
break;
}
}
if (found == false) {
child2[list2.remove(list2.size() - 1)] = population[parent1].getPath()[i];
}
}
// System.out.print("Parent 1: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(population[parent1].getPath()[i].getId() + " ");
// }
// System.out.print("\nParent 2: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(population[parent2].getPath()[i].getId() + " ");
// }
// System.out.print("\nChild 1: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(child1[i].getId() + " ");
// }
// System.out.print("\nChild 2: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(child2[i].getId() + " ");
// }
// System.out.println("");
//
// //Repeated Values
// for (int i = 0; i < list1.size(); i++) {
// System.out.print(list1.get(i) + " ");
// }
// System.out.println("");
// for (int i = 0; i < list2.size(); i++) {
// System.out.print(list2.get(i) + " ");
// }
if (AddToGenerationCheckFull(child1, child2) == false) {
return false;
} else {
return true;
}
} else {
if (AddToGenerationCheckFull(population[parent1].getPath(), population[parent1].getPath()) == false) {
return false;
} else {
return true;
}
}
}
public int getDone() {
return done;
}
public void setDone(int done) {
this.done = done;
}
public boolean AddToGenerationCheckFull(City[] child1, City[] child2) {
if (done == populationSize) {
return true;
}
Path newGenChild1 = new Path(numCities);
Path newGenChild2 = new Path(numCities);
newGenChild1.setPath(child1);
newGenChild2.setPath(child2);
if (done < populationSize - 2) {
this.nextGen[done] = newGenChild1;
this.nextGen[done + 1] = newGenChild2;
this.done += 2;
return false;
} else if (done == populationSize - 2) {
this.nextGen[done] = newGenChild1;
this.nextGen[done + 1] = newGenChild2;
done += 2;
return true;
} else {
this.nextGen[done] = newGenChild1;
done += 1;
return true;
}
}
public Path[] getNextGen() {
return nextGen;
}
public void setNextGen(Path[] nextGen) {
this.nextGen = nextGen;
}
public City[] Mutation(City[] child) {
int check = RandomNum(0, 100);
//Checks if its going to mutate
if (check <= (mutationRate * 100)) {
//finds the 2 cities that "mutate"
int point1 = RandomNum(0, numCities - 1);
int point2 = RandomNum(0, numCities - 1);
while (point2 == point1) {
point2 = RandomNum(0, numCities - 1);
}
//Cities are switched as result of mutation
City city1 = child[point1];
City city2 = child[point2];
child[point1] = city2;
child[point2] = city1;
}
return child;
}
public int RandomNum(int min, int max) {
return min + (new Random()).nextInt(max - min);
}
public void FitnessOrder() {
Arrays.sort(population);
// double cost = calculateTotalCost();
for (int i = 0; i < population.length; i++) {
// double total = cost - population[i].getCost();
// double fitness = (total * 100) / cost;
// fitness = 100 - fitness;
// population[i].setFitness(fitness);
int lol = 100000 / (population[i].getCost() + 1);
population[i].setFitness(lol);
// System.out.println("Total: "+total + " "+" Cost: "+cost+" "+" Fitness: "+fitness+"%" );
}
}
public int calculateTotalFitness() {
int cost = 0;
for (int i = 0; i < population.length; i++) {
cost += population[i].getFitness();
}
return cost;
}
public double getCrossoverRate() {
return crossoverRate;
}
public void setCrossoverRate(double crossoverRage) {
this.crossoverRate = crossoverRage;
}
public Path[] getPopulation() {
return population;
}
public void setPopulation(Path[] population) {
this.population = population;
}
public int getPopulationSize() {
return populationSize;
}
public void setPopulationSize(int populationSize) {
this.populationSize = populationSize;
}
public int getNumCities() {
return numCities;
}
public void setNumCities(int numCities) {
this.numCities = numCities;
}
}
package ga;
public class City {
private int x;
private int y;
private int id;
public City(int id,int x, int y){
this.x=x;
this.y=y;
this.id=id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int distance(int xOther,int yOther){
return (int) Math.sqrt(((this.x-xOther)*(this.x-xOther))+((this.y-yOther)*(this.y-yOther)));
}
}
I have class Book with three fields - name, author and isbn
I`m trying to insert the fields in ArrayList and to print:
book1, author1, isbn
book2, author2, isbn2
and... to 10
code:
public class InsertBooks {
private static ArrayList<String> booksNames = new ArrayList<>();
private static ArrayList<String> booksAuthors = new ArrayList<>();
private static ArrayList<Integer> booksIsbn = new ArrayList<>();
private static ArrayList<Book> books = new ArrayList<>();
// adding books in ArrayList booksNames
private static void addBooksNames() {
for (int i = 0; i < 10; i++) {
booksNames.add("Book" + i);
}
}
// adding author in ArrayList booksAuthors
private static void addBooksAuthor() {
for (int i = 0; i < 10; i++) {
booksAuthors.add("Author" + i);
}
}
// adding author in ArrayList booksAuthors
private static void addBooksIsbn() {
for (int i = 0; i < 10; i++) {
booksIsbn.add(Integer.valueOf("isbn" + i));
}
}
public static void fillArrayListOfBooks() {
for (int i = 0; i < 10; i++) {
books.add(new Book((addBooksNames(), addBooksAuthor(), addBooksIsbn()));
}
}
}
You want to call all your add* functions first. Then in the loop of fillArrayListOfBooks() use those values.
void fillArrayListOfBooks()
{
addBooksNames();
addBooksAuthor();
addBooksIsbn();
for (int i = 0; i < 10; i++) {
dbooks.add(new Book(booksNames.get(i), booksAuthors.get(i), booksIsbn.get(i)));
}
}
You could easily get rid of those lists (unless you need them later):
void fillArrayListOfBooks()
{
for (int i = 0; i < 10; i++) {
dbooks.add(new Book("Book" + i, "Author" + i, "isbn" + i));
}
}
I am working on a selection sort in Java. It will prompt a user to enter in 10 names and then sort them alphabetically. It is sorting some of them but not completely and cannot figure out why it is sorting some values and not others. I believe I have implemented the sort and swap correctly but I feel as though I am missing something. Any help is appreciated as always.
import java.util.*;
public class sortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
You are doing your swap too early. You need to wait until the smallest has been determined before swapping. You are swapping whenever you detect a smaller one.
public static void sortNames(String sortArray[]) {
for (int i = 0; i < sortArray.length; i++) {
int smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
// Move this.
//if (smallindex != i)
// swap(sortArray, smallindex, i);
}
}
// To here.
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
private void test() {
String[] names = {"C", "B", "A", "9"};
System.out.println(Arrays.toString(names));
sortNames(names);
System.out.println(Arrays.toString(names));
}
use below changes in your program.
import java.util.*;
public class SortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
//if (smallindex != i) No need here
//swap(sortArray, smallindex, i);
}
}
//place your swaping code here
if (smallindex != i)
swap(sortArray, smallindex, i);
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
after making these changes your program works. your code not works properly because you perform swap early.
So I'm getting this weird error that I can't seem to figure out, and it's way too long to google so my only help is you guys.
This is the error I'm getting:
https://i.imgur.com/5BWeiCk.png
Here's the class:
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Collections;
public class Ordliste {
private ArrayList<String> liste = new ArrayList<String>();
private int teller, total = 0;
public void lesBok (String filnavn) throws Exception{
Scanner fil = new Scanner(new File(filnavn));
while(fil.hasNextLine()){
liste.add(fil.next());
} fil.close();
}
public void leggTilOrd(String ord){
for(int t = 0; t < liste.size(); t++)
if(liste.get(t).equalsIgnoreCase(ord)){
teller++;
} total = total + teller + 1;
System.out.println("Ordet " + ord + " forekommer " + teller + " ganger i ordlisten og har naa blitt oekt til " + total + "!");
if (liste.stream().noneMatch(s -> s.equalsIgnoreCase(ord))){
liste.add(ord);
}
}
public Ord finnOrd(String tekst){
Ord finneord = new Ord(tekst);
for(int t = 0; t < liste.size(); t++)
if(liste.get(t).equalsIgnoreCase(tekst)){
return finneord;
} return null;
}
public int antallOrd(){
Set<String> ulikeOrd = new HashSet<String>(liste);
int unique = ulikeOrd.size();
System.out.println(unique);
return unique;
}
public int antallForekomster(String tekst){
int counter = 0;
for(int t = 0; t < liste.size(); t++)
if(liste.get(t).equalsIgnoreCase(tekst))
counter++;
return counter;
}
public Ord[] vanligste5(){
ArrayList<Ord> oftest = new ArrayList<Ord>();
oftest.add(liste.get(0));
int p = -1;
for(int t = 0; t < liste.size(); t++){
for(int i = 0; i < oftest.size(); i++){
if(liste.get(t).hentAntall() >= oftest.get(i).hentAntall()){
p = i;
break;
}
}
if(p == -1){
oftest.add(liste.get(t));
} else {
oftest.add(p, liste.get(t));
}
} Ord[] array = new Ord[5];
return oftest.subList(0,5).toArray(array);
}
}
Here's the Ord class:
import java.util.Scanner;
import java.io.File;
public class Ord {
private String tekstord;
private int teller = 0;
public Ord(String tekst){
tekstord = tekst.toLowerCase();
teller++;
}
public String toString(){
return tekstord;
}
public int hentAntall() {
return teller;
}
public void oekAntall(){
teller++;
}
public int hentLengde() {
int lengde = tekstord.length();
return lengde;
}
public int plassiDokument(){
int lengde = tekstord.length();
teller = teller * lengde;
return teller;
}
}
You are getting the error because oftest holds list of Ord objects not list of Strings.
You can do something like this oftest.add(new Ord(liste.get(0)));.
In this part of code you have issue:
public Ord[] vanligste5(){
ArrayList<Ord> oftest = new ArrayList<Ord>();
oftest.add(liste.get(0)); // error place
You are trying to add String to collection of Ord. It is not legal operation in java. You should rework this code block according to your specifications.
I tried to reprogramm this and fit it to my needs (calculating n^k with recursion). But something seems faulty, because I first got the txt files without any text in it; now after changing and trying to bugfix I get nothing at all :(
https://www.youtube.com/watch?v=br_TEuE8TbY
package Uebung3;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Hauptthread implements Runnable {
//int start;
//int stop;
boolean haupt=false;
String file;
static int n, k;
public Hauptthread(int startvalue, int stopvalue, String file, boolean h){
n= startvalue;
k=stopvalue;
this.file=file;
haupt=h;
}
public void run(){
ArrayList<Double> binominal=new ArrayList<>();
if (haupt=false) {
for (int i = n; i <= k; i++) {
binominal.add(binomial(n,k));
}
try{
PrintWriter print=new PrintWriter(new File(file));
for (int i = 0; i < binominal.size() ; i++) {
print.println("Test");
print.println(binominal.get(i));
}
}
catch(Exception e){
System.out.println("Error " + e.getMessage());
}
}
}
double binomial(int n, int k) {
if (k == 0) {
return 1; }
else {
return (((double)n/k) * binomial(n-1, k-1)); }
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
package Uebung3;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Uebung3 {
public static int threadcount=4;
public static int n, k;
public static int stop=k;
public static void main(String[] args) {
/*
int n = Integer.parseInt(JOptionPane.showInputDialog("n = "));
int k = Integer.parseInt(JOptionPane.showInputDialog("k = "));
if (n < 0 || k < 0 || k > n) {
JOptionPane.showMessageDialog(null, "Ungueltige Eingabe"); }
else {
JOptionPane.showMessageDialog(null, "Rechne" );
//JOptionPane.showMessageDialog(null, "n über k = " +binomial(n, k));
}
*/
System.out.println("Erstelle Threads...");
int erhoehe=20/threadcount;
int start=2;
ArrayList <Thread> threads = new ArrayList<>();
for (int i = 0; i < threadcount; i++) {
//if(!((i+1)==threadcount)){
if(start==10){
threads.add(new Thread(new Hauptthread(start, erhoehe, i+".txt",false)));
}
else {
threads.add(new Thread(new Hauptthread(start, erhoehe, i+".txt",true)));
}
}
for (int i = 0; i < threads.size(); i++) {
threads.get(i).start();
}
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (Exception e) {
System.out.println("Error" +e.getMessage());
}
}
}
}