I am learning Java and I am doing some C++ codes into java, I am following this webpage http://uva.onlinejudge.org and trying to do some of the problems in Java. Now I am doing this problem http://uva.onlinejudge.org/index.phpoption=com_onlinejudge&Itemid=8&page=show_problem&problem=1072 and after researching and figure out how to do it on paper I found this webpage where the problems seems easy to follow:
http://tausiq.wordpress.com/2010/04/26/uva-10131/
But now, and due to the fact I am new on Java, I want to learn how to do an array of struct in Java. I now I can do a class like a struct: if this is in C++
struct elephant {
int weight;
int iq;
int index;
} a [1000 + 10];
I can do this in Java:
public class Elephant {
private int _weight;
private int _iq;
private int _index;
public Elephant(int weight, int iq, int index) {
this._weight = weight;
this._iq = iq;
this._index = index;
}
public int getWeight() {
return this._weight;
}
public int getIQ() {
return this._iq;
}
public int getIndex() {
return this._index;
}
public void setWeigth(int w) {
this._weight = w;
}
public void setIQ(int iq) {
this._iq = iq;
}
public void setIndex(int i) {
this._iq = i;
}
}
But I don't know how I can turn this into the last part of the struct in c++:
a [1000 + 10];
I mean, having an array of a objects of the class Elephant in Java like having an array of elements elephants in c++
Could someone help me to understand it better..
Arrays of objects in Java are accomplished the same way as an array of primitives. The syntax for this would be
Elephant[] elephants = new Elephant[1000+10];
This will initialize the array, but it will not initialize the elements. Any index into the array will return null until you do something like:
elephants[0] = new Elephant();
This should be what you are loking for :
Elephant [] array = new Elephant[1010];
Related
I am new to Java and really like the challenge. Currently I'm trying to build a game that contains 3 classes (Warrior, Mage, Rouge) which the player can choose from. Therefore I created a constructor for the Basics (Health, Mana, Stamina) and subclasses for Warrior, Mage and Rouge.
I'd like to print the choice for the player, but unfortunately it won't work. Maybe someone can show me the right way.
This is the super class. Don't get confused by the german notations. :D
public class Klassen {
String Klasse;
int Vitalitat; //Health
int Mana;
int Ausdauer; //Stamina
Klassen(String k, int v, int m, int a) {
Klasse = k;
Vitalitat = v;
Mana = m;
Ausdauer = a;
}
String getKlasse() {return Klasse;} //choice of classes
int getVit() {return Vitalitat;}
int getMana() {return Mana;}
int getAusdauer() {return Ausdauer;}
void setVit(int v) {Vitalitat =v;}
void setMana(int m) {Mana = m;}
void setAusdauer(int a) {Ausdauer = a;}
void setKlase(String k) {Klasse = k;}
void showBasic() {
System.out.println("Vitalitaet: " + Vitalitat);
System.out.println("Mana: " + Mana);
System.out.println("Ausdauer " + Ausdauer);
}
Here an example of a subclass :
public class Krieger extends Klassen {
int Starke;
Krieger(int v, int m, int a, int s) {
super("Krieger", v, m, a);
Starke = s;
}
int getStarke() {return Starke;}
void setStarke(int s) {Starke = s;}
void showStarke() {
System.out.println("Starke: " + Starke);
}
}
The next step is to create an array to hold all the three choices:
Klassen[] fillKlassen() { //filling the array
Klassen[] Auswahl = new Klassen[3];
Auswahl[0] = new Krieger(0,0,0,0); //Warrior
Auswahl[1] = new Magier(0,0,0,0); //Mage
Auswahl[2] = new Waldlaufer(0,0,0,0); //Rouge
return Auswahl;
}
The last step should be to create a method that prints the content of the arrays.
I guess something similar to:
class KlassenAuswahl {
Klassen[] fillKlassen() {
Klassen[] Auswahl = new Klassen[3];
Auswahl[0] = new Krieger(0,0,0,0); // Eclipse can't use that reference and wants me to change it to Klassen(int,int,int)
Auswahl[1] = new Magier(0,0,0,0);
Auswahl[2] = new Waldlaufer(0,0,0,0);
return Auswahl;
}
void showKlassen() {
for(int i = 0; i < fillKlassen().length; i++) {
System.out.println(fillKlassen()[i].getKlasse());
}
}
The main goal is to implement this method in my main() Method but this won't work properly. Can someone help me out?
Edit: The main problem seems to be that I get a nullpointer.exception. This may a result of an empty array I guess? The next thing is that I can't implement the showAuswahl() in my main() perhaps because its inside in the constructor class. Therefore I need to create a new class outside of it. But outside of the constructor I can't use my subclasses...
Cheers
namelessshameless
I got the solution. Needed to change my subclasses to static :)
Im trying to code an algorithm that can learn by his experiences (in the game connect four). For that I wanted to save all the single steps in a List. But if I am adding Elements to my List, Every Element in the List gets overridden by the Element i am adding. I have no clue why this is like this and even after 1Hour searching I dont know why, because there is no static field in my Runde.java. The code is here: (Im German so dont be suprised by that weird names for the variables)
package me;
public class Runde{
private int[][] spielfeld;
private int[][] x= new int[7][5];
private int lastx;
private int lasty;
public Runde(int[][] spielfeld1, int xi, int jetzgzuege, int y){
spielfeld=spielfeld1;
lastx=xi;
x[xi][4]=jetzgzuege;
lasty=y;
}
public boolean equal(int[][] spielfeld){
if(spielfeld.equals(spielfeld)){
return true;
}else{
return false;
}
}
public void finishround(boolean sieg, int geszuege){
x[lastx][0]+=1;
if(sieg){
x[lastx][1]+=1;
x[lastx][2]+=geszuege;
}else{
x[lastx][3]+=geszuege;
}
}
public int[][] getSpielfeld(){
return spielfeld;
}
public int[][] getData(){
return x;
}
public int getlastx(){
return lastx;
}
public int getlasty(){
return lasty;
}
}
static ArrayList<Runde> liste= new ArrayList<Runde>();
static ArrayList<Runde> Steps= new ArrayList<Runde>();
static void erzeugeGen(){
int[][] spielfeld=leeresSperzeugen();
int x=0;
int y=0;
int zug=0;
int rand = new Random().nextInt(2);
boolean player;
if(rand==1){
player = true;
}else{
player=false;
}
while(!winner(spielfeld,x,y) && zug<42){
zug++;
player=!player;
Runde r;
if(player){
r= Computerzug(spielfeld.clone(),1,zug); // If i have a look in to the spielfeld in this element, its fine
Steps.add(r); // But after adding like this, its overridden :(
}else{
r= Computerzug(spielfeld.clone(),2,zug);
}
x=r.getlastx();
y=r.getlasty();
if(player){
spielfeld[y][x]=1;
}else{
spielfeld[y][x]=2;
}
}
if(zug<42){
GenAuswerten(zug,player);
zuege+=zug;
}else{
gen--;
}
}
static void GenAuswerten(int zug, boolean win){
for(Runde r: Steps){
r.finishround(win, zug);
ArrayList<Runde> removal = new ArrayList<Runde>();
for(Runde r2 : liste){
if(r2.equal(r.getSpielfeld())){
removal.add(r2);
}
}
for(Runde r3: removal){
liste.remove(r3);
}
}
for(Runde r: Steps){
liste.add(0,r);
}
Steps.clear();
}
you will need to clone the 2nd level arrays when you clone this
r= Computerzug(spielfeld.clone(),1,zug);
so the correct code is
int spielfeldclone[][] = new int[spielfeld.length][];
int i = 0;
for(int[] spielfeldArray: spielfeld){
spielfeldclone[i] =spielfeldArray.clone()lone();
i++;
}
r= Computerzug(spielfeldclone,1,zug);
the reason is that you are doing shallow copy of 2d array
and remeber 2d array is an array of array
normaly clone() of any array would work if the array was of primitive type like int
but here the array you are cloning contain arrays
that mean you will get new references to the same 2nd level array object
So
spielfeld[0] == spielfeld.clone()[0]
is true
since both spielfeld[0] and spielfeld.clone()[0] point to same object
now to resolve that we needed to do shallow copy of the inner arrays each one alone which resulted in deep copy
I'm trying to average 6 grades for two different people for school, I have all the grades for each student in different classes I was wondering
How can I import the numbers that I enter for each students object that I create?
//first class
public class GradesA {
int art;
int math;
int science;
int AddGrades(int a, int b, int c){
art = a;
math = b;
science = c;
return a+b+c;
}}
//second class
public class GradesB {
int english;
int carpentry;
int geography;
int AddGradesB(int a,int b,int c){
english = a;
carpentry = b;
geography = c;
return a+b+c;
}}
//final class
public class Classes {
public static void main(String[]args){
GradesA objGrades = new GradesA();
System.out.println(objGrades.AddGrades(100,85,95));
GradesB objGradesB = new GradesB();
System.out.println (objGradesB.AddGradesB(95,85,75));
}}
Hope I understood what you are looking for
Since
int addGrades(int a, int b, int c){
return and integer
why do not you just divide return number from this function by 3 and get your average that you are looking for.
If you want to have access to data fields art, math, and science values
you need getters and setters like follwing example for art data filed
setter function is
public void setArt(int art){
this.art = art;
}
getter function is
public int getArt(){
return this.art;
}
Read More About Setter and Getter
It's silly problem. I have my own comparator interface, class Student - it's objects will be sorted, class BubbleSort with bubblesorting algorithm and main. I think every class except from main is written quite well, but I have problem with implementation of them in main to make my sorting to start :/ I've just created ArrayList of random Students I want to be sorted, but I have problem with BubbleSort class and have no idea, how to start.
In future (I hope it will be today :)) I will do exactly the same with another classes containing sorting algorithms like BubbleSort here. I think their implementation in main will be identical.
import java.util.Random;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
int elements = 100000;
ArrayList<Student> list = new ArrayList<Student>();
Random rand = new Random();
for (int i=0; i<elements; i++) {
list.add(new Student(rand.nextInt(4)+2, rand.nextInt(900000)));
}
System.out.println(list);
}
}
.
import java.util.ArrayList;
public class BubbleSort {
private final Comparator comparator;
public BubbleSort(Comparator comparator) {
this.comparator = comparator;
}
public ArrayList<Student> sort(ArrayList<Student> list) {
int size = list.size();
for (int pass = 1; pass < size; ++pass) {
for (int left = 0; left < (size - pass); ++left) {
int right = left + 1;
if (comparator.compare(list.get(left), list.get(right)) > 0)
swap(list, left, right);
}
}
return list;
}
public int compare(Object left, Object right) throws ClassCastException
{ return comparator.compare(left, right); }
private void swap(ArrayList list, int left, int right) {
Object temp = list.get(left);
list.set(left, list.get(right));
list.set(right, temp);
}
}
.
public class Student implements Comparator<Student> {
int rate;
int indeks;
public Student(int ocena, int index) {
this.rate = ocena;
indeks = index;
}
public String toString() {
return "Numer indeksu: " + indeks + " ocena: " + rate + "\n";
}
public int getIndeks() {
return indeks;
}
public int getRate() {
return rate;
}
public int compare(Student left, Student right) {
if (left.getIndeks()<right.getIndeks()) {
return -1;
}
if (left.getIndeks() == right.getIndeks()) {
return 0;
}
else {
return 1;
}
}
}
.
public interface Comparator<T> {
public int compare(T left, T right) throws ClassCastException;
}
Your code looks little bit strange. You didnt mention if you have to use bubble sort so i write both my ideas
1.Without explicitly using bubble sort
You can use Collections.sort() combined with overridencompareTo() method
So your code will look like this
class Student implements Comparable<Student>{
//variables constructor methods go here
private index;
#Override
public int compareTo(Students s) {
int index = s.index;
if (this.index > index) {
return 1;
} else if (this.index == index) {
return 0;
} else {
return -1;
}
}
}
And in your main class Collections.sort(myStudents)
2.Explicitly using bubble sort
Student class
class Student{
//class variables methods constructor goes here
}
Comparator class
class StudentComparator implements Comparator<Student>{
#Override
public int compare(Student a, Student b) {
//bubble sort code goes here
}}
Main class
class MyMainClass{
public static void main(String[] args) {
public int elements = 100000;
ArrayList<Student> list = new ArrayList<Student>();
Random rand = new Random();
for (int i=0; i<elements; i++) {
list.add(new Student(rand.nextInt(4)+2, rand.nextInt(900000)));
}
Collections.sort(list, new StudentComparator());
}
Two points to make here:
a) You are not calling sort at all. You need to instantiate your BubbleSort class and actually call the method. list = new BubbleSort(new Comparator(){...}).sort(list); <-- This syntax also calls for the sort method to be static so that you don't need to make a new object for every sort. The example below sorts by index.
list = new BubbleSort(new Comparator<Student>() {
#Override
public compare(Student a, Student b) {
return a.getIndeks() - b.getIndeks();
}
}).sort(list);
Btw, this also assumes that BubbleSort is made generic, since it's easier (and kinda makes sense anyway)
b) I hope this is some kind of project where you have to show your ability to make a sorting algorithm, otherwise you should use library methods for these things
Also, while the code is not bad, you might want to show it to someone with professional Java experience (it does not conform to a lot of standards and many things can be improved and made consistent with each other), or post it to https://codereview.stackexchange.com/
I dont see you calling the bubblesort class anywhere. A list will not automatically sort its elements. Please go through this link. You ll find it handy.
http://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/
I am trying to return two numbers from this method. I thought this was correct. Where am I going wrong?
public int[] getDimension() {
int shapeWidth = 0;
int shapeHeight = 0;
// .....
int[] result = new int[] {shapeWidth, shapeHeight};
return result;
}
And then at a calling site, is this correct?
public int getWidth() {
return getDimension()[0];
}
I am asking because I believe there's a bug but I don't see it.
That's fine. Short but complete program to demonstrate it working:
public class Test {
public static void main(String args[]) {
int width = getDimension()[0];
System.out.println(width);
}
public static int[] getDimension() {
int shapeWidth = 5;
int shapeHeight = 10;
int[] result = new int[] {shapeWidth, shapeHeight};
return result;
}
}
You can make the result declaration line slightly simpler, by the way:
int[] result = {shapeWidth, shapeHeight};
Rather than using an array, I would recommend using a class
class Dimensions {
private int width;
private int height;
public Dimensions(int width, int height) {
this.width = width;
this.height = height;
}
// add either setters and getters
// or better yet, functionality methods instead
}
This will give you compile time referential integrity, which is much better than inferring based on "we know index 0 is width and index 1 is height".
If you still want to use an array, Jon's answer is spot on.
Your code looks fine, but try not to use an array if you only need a pair.
Since Java doesn't have tuples/pairs you have to implement them, but it's pretty easy. Refer to this question for a possible implementation.
public class Test {
public static void main(String args[]) {
int width = getDimension().getLeft();
System.out.println(width);
}
public static Pair<Integer, Integer> getDimension() {
int shapeWidth = 5;
int shapeHeight = 10;
return new Pair<Integer, Integer>(shapeWidth, shapeHeight);
}
}
This is better than a Dimension class, because you can use it everywhere in your code.