package the_JC;
public class Cls_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack1 obj1 = new Stack1(20);
for(int i = 1; i<=obj1.len; i++) {
obj1.push(i*3+i);
}
for(int i=0; i < obj1.len; i++) {
System.out.println(obj1.pop());
}
}
}
class Stack1{
int len=0;
Stack1(int num){
len = num;
System.out.println(len);
}
int[] stck = new int[len]; // this array is not accepting len as value from constructor above ,taking len =0
int pos = -1;
void push(int value) {
System.out.println(stck.length);
if(pos==len-1) {
System.out.println("Overflowed");
} else {
stck[++pos] = value;
System.out.println("Pushed value :\t"+value);
}
}
int pop(){
if(pos<0) {
System.out.println("Underflow");
return 0;
} else {
return stck[pos--];
}
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at the_JC/the_JC.Stack1.push(Cls_01.java:33)
at the_JC/the_JC.Cls_01.main(Cls_01.java:10)**
class Stack1{
int len=0;
int[] stck;
int pos;
Stack1(int num){
len = num;
stck = new int[len];
pos = -1;
System.out.println(len);
}
void push(int value) {
System.out.println(stck.length);
if(pos==len-1) {
System.out.println("Overflowed");
} else {
stck[++pos] = value;
System.out.println("Pushed value :\t"+value);
}
}
int pop(){
if(pos<0) {
System.out.println("Underflow");
return 0;
} else {
return stck[pos--];
}
}
}
How to calculate the distance between the generated cubes. The assigned script on the dice only specifies a different speed. How is the distance between the individual instantiate cubes calculated?
Sorry for the bad English, I'm using google trnslator. I'm attaching the code, and I'm a beginner in the unit
public class vehicless : MonoBehaviour
{
[SerializeField] private GameObject[] vehicle;
[SerializeField] private Transform spawnPos;
[SerializeField] private float minTime;
[SerializeField] private float maxTime;
int randomInt;
// Use this for initialization
void Start ()
{
StartCoroutine(SpawnVehicle());
}
// Update is called once per frame
void Update ()
{
}
private IEnumerator SpawnVehicle()
{
int i=1;
while(true)
{
randomInt = Random.Range(0,vehicle.Length);
yield return new WaitForSeconds(Random.Range(minTime,maxTime));
GameObject myPrefabInstance = Instantiate(vehicle[randomInt],spawnPos.position,Quaternion.identity);
var red = myPrefabInstance.gameObject.name; //NAME OBJECT
var namecube = red + i ;
Debug.Log("Name object:"+namecube ) ;
i++;
}
}
}
// float dist = Vector3.Distance(----------);
Thanks for help
If you need to quickly find the distance between 2 objects i suggest you to stock the distance in a dictionary with Tuple Key = (GameObject, GameObject) and Value = float:
Dictionary<(GameObject, GameObject), float>()
public Dictionary<(GameObject, GameObject), float>() calculate(GameObject[] objs)
{
var distanceArray = new Dictionary<(GameObject, GameObject), float>();
for (int i = 0; i < objs.Length; i++)
{
for (int j = i; j < objs.Length; j++)
{
if (i == j)
{
//distance between same obj is 0f
continue;
}
else
{
distanceArray.Add((objs[i], objs[j]), Vector3.Distance(objs[i].transform.position, objs[j].transform.position));
}
}
}
return distanceArray;
}
After you could quickly find the distance between 2 object like this:
if (distanceArray.ContainsKey((obj1, obj2)))
{
distance = distanceArray[(obj1, obj2)];
}
else if (distanceArray.ContainsKey((obj2, obj1)))
{
distance = distanceArray[(obj2, obj1)];
}
else if (obj1 == obj2)
{
distance = 0f;
}
else
{
//Error
}
Your question is not very easy to understand, i just add the way to calculate the distance after each new spawned vehicle:
GameObject myPrefabInstance = Instantiate(vehicle[randomInt],spawnPos.position,Quaternion.identity);
for (int i = 0; i < vehicle.Length; i++)
{
var distance = Vector3.distance(myPrefabInstance.transform.position, vehicle[i].transform.position);
Debug.Log($"Distance: {distance}");
}
I imagine that the cubes have different speeds, objects can be a lot, for example 10.15 cubes and a cube that will have a higher speed to slow down in front of a cube that has a slower speed.
The purpose of this code is is to define the root of the sum of the squares.
I cant figure out how to put i into j. Please help.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int input, som, i=0;
int j = 0;
double answer;
Boolean gaDoor= true;
int [] array = new int [24];
while (gaDoor)
{
Console.Write("Specify a positive integer");
input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
gaDoor = false;
}
else
{
if (input >= 0)
{
array[i] = input;
i++;
}
else
{
Console.WriteLine("Specify a positive integer ");
}
}
}
while (j<i)
{
sum = array [j] ^ 2;
answer = Math.Sqrt(sum);
Console.Write(answer);
}
Console.ReadKey();
}
}
}
using System;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
int[] invoer = new int[24];
double[] resultaat = new double[24];
double totaal = 0;
double wortel = 0;
int commando = 0;
int teller = -1;
try {
// Keep going until a negative integer is entered (or a 0)
while ((commando = Convert.ToInt32 (Console.ReadLine ())) > 0) {
teller++;
invoer [teller] = commando;
}
} catch (FormatException) {
// Not a number at all.
}
teller = -1;
foreach (int i in invoer) {
teller++;
resultaat [teller] = Math.Pow (invoer [teller], 2);
totaal += resultaat [teller];
if (invoer [teller] > 0) {
Console.WriteLine ("Invoer: {0}, Resultaat: {1}", invoer [teller], resultaat [teller]);
}
}
wortel = Math.Sqrt (totaal);
Console.WriteLine ("Totaal: {0}, Wortel: {1}", totaal, wortel);
}
}
}
I'm working on a boids flocking project.
My goal is to have several draggable objects which have to be avoided by the boids.
There are several different flocks with a different starting position.
I managed to get the boids to avoid one draggable object. But I can't seem to make them avoid all. (using a for loop)
I really can't figure out why this won't do the trick..
I hope you could give me some suggestions.
the code:
int initBoidNum = 100; //amount of boids to start the program with
BoidList flock1, flock2, flock3;
Draggable draggable;
NullDraggableObject nullDraggableObject;
ArrayList draggables;
int id;
float[] xposs= new float[10];
float[] yposs= new float[10];
String turn;
void setup() {
size(1000, 700);
//create and fill the list of boids
flock1 = new BoidList(150, 0, 10, 100);
flock2 = new BoidList(150, 255, 10, 200);
flock3 = new BoidList(150, 150, 10, 300);
turn = "turn";
nullDraggableObject = new NullDraggableObject();
draggables = new ArrayList();
for (int i = 0; i < 10; i++) {
draggables.add(new DraggableObject(random(width), random(height/2)));
}
}
void draw() {
background(100, 60);
flock1.run();
flock2.run();
flock3.run();
stroke(255);
noFill();
draggable = nullDraggableObject;
for (id = 0; id < draggables.size (); id++) {
Draggable d = (Draggable)draggables.get(id);
d.draw();
if (d.isBeingMouseHovered()) {
draggable = d;
}
}
}
void mousePressed() {
draggable.mousePressed();
}
void mouseDragged() {
draggable.mouseDragged();
}
void mouseReleased() {
draggable.mouseReleased();
}
interface Draggable {
boolean isBeingMouseHovered();
boolean inside(float ix, float iy);
void draw();
void mousePressed();
void mouseDragged();
void mouseReleased();
}
class NullDraggableObject implements Draggable {
boolean isBeingMouseHovered() {
return false;
}
boolean inside(float ix, float iy) {
return false;
}
void draw() {
}
void mousePressed() {
}
void mouseDragged() {
}
void mouseReleased() {
}
}
public class DraggableObject implements Draggable {
float XX, YY;
float radius;
boolean drag;
float dragX, dragY;
DraggableObject(float _x, float _y) {
XX = _x;
YY = _y;
radius = 50;
drag = false;
dragX = 0;
dragY = 0;
}
boolean isBeingMouseHovered() {
return inside(mouseX, mouseY);
}
boolean inside(float ix, float iy) {
return (dist(XX, YY, ix, iy) < radius);
}
void draw() {
ellipseMode(CENTER);
ellipse(XX, YY, 2*radius, 2*radius);
String space = "__";
println(id);
println(XX);
println(YY);
xposs[id] = XX;
yposs[id] = YY;
}
void mousePressed() {
drag = inside(mouseX, mouseY);
if (drag) {
dragX = mouseX - XX;
dragY = mouseY - YY;
}
}
void mouseDragged() {
if (drag) {
XX = mouseX - dragX;
YY = mouseY - dragY;
}
}
void mouseReleased() {
drag = false;
}
}
class Boid {
//fields
PVector pos, vel, acc, ali, coh, sep; //pos, velocity, and acceleration in a vector datatype
float neighborhoodRadius; //radius in which it looks for fellow boids
float maxSpeed = 1; //maximum magnitude for the velocity vector
float maxSteerForce = .05; //maximum magnitude of the steering vector
float sMod, aMod, cMod; //modifiers for the three forces on the boid
float h; //hue
Boid(PVector inPos) {
pos = new PVector();
pos.set(inPos);
vel = new PVector(random(-1, 1), random(-1, 1));
acc = new PVector(0, 0);
neighborhoodRadius = 20;
sMod = 1;
aMod = 1;
cMod = 4;
}
Boid(PVector inPos, PVector inVel, float r) {
pos = new PVector();
pos.set(inPos);
vel = new PVector();
vel.set(inVel);
acc = new PVector(0, 0);
neighborhoodRadius = r;
}
void run(ArrayList bl) {
for (int i =0; i < 10; i++) {
acc.add(attract(new PVector(width/2, height/2), true));
acc.add(avoid(new PVector(xposs[i], yposs[i]), true));
if (i == 10) i = 0;
}
if (pos.x>width-10)acc.add(bounce(new PVector(width, pos.y), true));
if (pos.x<10) acc.add(bounce(new PVector(0, pos.y), true));
if (pos.y>height-10) acc.add(bounce(new PVector(pos.x, height), true));
if (pos.y<10) acc.add(bounce(new PVector(pos.x, 0), true));
ali = alignment(bl);
coh = cohesion(bl);
sep = seperation(bl);
for (int i =0; i < 10; i++) {
if (PVector.dist(new PVector(xposs[i], yposs[i]), pos)>180) {
acc.add(PVector.mult(ali, aMod));
acc.add(PVector.mult(coh, cMod));
acc.add(PVector.mult(sep, sMod));
}
if (PVector.dist(new PVector(xposs[i], yposs[i]), pos)<80) maxSpeed = 1000;
if (i == 10) i = 0;
}
if (PVector.dist(new PVector(width, height), pos)<60) maxSpeed = 1000;
if (PVector.dist(new PVector(0, 0), pos)<50) {
maxSpeed = 1000;
} else {
maxSpeed = 1;
}
move();
checkBounds();
render();
}
void move() {
vel.add(acc); //add acceleration to velocity
vel.limit(maxSpeed); //make sure the velocity vector magnitude does not exceed maxSpeed
pos.add(vel); //add velocity to position
acc.mult(0); //reset acceleration
}
void checkBounds() {
}
void render() {
pushMatrix();
translate(pos.x, pos.y);
rotate(atan2(vel.y, vel.x)); //rotate drawing matrix to direction of velocity
stroke(0);
noFill();
ellipse(0, 0, neighborhoodRadius/2, neighborhoodRadius/2);
noStroke();
fill(h);
//draw triangle
beginShape(TRIANGLES);
rect(0, 0, 6, 2);
endShape();
popMatrix();
}
//steering. If arrival==true, the boid slows to meet the target. Credit to Craig Reynolds
PVector steer(PVector target, boolean arrival) {
PVector steer = new PVector(); //creates vector for steering
if (!arrival) {
steer.set(PVector.sub(target, pos)); //steering vector points towards target (switch target and pos for avoiding)
steer.limit(maxSteerForce); //limits the steering force to maxSteerForce
} else {
PVector targetOffset = PVector.sub(target, pos);
float distance=targetOffset.mag();
float rampedSpeed = maxSpeed*(distance/100);
float clippedSpeed = min(rampedSpeed, maxSpeed);
PVector desiredVelocity = PVector.mult(targetOffset, (clippedSpeed/distance));
steer.set(PVector.sub(desiredVelocity, vel));
}
return steer;
}
//avoid. If weight == true avoidance vector is larger the closer the boid is to the target
PVector avoid(PVector target, boolean weight) {
PVector steer = new PVector(); //creates vector for steering
steer.set(PVector.sub(pos, target)); //steering vector points away from target
if (weight) steer.mult(1/sq(PVector.dist(pos, target)));
//steer.limit(maxSteerForce); //limits the steering force to maxSteerForce
return steer;
}
PVector attract(PVector target, boolean weight) {
PVector steer = new PVector(); //creates vector for steering
steer.set(PVector.sub(target, pos)); //steering vector points away from target
if (weight) steer.mult(1/sq(PVector.dist(target, pos)));
//steer.limit(maxSteerForce); //limits the steering force to maxSteerForce
return steer;
}
PVector bounce(PVector target, boolean weight) {
PVector steer = new PVector(); //creates vector for steering
steer.set(PVector.sub(pos, target)); //steering vector points away from target
if (weight) steer.mult(1/sq(PVector.dist(pos, target)));
//steer.limit(maxSteerForce); //limits the steering force to maxSteerForce
return steer;
}
PVector seperation(ArrayList boids) {
PVector posSum = new PVector(0, 0);
PVector repulse;
for (int i=0; i<boids.size (); i++) {
Boid b = (Boid)boids.get(i);
float d = PVector.dist(pos, b.pos);
if (d>0&&d<=neighborhoodRadius) {
repulse = PVector.sub(pos, b.pos);
repulse.normalize();
repulse.div(d);
posSum.add(repulse);
}
}
return posSum;
}
PVector alignment(ArrayList boids) {
PVector velSum = new PVector(0, 0);
int count = 0;
for (int i=0; i<boids.size (); i++) {
Boid b = (Boid)boids.get(i);
float d = PVector.dist(pos, b.pos);
if (d>0&&d<=neighborhoodRadius) {
velSum.add(b.vel);
count++;
}
}
if (count>0) {
velSum.div((float)count);
velSum.limit(maxSteerForce);
}
return velSum;
}
PVector cohesion(ArrayList boids) {
PVector posSum = new PVector(0, 0);
PVector steer = new PVector(0, 0);
int count = 0;
for (int i=0; i<boids.size (); i++) {
Boid b = (Boid)boids.get(i);
float d = dist(pos.x, pos.y, b.pos.x, b.pos.y);
if (d>0&&d<=neighborhoodRadius) {
posSum.add(b.pos);
count++;
}
}
if (count>0) posSum.div((float)count);
steer = PVector.sub(posSum, pos);
steer.limit(maxSteerForce);
return steer;
}
}
class BoidList {
ArrayList boids; //will hold the boids in this BoidList
float h; //for color
BoidList(int n, float ih, int xstart, int ystart) {
boids = new ArrayList();
h = ih;
for (int i=0; i<n; i++) {
boids.add(new Boid(new PVector(xstart, ystart)));
}
}
void run() {
for (int i=0; i<boids.size (); i++) {
Boid tempBoid = (Boid)boids.get(i); //create a temporary boid to process and make it the current boid in the list
tempBoid.h = h;
tempBoid.run(boids); //tell the temporary boid to execute its run method
}
}
}
I am planning to make an airline system. I have initialized the array using initSeats but it still throws back the NPE error. It happens when i call the seatChecker() from bookMenu.
public void initSeats(){
for(int b = 0; b < seatList.length; b++)
{
initC.setName("null");
initC.setEmail("null");
initC.setCreditNo(0);
initC.setAddress("null");
initC.setPassportNo("null");
seatList[b] = new Seat('A', 0, "null", 0.0, "Available", initC);
}
for(int d = 0; d <= 24; d++)
{
seatList[d].setSeatLetter('A');
seatList[d].setSeatNo(d);
}
for(int n = 25; n <= 48; n++)
{
seatList[n].setSeatLetter('B');
seatList[n].setSeatNo(n);
}
for(int m = 49; m <= 72; m++)
{
seatList[m].setSeatLetter('C');
seatList[m].setSeatNo(m);
}
for(int t = 73; t <= 96; t++)
{
seatList[t].setSeatLetter('D');
seatList[t].setSeatNo(t);
}
for(int q = 97; q <= 120; q++)
{
seatList[q].setSeatLetter('E');
seatList[q].setSeatNo(q);
}
for(int v = 121; v < 144; v++)
{
seatList[v].setSeatLetter('F');
seatList[v].setSeatNo(v);
}
for(int x = 0; x <= 48; x++)
{
seatList[x].setSection("Front");
seatList[x].setPrice(500);
}
for(int j = 49; j <= 96; j++)
{
seatList[j].setSection("Middle");
seatList[j].setPrice(250);
}
for(int u = 97; u < 144; u++)
{
seatList[u].setSection("Back");
seatList[u].setPrice(100);
}
}
public void seatChecker(int index)
{
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available")){
System.out.println("Seat is Available.");
}else{
System.out.println("Seat is not Available. Please Pick Another Seat.");
bookMenu();
}
}
public void bookMenu()
{
int choice1 = 0;
int index;
System.out.println("Where do you want to be seated?");
System.out.println("[1] Front");
System.out.println("[2] Middle");
System.out.println("[3] Back");
choice1 = sc.nextInt();
sc.nextLine();
if(choice1 == 1){
System.out.print("Choose a seat number (0 - 48): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 2){
System.out.println("Choose a seat number (49 - 96): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 3){
System.out.println("Choose a seat number (97 - 144): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else
{
System.out.println("Invalid Choice. Going back to Menu.");
MainMenu();
}
}
Null Pointer Exception Code
Exception in thread "main" java.lang.NullPointerException
at pkg.Airlines.AirlineUI.seatChecker(AirlineUI.java:132)
Seat Class
public class Seat{
private char seatLetter;
private int seatNo;
private String section;
private double price;
private String status;
private Customer customerDetails;
public Seat(char seatLetter, int seatNo, String section, double price, String status, Customer details)
{
this.seatLetter = seatLetter;
this.seatNo = seatNo;
this.section = section;
this.price = price;
this.status = status;
this.customerDetails = details;
}
public Customer getCustomerDetails() {
return customerDetails;
}
public void setCustomerDetails(Customer customerDetails) {
this.customerDetails = customerDetails;
}
public char getSeatLetter() {
return seatLetter;
}
public void setSeatLetter(char seatLetter) {
this.seatLetter = seatLetter;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSeatNo() {
return seatNo;
}
public void setSeatNo(int seatNo) {
this.seatNo = seatNo;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}
Probably the problems are this two line :
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available"))
First thing could be seatList[index] is not initialized . Once you declare an array of references as :
Seat[] array = new Seat[10];
The array contains 10 null references for Seat object . You need to instantiate them before using them :
Seat[0] = new Seat();
Second potential problem will be, this check :
if(status.equalsIgnoreCase("Available"))
Replace it to :
if("Available".equalsIgnoreCase(status))
to avoid any NullPointerException in case status is null.
P.S. Please show us the Seat class to understand your problem better.
Well is quite simple resolve a Null Pointer Exception.
Probably in one of the index of seatList there isn't a value.