Performing a method on an int [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to generate a random number for an int through a method. I know that this cannot be done because an int is a primitive type and I get an int cannot be deferenced error. Is there is away around it to where I can still use the method to get the value for the int?
public int move()
{
Random random = new Random();
int generatedNum = random.nextInt(7 - 1) + 1;
return generatedNum;
}
public static void main(String[] args)
{
int player1 = 0;
int player2 = 0;
player1 = player1.move();
player2 = player2.move();
}

What are you trying to do?
This would work, but no idea if it is what you want...
// made this static so you don't need a class reference
public static int move()
{
Random random = new Random();
int generatedNum = random.nextInt(7 - 1) + 1;
return generatedNum;
}
public static void main(String[] args)
{
int player1 = 0;
int player2 = 0;
// Now we just call the static method move to set the ints.
player1 = move();
player2 = move();
}

int is a primitive type and Integer is final, so no, you will never be able to write 5.move().
You could write a class that just wraps an integer, but will not be able to do arithmetics with it.
Maybe Iterator<Integer> is an interface worth implementing.

You can create your own class similar to the Integer class (which is unfortunately final or you'd be able to subclass that). Then add whatever methods you'd like to that class. A little inconvenient to use when you want to retrieve the value, but not too messy.

Related

java extended class inheritance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Sum s = new Sum();
Sum.SetToZero z = new Sum.SetToZero();
Scanner input = new Scanner(System.in);
String read = input.nextLine();
while (!read.equals("end")) {
if (read.equals("add")) {
s.add()
}
else if (read.equals("get")) {
System.out.println(s.returnTotal());
}
else if (read.equals("zero")) {
z.zero();
}
read = input.nextLine();
}
class:
public class Sum {
int total = 0;
public void add() {
total += 1;
}
public int returnTotal() {
return total;
}
public static class SetToZero extends Sum {
public void zero() {
total = 0;
}
}
}
input:
add
add
zero
add
get
add
get
end
output:
3
4
output wanted:
1
2
Shouldn't the subclass inherit the total and set it to zero? What am I doing wrong? I know I could just move the zero into the main class but I want it to be in a separate class. thx for your help.
By making your total variable static, you can get the desired output.
class Sum {
static int total = 0;
public void add() {
total += 1;
}
public int returnTotal() {
return total;
}
public static class SetToZero extends Sum {
public void zero() {
total = 0;
}
}
}
Apart from things pointed out in names like not using lowecase letters to start your class name; I think the reason why it's not working is because you're using two different variable instances for Sum and Sum.SetToZero. You don't need to create a new variables since SetToZero has all the attributes of Sum. I think you should change this:
Sum s = new Sum();
Sum.SetToZero z = new Sum.SetToZero();
Sum.SetToZero s = new Sum.SetToZero(); // use s for all operations
Here is how your modified main method would look:
public static void main(String[] args) {
Sum.SetToZero s = new Sum.SetToZero();
Scanner input = new Scanner(System.in);
String read = input.nextLine();
while (!read.equals("end")) {
if (read.equals("add")) {
s.add();
}
else if (read.equals("get")) {
System.out.println(s.get());
}
else if (read.equals("zero")) {
s.zero();
}
read = input.nextLine();
}
}
When I ran this, I saw expected output:
src : $ java Sum
add
add
zero
add
get
1
add
get
2
end

java generics: defining objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to learn Java and having trouble understanding generics. I'm attempting to define an object of Integer data type, then use the object to to call a generic method.
Guided by the API and some web resources, I've been trying all sorts of things but I don't know if i'm on the right track in terms of simply defining the object.
SearchSortAlgorithms.java:
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
public void quickSort(T[] list, int length)
{
recQuickSort(list, 0, length - 1);
}
}
TestQuickSort.java
public class TestQuickSort
{
static void main(String [] args)
{
// define an Integer array of 50000 elements
Integer[] anArray = new Integer[5000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*50000)
for (int i = 0; i < anArray.length; i++) {
anArray[i] = (int)(Math.random() * i);
}
// define an object of SearchSortAlgorithm with Integer data type
// use this object to call the quickSort method with parameters: your array name and size-50000
Integer aSortedArray = new Integer(5000);
public void quickSort(anArray, 5000) {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
return aSortedArray.quickSort(anArray, 5000);
}
// print out the first 50 array elements with a for loop
// they have to be sorted now
for (int k = 0; k <= 50; k++) {
System.out.print(aSortedArray[k] + " ");
}
}
}
Errors on these lines:
public int TestQuickSort () {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
aSortedArray = quickSort(anArray, 5000);
}
-Illegal start of expression: I wonder if my attempt at creating the constructor is right
-; expected
Ignoring any other potential errors in your code (or due to its presentation to us here), you are attempting to declare another method in main.
public int SearchSortAlgorithm () {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
aSortedArray = quickSort(anArray, 5000);
}
This needs to be moved out of main. And also fixed to actually return an int. And main's signature should be public static void main(String[] args).
Although, it should really be returning an int[] instead...
public static int[] searchSortAlgorithm (final int[] anArray) {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
return quickSort(anArray, 5000);
}
...and called in your main method like this...
int[] aSortedArray = searchSortAlgorithm(anArray);
for (int k = 0; k <= 50; k++) { // would be better to use aSortedArray.length
System.out.print(aSortedArray[k] + " ");
}

Java Arrays: I want to create two arrays that hold 3 int values each [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Objective:
Retrieve array defined in class Player in another class to do additional operations on the array content;
Code so far:
public class Players {
//attributes
private int [] Player1 = new int [3];
private int [] Player2 = new int [3];
private int round=Math.random();
//Constructor
public Players(int [] p1, int [] p2 ){
[] player1 = [] p1
[] player2 = [] p2
}
Problem specification : Does not compile;
You have multiple syntax as well as type mismatch issues
1) Java is case sensitive
public Players(int [] p1, int [] p2 ){
Player1 = p1;
Player1 = p2;
}
So
Player1 !=player1
2) And
[] player1 = [] p1
Is not a valid java syntax
3) Finally Math.random() returns double, Change it as
double random = Math.random();
You have to separate the parameters trough a comma
public Game(int[] p1, int[] p2) {
And this isn't even close to working (note the lack of semicolons as well):
[] player1 = [] p1
[] player2 = [] p2
You want to set the instance fields equal to the given parameters, but there's no need to redefine that they're arrays.
Instead use this:
this.player1 = p1;
this.player2 = p2;
Keep in mind naming conventions: fields start with lowercase (so player1 instead of Player1). Java is case sensitive so Player1 and player1 are not the same. Exactly one of the reasons why naming conventions exist.
Lastly: Math.random returns a double. If you cast it to an int you will lose its purpose (it returns a value between 0 and 1, if you cast it to int you will lose everything between those two boundaries). Instead make it as such:
private double round = Math.random();
As per my comment, you might want to consider structuring your class like this:
public class Player {
//attributes
private int[] roundValues;
private double round=Math.random(); //not sure what you are using this for
//Constructor
public Player(int[] roundValues){
this.roundValues = roundValues;
}
// use this to get the roundValues array
public int[] getRoundValues() {
return roundValues;
}
// use this to change the roundValues array
public void setRoundValues(int[] roundValues) {
this.roundValues = roundValues;
}
public static void main(String[] args) {
int[] array1 = {1,2,3}; //just some dummy values
Player player1 = new Player(array1);
// do this to get the player's round values
int[] roundVals = player1.getRoundValues();
}
}
There is several mistakes with you program.
Check the one below:
public class Players {
//attributes
private int [] player1 = new int [3]; // use names with lowercase at beginning (convention)
private int [] player2 = new int [3];
private double round = Math.random();
//Constructor
public Players(int[] p1, int[] p2) { // you missed a comma and a parenthesis
player1 = p1; // no need to say again that they are arrays. add ';' at the end
player2 = p2;
}
// you could need to add these to access your private arrays from an other class
public int[] getPlayer1(){
return player1;
}
public int[] getPlayer2(){
return player2;
}
}
Hope it helps
Watch out for case sensitivity by player1 and Player1.
add some semicolons
remove some braces for setting array variables
the Math.random() method returns a double, not an integer
variables should begin with lower case letters
Like this:
public class Players {
//attributes
private int[] player1 = new int[3];
private int[] player2 = new int[3];
private double round = Math.random();
//Constructor
public Players(int[] p1, int[] p2) {
player1 = p1;
player2 = p2;
}
}

Java Chess scorekeeper

I am new to Java and I'm grateful if anyone could help with the below. I am trying to make a scorekeeper for my chessboard. At the moment, the score will go back to zero everytime. How would I be able to save the previous score and add it every move? Thanks!
public static int scoreKeeper(Chessmen[][] chessboard, int X, int Y, int X1, int Y1, int currentNumber, int totalNumber){
AbstractPiece knight = new Knight();
AbstractPiece bishop = new Bishop();
AbstractPiece pawn = new Pawn();
AbstractPiece king = new King();
AbstractPiece queen = new Queen();
AbstractPiece rook = new Rook();
if ((chessboard[Y][X] == Chessmen.WHITE_KNIGHT) ||
(chessboard[Y][X] == Chessmen.BLACK_KNIGHT)){
currentNumber = currentNumber+totalNumber+knight.relativeValue();
return currentNumber;
}else return totalNumber;
}
The main problem you have is that you are passing the value of currentNumber as a parameter
that means it will not change outside this method
this Example will illustrate my point
public class Test{
public static void main (String[] args){
int a = 0 ;
changeValue(a);
System.out.print(a);
}
public static void changeValue(int a){
a=20;
}
}
the output will be always 0 .
you can solve it by writing the methods getValueOfCurrentNumber() and getValueOfTotalNumbe()
to get the values [currentNumber and totalNumbe] instead of taking them as parameters .
The easiest solution is to store your score as a class data member:
class Game {
static int score;
public static int updateScore(... some inputs...) {
if(some condition is true) {
score = score + whatever you want to add;
}
}
}
The class retains the value of "score" between method calls.
I suspect that you have a bad abstraction. I think you want a Chessboard to hide the 2D array of Chessmen. Let it keep the current score as a data member. Provide methods to select and move pieces appropriately.
I can see its constructor instantiating a Chessboard. It would set each of the pieces at their appropriate starting positions. Then each Player would take turns moving.
Not a trivial problem.

static Math.random change java

I don't have a problem anymore, However I want to understand the behaviour of some code. Initially I was generating some random numbers and somewhere in my code the Math.random was returning the same number for all iterations. I tried to create a minimal example with the following two Classes:
first Class:
public class randomTest {
public randomTest()
{ }
public double generateRandomNumber()
{
double r = Math.random();
return r;
}
public static void main(String args[])
{
randomTest t = new randomTest();
for (int i = 0; i < 10; i++)
System.out.println(t.generateRandomNumber());
}
}
The second class:
public class anotherClass {
private randomTest t = new randomTest();
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
anotherClass c = new anotherClass();
System.out.println(c.t.generateRandomNumber());
}
}
}
I was trying to generate a minimal code example to track the reason why I am always getting the same random value for the whole 10 iterations. In this minimal example the results are correct and random, However In my real situation The output of the second class is the same for the whole ten iterations.
At last i was able to solve the problem by changing the method I am calling into a static method. I still don't understand how did this solve my problem, and where the original problem was.
Old Nonworking code:
...
public ImagePlus createAnImage()
{
drawBackground(c.ip);
width = ip.getWidth();
height =ip.getHeight();
createCircles(requiredCircles); // this is not creating random numbers
ArrayList<Circle> list = circlesList;
drawBoundaries(list, ip, percentage);
background.setProcessor(ip);
return background;
}
...
New Code:
...
public static ImagePlus createAnImage()
{
createCircles c = new createCircles();
c.drawBackground(c.ip);
c.width = c.ip.getWidth();
c.height =c.ip.getHeight();
c.createCircles(c.requiredCircles); // this is creating random numbers
ArrayList<Circle> list = c.circlesList;
c.drawBoundaries(list, c.ip, c.percentage);
c.background.setProcessor(c.ip);
return c.background;
}
...
In both cases I was already creating an instance of createCircles class from another class as follows:
...
private ImagePlus createRandomImage(int radius, int numberOfCircles, double minPercentage, double maxPercentage, int minBackground, int maxBackground)
{
// create the image using class createCircles
createCircles c = new createCircles();
c.setParameters(radius, radius, minBackground, maxBackground, numberOfCircles, imageWidth, imageHeight, minPercentage, maxPercentage);
ImagePlus imp = c.createAnImage(); // calling the static method works
return imp;
}
Although my problem is solved, I still need to understand the reason behind this. I suppose a better understanding of static vs. non-static methods might explain it. Anyone has a clue?
Best Regards,
M. Tleis
Do not use Math.random (it produces doubles, not integers)
use the Random class to generate random integers between 0 and N.
To generate a series of random numbers as a unit, you need to use a single Random object - do not create a new Random object for each new random number.
import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
public static final void main(String... aArgs){
log("Generating 10 random integers in range 0..99.");
//note a single Random object is reused here
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
int randomInt = randomGenerator.nextInt(100);
log("Generated : " + randomInt);
}
log("Done.");
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}

Categories

Resources