Trouble with Sort program using objects and constructors - java

Really new to java wanted to make my separate sorting methods (they all work hopefully i did them right)
Also very new to objects and constructors hopefully what im talking about is an object
so here are the constructors
public class sort{
public int[] selectsort(int[] num)
{
int j,i,key,min;
for(j = 0; j<num.length; j++)
{
key = num[j];
min = j;
for(i=j+1; i<num.length; i++)
{
if(num[i]<num[min])
{
min = i;
}
}
num[j] = num[min];
num[min] = key;
}
return num;
}
public int[] insertsort(int[] num)
{
int j,i,key;
for(j = 1; j<num.length; j++)
{
key = num[j];
for(i=j-1; i>=0 && num[i]>key; i--)
{
num[i+1]=num[i];
}
num[i+1]=key;
}
return num;
}
public static int[] bubblesort(int[] num)
{
int i,j,ini;
for(i = num.length-1; i>1; i--)
{
for(j=0;j<i; j++)
{
if(num[j]>num[j+1])
{
ini = num[j];
num[j]=num[j+1];
num[j+1]=ini;
}
}
}
return num;
}
}
and the program/test
import java.util.Arrays;
public class sorttest{
public static void main(String[] args)
{
int[] num = new int[]{9,1,4,5,6,2,3,7,8};
System.out.println(Arrays.toString(selectsort(num)));
}
}
javac sort.java compiles but javac sorttest.java doesnt
error:
sorttest.java:9: cannot find symbol
symbol : method selectsort(int[])
location: class sorttest
System.out.println(Arrays.toString(selectsort(num)));
^
1 error

The method selectsort is not a part of the sorttest class - it's a public static method in the sort class. This means you need to qualify it by its class name:
import java.util.Arrays;
public class sorttest{
public static void main(String[] args) {
int[] num = new int[]{9,1,4,5,6,2,3,7,8};
System.out.println(Arrays.toString(sort.selectsort(num)));
}
}
Alternatively, you could use a static import:
import static sort.selectsort;
import java.util.Arrays;
public class sorttest{
public static void main(String[] args) {
int[] num = new int[]{9,1,4,5,6,2,3,7,8};
System.out.println(Arrays.toString(selectsort(num)));
}
}

Related

Print Random Generated Sudoku Java

I am having troubles printing the generated Sudoku on this program. Every time I try to print it, it says "null". Originally the code doesn't have the main method so I added one.
class GenerateSudoku{
public static int[][][] sudoku;
public static Random rand=new Random();
GenerateSudoku(int[][][] sudoku){
this.sudoku=sudoku;
for(int ctr=0; ctr<sudoku.length; ctr++){
for(int ct=ctr; ct<sudoku.length; ct++){
double first=rand.nextDouble(), second=rand.nextDouble();
if(first>1-second){
this.sudoku[ct][ctr][0]=0;
this.sudoku[ct][ctr][1]=1;
}
else{
this.sudoku[ct][ctr][1]=0;
}
if(ct!=ctr && first>1-second){
this.sudoku[ctr][ct][0]=0;
this.sudoku[ctr][ct][1]=1;
}
else if(ct!=ctr){
this.sudoku[ctr][ct][1]=0;
}
}
}
}
public int[][][] getSudoku(){
return sudoku;
}
private void sop(Object obj){
System.out.println(obj+"");
}
public static void main(String[] args) {
System.out.println(sudoku);
}
}
As discussed in the comments, you should create an instance of the GenerateSudoku class and get the resulting sudoku from getSudoku() method:
import java.util.Random;
class GenerateSudoku{
public static int[][][] sudoku;
public static Random rand=new Random();
GenerateSudoku(int[][][] sudoku){
this.sudoku=sudoku;
for(int ctr=0; ctr<sudoku.length; ctr++){
for(int ct=ctr; ct<sudoku.length; ct++){
double first=rand.nextDouble(), second=rand.nextDouble();
if(first>1-second){
this.sudoku[ct][ctr][0]=0;
this.sudoku[ct][ctr][1]=1;
}
else{
this.sudoku[ct][ctr][1]=0;
}
if(ct!=ctr && first>1-second){
this.sudoku[ctr][ct][0]=0;
this.sudoku[ctr][ct][1]=1;
}
else if(ct!=ctr){
this.sudoku[ctr][ct][1]=0;
}
}
}
}
public int[][][] getSudoku(){
return sudoku;
}
private void sop(Object obj){
System.out.println(obj+"");
}
public static void main(String[] args) {
int[][][] sudoku = new int[9][9][2];
GenerateSudoku generator = new GenerateSudoku(sudoku);
sudoku = generator.getSudoku();
for(int i = 0 ; i < sudoku.length; i++) {
for(int j = 0 ; j < sudoku.length; j++) {
System.out.print(sudoku[i][j][1]);
}
System.out.println();
}
}
}
Generates:
110110011
100010111
001111100
101110010
111101111
001011100
011011000
110110000
110010001

How to access an array from another class

I want to operate on the array called "players" that is declared in the main method. I want to use "players" in my class called "Glucksspielthread"
I know that I can't access "players" because it is declared in the main method and is not visible for other classes.
How can I solve this problem? Here is my code:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Glucksspieltest {
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
Glucksspielthread[] players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
class Thinker {
public static void think(int Millisekunden) {
try {
Thread.sleep(Millisekunden);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void randomThink(int minMillisekunden, int maxMillisekunden) {
System.out.println("test");
}
}
class Glucksspielthread implements Runnable {
public int playerNumber;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
}
}
}
Just for your test purpose make your players variable static and public in the Glucksspieltest class, like this:
public class Glucksspieltest {
public static Glucksspielthread[] players;
Then acces it in the Glucksspielthread class like this:
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
Glucksspieltest.players
}
Add a method to class Glucksspieltest, and make the players array global:
public class Glucksspieltest {
private static Glucksspielthread[] players;
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
This way you can get the array by calling the getPlayers() method.
(Note that, it would be adviced to add a constructor to initialize and fill the players array, and separate the player management from the main method as well.)
Make players as private global referance variable
public class Glucksspieltest {
//Make a Global reference variable players
private static Glucksspielthread[] players;
// Make a getter Method to get players
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
And access it by Glucksspieltest.getPlayers();
class Glucksspielthread implements Runnable {
public int playerNumber;
private static Glucksspielthread[] players;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
players= Glucksspieltest.getPlayers(); // play with players
}
}
}

Setting ArrayList items in one Class from another Class

There is a foo class with an ArrayList of double msg called msgstoboo as well as a method setMsg(int index, double input) to alter individual messages in msgstoboo.
There is a networkoffoos class with an ArrayList of foo objects called listoffoos. There is an updatefoomsg method:
public void updatefoomsg (ArrayList<ArrayList<Foo>> Foonetwork)
{
for(int foolayer = 0; foolayer< foonetwork.size(); foolayer++)
for(int fooinlayer = 0; fooinlayer< foonetwork.get(foolayer).size(); fooinlayer++)
for(int msginfoo = 0; msginfoo < foonetwork.get(foolayer).get(fooinlayer).msgstoboo.size(); msginfoo++)
Foonetwork.get(foolayer).get(fooinlayer).setMsg(msginfoo,somerandomvalue)
}
The goal of updatefoomsg is to change the values of individual msgs in msgstooboo. However, no values in the foo class ArrayList `msgstoboo' are altered. Why is this and how do I fix it? Thank you in advance.
UPDATE: Here are the whole foo and networkoffoos classes
public class foo
{
ArrayList<Double> msgstoboo = new ArrayList<Double>(Double);
public foo(int numofmessages)
{
for (int i = 0; i < numofmessages; i++)
{
msgstoboo.add(1);
}
}
public void setMsg(int index, double input)
{
msgstoboo.set(index,input);
}
&&
public class networkoffoos
{
ArrayList<ArrayList<foo>> foonetwork = new ArrayList<ArrayList<foo>>();
public void networkoffoos(int numoffoos)
{
for(int i = 0; i < numoffoos; i++)
foonetwork.add(new foo(somenumberofmsgs))
}
//**AND THE "updatefoomsg" method included in this post**
}
The following works for me. Made some small changes because your code wouldn't compile. Hope it helps.
import java.util.ArrayList;
public class test {
private static ArrayList<ArrayList<Foo>> foonetwork = new ArrayList<ArrayList<Foo>>();
public static void main(String[] args){
networkoffoos(5);
updatefoomsg(foonetwork);
}
public static void networkoffoos(int numoffoos) {
for(int i = 0; i < numoffoos; i++) {
ArrayList<Foo> fooArrayList = new ArrayList<Foo>();
fooArrayList.add(new Foo(10));
foonetwork.add(fooArrayList);
}
}
public static void updatefoomsg (ArrayList<ArrayList<Foo>> foonetwork) {
for(int foolayer = 0; foolayer< foonetwork.size(); foolayer++)
for(int fooinlayer = 0; fooinlayer< foonetwork.get(foolayer).size(); fooinlayer++)
for(int msginfoo = 0; msginfoo < foonetwork.get(foolayer).get(fooinlayer).msgstoboo.size(); msginfoo++)
foonetwork.get(foolayer).get(fooinlayer).setMsg(msginfoo,3);
}
}
and your Foo class
import java.util.ArrayList;
public class Foo {
ArrayList<Double> msgstoboo = new ArrayList<Double>();
public Foo(int numofmessages) {
for (int i = 0; i < numofmessages; i++) {
msgstoboo.add(Double.valueOf(1));
}
}
public void setMsg(int index, double input) {
msgstoboo.set(index, input);
}
}

static reference on a non-static object error in eclipse

Eclipse is giving me the static referencing a non-static object error when I try to call isOdd() from Number.java but since isOdd() doesn't contain any arguments, I can't call the outside method as I usually would.
NumberAnalyzer.java
import java.util.ArrayList;
import java.util.Scanner;
import com.sun.xml.internal.ws.api.pipe.NextAction;
import static java.lang.System.*;
public class NumberAnalyzer
{
private ArrayList<Number> list;
public NumberAnalyzer()
{
}
public NumberAnalyzer(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
System.out.println(list);
}
public void setList(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
}
public int countOdds()
{
int oddCount=0;
for(int i = 0; i < list.size(); i++){
if(Number.isOdd()== true){
oddCount++;
}
}
return oddCount;
}
public int countEvens()
{
int evenCount=0;
return evenCount;
}
public int countPerfects()
{
int perfectCount=0;
return perfectCount;
}
public String toString( )
{
return "";
}
}
Number.java
public class Number
{
private Integer number;
public Number()
{
}
public Number(int num)
{
number = num;
}
public void setNumber(int num)
{
number = num;
}
public int getNumber()
{
return number;
}
public boolean isOdd()
{
if(number%2==0){
return false;
}
return true;
}
public boolean isPerfect()
{
int total=0;
for(int i = 1; i < number; i++){
if(number%i==0){
total+= i;
}
}
return (number==total);
}
public String toString( )
{
String output = getNumber() + "\n" + getNumber()+ "isOdd == " + isOdd() + "\n" + getNumber()+ "isPerfect==" + isPerfect()+ "\n\n";
return output;
}
}
runner class
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.*;
public class Lab16b
{
public static void main( String args[] )
{
NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
//add more test cases
}
}
You seem to have list global. Just do
for(int i = 0; i < list.size(); i++){
if(list.get(i).isOdd()){
oddCount++;
}
}
That way you're actually getting a Number from list and can call the isOdd() method.
Note that you don't need the == true check.
Number.isOdd applys to a Number instance. As your for loop is covering the range of indices for the List (list) of Numbers, you can replace
if (Number.isOdd() == true) {
with
if (list.get(i).isOdd() == true) {
or better
if (list.get(i).isOdd()) {

Constructor for array of variable size

I want to code a constructor for an array of size x with x being a parameter speciified in main().
My class:
public class CharA
{
private char[] stack;
private int n = 0;
public void CharA (int max)
{
this.stack = new char[max];
this.n = max;
}
My main():
public class CharTest
{
public static void main (String args)
{
CharA stack1 = new CharA(100);
}
}
The error:
CharTest.java:5: cannot find symbol
symbol : constructor CharA(int)
location: class CharA
CharA stack1 = new CharA(100);
^
There are several examples here where the same thing is done with an int array. Why doesn't it work for this char array?
remove void in your "constructor":
public CharA (int max) {
// ...
}
Replace public void CharA (int max) with public CharA (int max), because constructors don't have a return type.
The constructor method should not have a return type in its definition:
public CharA(int max) {...}

Categories