So I wrote this Bubblesort code and everything is working fine, but now I want to split this up into two classes and I can't find out how to do this.
import java.util.Arrays;
public class bubblesorter
{
public static int[] bubblesort(int[] zusortieren) {
int temp;
for(int i=1; i<zusortieren.length; i++) {
for(int j=0; j<zusortieren.length-i; j++) {
if(zusortieren[j]<zusortieren[j+1]) {
temp=zusortieren[j];
zusortieren[j]=zusortieren[j+1];
zusortieren[j+1]=temp;
}
}
}
return zusortieren;
}
public static void main(String[] args) {
int[] unsortiert={1,5,8,2,7,4};
int[] sortiert=bubblesort(unsortiert);
for (int i = 0; i<sortiert.length; i++) {
System.out.print(sortiert[i] + ", ");
}
}
}
Thanks for your help.
I think you want something like this:
Main class
public class Main
{
public static void main(String[] args) {
int[] unsortiert={1,5,8,2,7,4};
int[] sortiert=BubbleSort.sort(unsortiert);
for (int i = 0; i<sortiert.length; i++) {
System.out.print(sortiert[i] + ", ");
}
}
}
Sort class
public class BubbleSort {
public static int[] sort(int[] zusortieren) {
int temp;
for(int i=1; i<zusortieren.length; i++) {
for(int j=0; j<zusortieren.length-i; j++) {
if(zusortieren[j]<zusortieren[j+1]) {
temp=zusortieren[j];
zusortieren[j]=zusortieren[j+1];
zusortieren[j+1]=temp;
}
}
}
return zusortieren;
}
}
Just copy paste your main into it's own file.
Main.java
public class Main
{
public static void main(String[] args) {
int[] unsortiert={1,5,8,2,7,4};
int[] sortiert=BubbleSort.sort(unsortiert);
for (int i = 0; i<sortiert.length; i++) {
System.out.print(sortiert[i] + ", ");
}
}
}
BubbleSort.java
public class BubbleSort {
public static int[] sort(int[] zusortieren) {
int temp;
for(int i=1; i<zusortieren.length; i++) {
for(int j=0; j<zusortieren.length-i; j++) {
if(zusortieren[j]<zusortieren[j+1]) {
temp=zusortieren[j];
zusortieren[j]=zusortieren[j+1];
zusortieren[j+1]=temp;
}
}
}
return zusortieren;
}
}
As long as you refer to both files in the javac call when it comes time to compile, it'll all work nicely. However, for the sake of not being messy, some structure is good to have. Later in your Java experience, you'll be hearing about tools like Maven and Gradle, so I suggest getting in the habit of using their folder formats:
ProjectName/
src/main/java/
LuisIsLuis/Awesome/Package/
Main.java
BubbleSort.java
I did not follow "pretty package naming" conventions, I figure you'll learn that on your own later. The only thing you need to do with the files themselves is put package LuisIsLuis.Awesome.Package; as the first line in both files when organizing your code in this manner; if you're curious as to why, go look up package naming standards. That being said, your coursework will probably cover that soon.
It is pretty straight forward and depends on what you want to achieve. If you have a helper class with static methods, then add static method BubbleSorter to it and access it like rmpt mentioned above. Otherwise, you can store the method in a separate class BubbleSorter.java and access it via an instance of the class.
public class Main
{
int[] unsortiert={1,5,8,2,7,4};
Bubblesorter bubble = new Bubblesorter();
int [] sortiert = bubble.bubblesort(unsortiert);
for (int i = 0; i<sortiert.length; i++) {
System.out.print(sortiert[i] + ", ");
}
}
public class Bubblesorter
{
public int[] bubblesort(int[] zusortieren) {
int temp;
for(int i=1; i<zusortieren.length; i++) {
for(int j=0; j<zusortieren.length-i; j++) {
if(zusortieren[j]<zusortieren[j+1]) {
temp=zusortieren[j];
zusortieren[j]=zusortieren[j+1];
zusortieren[j+1]=temp;
}
}
}
return zusortieren;
}
}
Related
I am new to Java so this could be a naive question. I created a Main class like below, and I would like to write some tests for the getArrays, getAverage, and bubbleSortAscending methods, just for the purpose of learning how to do unit tests.
public class Main {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String [] args) {
int[] myArrays = getArrays(5);
for (int i=0; i<myArrays.length; i++) {
System.out.println("index = " + i + " value = " + myArrays[i]);
}
System.out.println("Average is " + getAverage(myArrays));
int[] sortedArray = bubbleSortAscending(myArrays);
System.out.println("Sorted: \r");
for (int i=0; i<sortedArray.length; i++) {
System.out.println(sortedArray[i]);
}
}
public static int[] getArrays(int number) {
System.out.println("Enter " + number + " integer values.\r");
int[] values = new int[number];
for (int i=0; i<values.length; i++){
values[i] = scanner.nextInt();
}
return values;
}
public static double getAverage(int[] array) {
double sum = 0;
for (int i=0; i<array.length; i++){
sum += array[i];
}
return sum / (double) array.length;
}
public static int[] bubbleSortAscending(int[] array) {
for (int i=0; i<array.length-1; i++){
for (int j=0; j<array.length - i - 1; j++){
int a = array[j];
int b = array[j+1];
if (a > b) {
int c = a;
a = b;
b = c;
}
array[j] = a;
array[j+1] = b;
}
}
return array;
}
}
And IntelliJ automatically generated these test codes for me:
public class MainTest {
#org.junit.Test
public void getArrays() {
}
#org.junit.Test
public void getAverage() {
}
#org.junit.Test
public void bubbleSortAscending() {
}
}
However, when I filled the first one with codes like this:
#org.junit.Test
public void getArrays() {
int[] expectedArray = new int[]{1,2,3,4,5};
int[] generatedArray = getArrays(5);
assertArrayEquals(expectedArray, generatedArray);
}
IntelliJ told me that something is wrong ...
So looks like it's because the getArrays() inside the MainTest is not taking any input argument? Why the getArrays() in the MainTest is not working the same as the getArrays() defined in the Main?
The issue is that you are recursively calling (by mistake) the test method itself, which happens to have the same method name as the tested method.
The test method (MainTest.getTest()), in contrary to the tested method (Main.getTest(int)) does not have any parameter - hence the error message, that you cannot pass the int to that method.
You have to call the tested static method by specifying the class:
#Test
public void getArrays() {
...
int[] generatedArray = Main.getArrays(5); // Call getArrays(int) in Main class
...
}
or change the method name, you will probably have more than one test method anyways:
#Test
public void getArraysReturnsNull() { ... }
// OR
#Test
public void testGetArrays() { ... }
...
Now you can use static import and call tested static method without clasifying the class:
import static segovia.java.learn.Main.getArrays;
#Test
public void testGetArrays() {
int[] generatedArray = getArrays(); // OK now
}
IntelliJ tip:
Hold CTRL and click on the method name.
I am trying to run my project, but the main class isn't being found. Whats wrong? Here's my code.
public class ArrayPrinter {
public static void printArray(int[] arr) {
int size = arr.length;
System.out.print("[");
for(int i=0;i< size; i++){
System.out.print(arr[i]);
if(i<size-1){
System.out.print(",");
}
}
System.out.println("]");
}
}
You need a main method, not class. See below:
public class ArrayPrinter {
public static void main(String[] args){
//Sample use
int[] arr = new int[2];
arr[0] = 4;
arr[1] = 2;
printArray(arr);
}
public static void printArray(int[] arr) {
int size = arr.length;
System.out.print("[");
for(int i = 0;i < size; i++){
System.out.print(arr[i]);
if (i < size-1){
System.out.print(",");
}
}
System.out.println("]");
}
}
The signature of the main function always looks the same:
public class ArrayPrinter {
public static void main(String[] args) {
// put code here
}
public static void printArray(int[] arr) {
int size = arr.length;
System.out.print("[");
for(int i=0;i< size; i++){
System.out.print(arr[i]);
if(i<size-1){
System.out.print(",");
}
}
System.out.println("]");
}
}
You need to have a main method in order to run a Java application.
The signature of the main method is
public static void main (String[] args)
More info can be found
here
I have a small java program that collects 10 words written by a user and prints them in specified orders. As it stands, the program works, but it is not cohesive.
My issue stems from not knowing enough about the concept of cohesion to work on fixing this, as well as being new to Java/OO languages.
I believe that the class Entry is way way way too cluttered, and that another class should take on some of this class' functions.
Any hint or clue, cryptic or otherwise would be greatly appreciated!
The lack of a input reader in Dialogue.java is intentional, as the original code uses proprietary code.
These are the three classes: entry, dialogue and printer.
Entry.java
public class Entry {
public static void main(String[] args){
String[] wordArray = new String[10];
Dialogue d = new Dialogue();
wordArray = d.read(wordArray);
Printer p = new Printer();
p.printForwards(wordArray);
p.printBackwards(wordArray);
p.printEveryOther(wordArray);
}
}
Dialogue.java
public class Dialogue {
public String[] read(String[] s){
String[] temp;
temp = new String[s.length];
for(int i=0;i<s.length;i++){
String str = anything that reads input("Enter word number" + " " + (i+1));
temp[i] = str;
}
return temp;
}
}
Printer.java
public class Printer {
public void printForwards(String[] s){
System.out.println("Forwards:");
for(int i=0;i<s.length;i++){
System.out.print(s[i] + " ");
if(i==s.length-1){
System.out.println("");
}
}
}
public void printBackwards(String[] s){
System.out.println("Backwards:");
for(int i=s.length-1;i>=0;i--){
System.out.print(s[i]+ " ");
if(i==0){
System.out.println("");
}
}
}
public void printEveryOther(String[] s){
System.out.println("Every other:");
for(int i = 0; i < s.length; i++){
if(i % 2 == 0){
System.out.print(s[i] + " ");
}
}
}
}// /class
It looks okay overall, the truth is it is a very simple task where as OOP is better suited for more complex programs. That being said, here are a few pointers/examples.
You can also do your printing more OOP style.
The purpose of this is build reusable, modular code. We do this by abstracting String array manipulations (which previously existed in the Printer class) to it's own class.
This is also very similar/also known as loose-coupling. We achieve loose-coupling by splitting the string processing functionality and the printing functionality.
Change you Printer class to StringOrderer or something along those lines:
public class StringOrderer {
private String[] array;
public class StringOrderer(String[] array) {
this.array = array;
}
public String[] getArray() {
return array;
}
public String[] everyOther(){
String[] eos = new String[array.length];
for(int i = 0; i < s.length; i++){
if(i % 2 == 0){
eos[eos.length] = s[i];
}
return eos;
}
public String[] backwards() {
...
And then in your main class add a method like such:
private static void printStringArray(String[] array) {
for (int i=0; i<array.length; i++) {
System.out.print(array[i]);
}
}
Then call it in your main method:
StringOrderer s = new StringOrderer(wordArray);
System.out.println('Forward:');
printStringArray(s.getArray());
System.out.println('Every other:');
printStringArray(s.everyOther());
System.out.println('Backwards:');
...
Extra tip - You can also add methods in your main class like so:
public class Entry {
public static void main(String[] args){
String[] wordArray = readWordArray()
Printer p = new Printer();
p.printForwards(wordArray);
p.printBackwards(wordArray);
p.printEveryOther(wordArray);
}
private static String[] readWordArray() {
Dialogue d = new Dialogue();
return d.read(new String[10]);
}
}
to make it more readable.
Receiving 5,9,7 as output.. Where as the expected should be only 9..Below is the code:
public class GreatestNoInArray {
public static void main(String[] args) {
int a[]= new int[] {1,2,5,9,7};
int big=a[0];
for (int i=1; i<a.length; i++){
if (big<a[i])
big=a[i];
System.out.println(a[i]);
}
}
}
Please help
for expected answer you need to print big (not a[i]) out side of loop
public class GreatestNoInArray {
public static void main(String[] args) {
int a[]= new int[] {1,2,5,9,7};
int big=a[0];
for (int i=1; i<a.length; i++){
if (big<a[i])
big=a[i];
}
System.out.println(big);
}
}
code should be like this:
public class GreatestNoInArray {
public static void main(String[] args) {
int a[] = new int[] {1,2,5,9,7};
int big = a[0];
for (int i=1; i<a.length; i++){
if (big < a[i])
big = a[i];
//System.out.println(a[i]);
}
System.out.println("Big: " + big);
}
}
This works!
I am attempting to write a simple Genetic Algorithm in Java after reading a book on Machine Learning and have stumbled on the basics. I'm out of practice with Java so I'm probably missing something extremely simple.
Individual
public class Individual {
int n;
int[] genes = new int[500];
int fitnessValue;
public int getFitnessValue() {
return fitnessValue;
}
public void setFitnessValue(int fitnessValue) {
this.fitnessValue = fitnessValue;
}
public int[] getGenes() {
return genes;
}
public void setGenes(int index, int gene) {
this.genes[index] = gene;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
// Constructor
public Individual() {
}
}
Population
import java.util.Random;
public class Population {
public Population() {
}
public static void main(String[] args) {
Random rand = new Random();
int p = rand.nextInt(10);
int n = rand.nextInt(10);
Individual pop[] = new Individual[p];
System.out.println("P is: " + p + "\nN is: " + n);
for(int j = 0; j <= p; j++) {
for(int i = 0; i <= n; i++) {
pop[j].genes[i] = rand.nextInt(2);
}
}
}
public void addPopulation() {
}
}
The aim of this code is to populate the Population and the Genes with a random number. Could someone please take a look at my code to see where I'm going wrong?
before
pop[j].genes[i] = rand.nextInt(2);
add
pop[j] = new Individual();
the elements of the array are null.
I believe you need to initialize pop[j] before doing pop[j].genes[i] = rand.nextInt();
Individual pop[] = new Individual[p];
This just initializes the array, not the individual elements. Try to put pop[j] = new Individual() between your two loops.
What they said...
Also, do you mean to call your setGenes method, or do you just want to directly access the gene array.
From what I understand of your code I think you need to do this:
for(int j = 0; j <= p; j++) {
pop[j] = new Individual();
for(int i = 0; i <= n; i++) {
pop[j].setGenes(i, rand.nextInt(2));
}
}