How to find random element matching to condition in a table? - java

I've made a table with geometrical figures and a for loop for printing out the name of figures that have right angle, but I would like to print out one random name for this figure that matches the condition and if it's possible create another table that contains only figures that match the condition. I was trying to use some method from java.util.Random but I couldn't find out how. I'll be thankful for Your help:
import java.util.Random;
public class rectangularFigures {
private String name;
private boolean rightAngle;
public String getName() {
return name;
}
public rectangularFigures(String name, boolean rightAngle) {
this.name = name;
this.rightAngle = rightAngle;
}
public static void main(String[] args) {
rectangularFigures[] lOFigures = new rectangularFigures[4];
lOFigures[0] = new rectangularFigures("whell", false);
lOFigures[1] = new rectangularFigures("square", true);
lOFigures[2] = new rectangularFigures("rhombus", false);
lOFigures[3] = new rectangularFigures("rectangle", true);
for (int i = 0; i < lOFigures.length; i++) {
{
if (lOFigures[i].rightAngle) {
System.out.println(lOFigures[i].name);
}
}
}
}
}

The simplest way is to use java streams:
rectangularFigures[] onlyRightAngles = Arrays.stream(lOFigures).filter(x -> x.rightAngle).toArray(rectangularFigures[]::new);
rectangularFigures randomElement = onlyRightAngles[new Random().nextInt(onlyRightAngles.length)];
System.out.println(randomElement.name);
But if for some reasons you can't use streams, i suggest to use ArrayList and traditional foreach loop:
List<rectangularFigures> onlyRightAngles = new ArrayList<>();
for (rectangularFigures figure : lOFigures) {
if (figure.rightAngle) onlyRightAngles.add(figure);
}
rectangularFigures randomElement = onlyRightAngles.get(new Random().nextInt(onlyRightAngles.size()));
System.out.println(randomElement.name);

This is just a small example but it can be improved:
Random r = new Random();
for (int i = 0; i < lOFigures.length; i++) {
{
int f = r.nextInt(4);
if (lOFigures[f].rightAngle) {
System.out.println(lOFigures[f].name);
}
}
}

Related

The practice of deep clone failed

I tried to make a deep clone via overridong the clone method, but the result is not how a deep clone behaves(blanks and oldBlanks should print differently).
It is supposed to print:
192, []
1_2, [1]
It actually prints:
192, []
192, []
An MCVE is presented.
import java.util.ArrayList;
public class Program {
static class Blank implements Cloneable {
#Override
protected Blank clone() {
Blank b = new Blank(this);
return b;
}
public Blank(String str) {
origin = str;
uradix = str.length();
String strn = str.replaceAll("_","0");
existed = Integer.parseInt(strn);
for (int i = 0; i < uradix; i++) {
int radix = uradix - i;
if (str.charAt(i) == '_'){
not_existed.add(radix-1);
}
}
}
public Blank(Blank b){
this.origin = b.origin;
this.uradix = b.uradix;
this.existed = b.existed;
for (Integer i :
b.not_existed) {
int k = i;
this.not_existed.add(k);
}
}
String origin;
int uradix;
int existed;
ArrayList<Integer> not_existed = new ArrayList<>();//remain sequence: ->, i.e. left to right
}
static Blank[] copy(Blank[] ts){
for (Blank t :
ts) {
t = t.clone();
}
return ts;
}
public static void main(String[] args) {
Blank[] blanks = {new Blank("1_2"),new Blank("_2"),new Blank("_2_")};
Blank[] oldBlanks = copy(blanks);
StringBuilder sb = new StringBuilder(blanks[0].origin);
System.out.println("before the change");
System.out.println(blanks[0].origin+", "+blanks[0].not_existed);
System.out.println(oldBlanks[0].origin+", "+oldBlanks[0].not_existed);
int index = 1;
sb.replace(index,index+1,"9");
blanks[0] = new Blank(sb.toString());
System.out.println("after the change");
System.out.println(blanks[0].origin+", "+blanks[0].not_existed);
System.out.println(oldBlanks[0].origin+", "+oldBlanks[0].not_existed);
}
}
p.s. My tutor said that a static class used in such a pattern is weird, but that should not be the problem because the problem reproduces even if I modify the class Blank outside non-static.
It's not your clone method that causes the problem, bBut rather the way you implemented your copy.
You return the original Blank[] reference and then adapt it.
If you do this:
static Blank[] copy(Blank[] ts){
Blank[] ts_copy = new Blank[ts.length];
for (int i=0; i<ts.length; i++) {
ts_copy[i] = ts[i].clone();
}
return ts_copy;
}
Then I get an output like this:
before the change
1_2, [1]
1_2, [1]
after the change
192, []
1_2, [1]

Iterate through ArrayList

I'm currently trying to iterate through an ArrayList and see if it contains the following numbers I input into the winners array. However, the ticket object won't allow me to utilize the .contains() method which is where I'm getting the error. Any idea on how to work around this?
int[] winners = new int[6];
for(int i = 0; i < winners.length; i++)
{
winners[i] = in.nextInt();
}
in.close();
Scanner scan = new Scanner(file);
ArrayList<Ticket> info = new ArrayList<Ticket>();
for(int i = 0; i < lim; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
String[] t = num.split(" ");
int[] tichold = new int[t.length];
for(int j = 0; j < t.length; j++)
{
tichold[j] = Integer.parseInt(t[j]);
}
Ticket ticket = new Ticket(name, tichold);
info.add(ticket);
}
**for(Ticket t : info)
{
if(t.contains(winners))
{
System.out.println("Yes");
}
}**
scan.close();
}
**public static class Ticket
{
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}**
You can't use a method that doesn't exist for that class. Since you don't have contains defined for Ticket, I'm not surprised that it isn't working.
From inference, winners is an int[]. In that case, you'd define a new method contains inside of Ticket.
public boolean contains(int[] winningNumbers) {
// logic here
}
Depending on how the winning numbers for a given ticket are stored, and given how you define different conditions of winning, you'd handle your logic here.
If they're stored as an array and you want an exact match, then you can use Arrays.equals for that.
public boolean contains(int[] winningNumbers) {
return Arrays.equals(numbers, winningNumbers);
}
Try this Ticket class with and added contains method:
public class Ticket {
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}
public boolean contains(int[] winners) {
for (int i = 0; i < winners.length; i++) {
for (int j = 0; j < tarray.length; j++) {
if (winners[i] == tarray[j])
return true;
}
}
return false;
}
}

Using an array as an attribute to modify it Java

my friend has programmed a Breakout game in java. I know C++, which tranfers relatively well to java.
I had a problem when trying to insert a MultiBall brick.
Here are the relevent bits of my function:
private Balle[] balle;
public BriqueMultiBalle(Balle[] bal) {
super();
balle = bal;
SCORE = 100;
}
public void touched() {
visible = false;
balle[Balle.getNInstance()].makeVisible();
}
I get no error but I found out when debugging that balle corresponds to a null pointer. I tried using these different declarations, however, none of them worked:
1.
public BriqueMultiBalle(Balle[] bal) {
super();
for(int i = 0; i < 6; i++)
{
balle[i] = bal[i];
}
SCORE = 100;
}
2.
public BriqueMultiBalle(Balle[] bal) {
super();
balle = new Balle[](bal);
SCORE = 100;
}
However, these methods do not work.
Thanks,
Ghi102
You are getting a null pointer on balle because you never initialize the array, you leave it as
private Balle[] balle;
Try initializing you code
balle = new Balle[bal.length];
for(int i = 0; i < bal.length; i++){
balle[i] = bal[i];
}
Here's an example I wrote using an int array. Same concept, just apply it to your object.
public static void main(String[] args) throws Exception {
int[] arrayInts;
int[] originalInts = { 1, 2, 3, 4, 5 };
arrayInts = new int[originalInts.length];
for(int i = 0; i < originalInts.length; i++){
arrayInts[i] = originalInts[i];
}
originalInts[0] = 10;
for (int i : arrayInts) {
System.out.println(i);
}
}

Adding objects to an array

I have been looking at questions of how to add elements to an array How can I dynamically add items to a Java array?.
I do not understand how to add objects of a class type, not a datatype like String. How am I supposed to do this, when the object patient has various datatypes? What I can't get my head around, is how to put the attributes of a Patient object into an array.
Class Patient{
public Patient(String ptNo, String ptName, int procType) throws IOException
{
Patient.patientNo = ptNo;
Patient.patientName = ptName;
Patient.procedureType = procType;
}
}
Another class:
public static void main(String[] args) throws IOException
{
Patient [] patients;
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients.add(p);
}
}
I understand I am missing the obvious, and only come here, after exhausting other resources.
You need to specify the array size like below
Patient [] patients = new Patient[2];
Then now add the elements like below
patients[i] = new Patient(null, null, 0)
The complete code like below
for (int i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0);
}
You need to access an array using the indexes
patients[i] = p;
but before that you need to initialize it as well.
Patient [] patients = new Patient[10]; // random init
Since you want them to be dynamic, try to use an ArrayList and keep adding the objects to it.
List<Patient> patients = new ArrayList<>();
patients.add(p);
Arrays are accessed via index:
Please modify your code like this.
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[10];
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
}
You are using an array and not an ArrayList thus add them by specifying the index
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
EDIT
If you really want to assign the same object in the string you can even skip the object reference, like
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0); // No need for p now
}
}
First you need to initialize an array to be of a specific size.
Patient [] patients = new Patient[2];
Secondly, you need to use index when assigning a value.
patients[i] = p;
Finally;
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
}
First:
Some fixes:
class Patient
{
public String patientNo;
public String patientName;
public int procedureType;
public Patient(String ptNo, String ptName, int procType)
{
this.patientNo = ptNo;
this.patientName = ptName;
this.procedureType = procType;
}
}
Since you want your patients to be unique not the same as Patient.sth is class' property (common to all instances).
Now array and inserting:
Patient patients[] = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
but again do not fill array with the same objects. In addition not to be bound to fixed array size - use Vector (for example)
Update: about class members / aka static object members
These 2 code samples are completely different things:
class X
{
public String abc;
public void someMember()
{
this.abc = ;
}
}
and
class X
{
public static String abc;
public void someMember()
{
X.abc =
}
}
You must distinguish between what is unique to an abject and what is common to a class (ie available to all instances - common to them).
With static keyword you declare class members (they will be common foa all instances). You cannot use them with 'this' keyword which is reserved for instance members from the first example.
Here is what you must read class vs instance members

Why is there an NullPointerException?

I am trying to mommertary use a string and convert it to an int to compare the first first column and all the rows with the all of the numbers within the string typed in. When I type in a number, I get a NullPointerException. The thing is, I don't understand why the compiler is telling me this when I feel like I have declared all my objects properly. please help!
import java.util.ArrayList;
public class Decoder
{
private int[][] zipdecoder;
private ArrayList<Integer> zipcode;
private String finalCode;
private String bars;
private int place;
public Decoder()
{
int[][] zipdecoder = new int[][]{
{1,0,0,0,1,1},
{2,0,0,1,0,1},
{3,0,0,1,1,1},
{4,0,1,0,0,0},
{5,0,1,0,1,1},
{6,0,1,1,0,0},
{7,1,0,0,0,0},
{8,1,0,0,1,1},
{9,1,0,1,0,0},
{0,1,1,0,0,0}
};
zipcode = new ArrayList<Integer>();
}
public void insertToArray(String zip)
{
int count = 0;
for(int i = 1; i<zip.length()+1;i++)
{
String piece = zip.substring(count, i);
int number = Integer.parseInt(piece);
for(int j = 0;j<10;j++)
{
if(number == zipdecoder[j][0]){
for(int a = 1;a<5;a++)
{
zipcode.add(place,zipdecoder[j][a]);
place++;
}
}
count++;
}
}
}
You're not initializing the class member zipdecoder but a new local variable (with the same name) in the constructor.
Change this
int[][] zipdecoder = new int[][]{
to
zipdecoder = new int[][]{
and it should work.

Categories

Resources