Make String from String[] and int - java

String callsign;
String airlines[] = {"DLH","BER","TUI","EZY","ACA","AAL","FDX","SKW","ABY","SWR"};
public void assignCallsign()
{
Random r = new Random();
int airline = r.nextInt(10);
int number = r.nextInt(900) + 100;
callsign = airlines[airline] + number;
}
The String Array airlines[] contains 3 letters designating an airline.
The random integer airline is used to choose one of those airlines. The random integer number should designate the last 3 characters of an airplanes callsign.
I'm trying to get an output like "BER219", "AAL814" and so on, but upon executing the class, the String callsign is still null :/

Java passes variables by value. If you are testing the value of callsign variable outside this function then it will be null because you have set it to null outside of the assignCallsign method.
To remedy this, you can either:
return the callsign value from the function and set a variable with it.
public String assignCallSign() {
return airlines[airline] + number;
}
String callsign = assignCallSign()
make callsign a member variable of the class, and your code will function as you expect:
private String callsign;

It is difficult to see the issue without seeing the class that is using it.
Speculating this is part of some "Flight" object. This demonstrates the callsign being set and displayed correctly.
public static void main(String[] args) {
Flight flight = new Flight();
flight.assignCallsign();
System.out.println(flight);
}
private static class Flight {
private static final String AIRLINES[] = { "DLH", "BER", "TUI", "EZY", "ACA", "AAL", "FDX", "SKW", "ABY", "SWR" };
private String callsign;
public void assignCallsign() {
Random r = new Random();
int airline = r.nextInt(10);
int number = r.nextInt(900) + 100;
callsign = AIRLINES[airline] + number;
}
#Override
public String toString() {
return "Flight [callsign=" + callsign + "]";
}
}
Output
Flight [callsign=SKW534]

Related

How to save the results of a called method of all the objects in an array?

I am creating a program that handles a car dealership. The user has the opportunity to add a car in the store by creating a random 3 digit number.
Now the question is how I can search/delete cars depending on the 3 digit code?
I'm thinking that I need every code that the cars have to save it on an array so I can search and delete afterwards.
I have created a class and certain methods on it, I have also created 5 objects and I'm trying to see if it works on these 5.
Here is the method of the random number:
I use the metritis variable because I can't achieve to place correctly the values on the array so I have to give parameter of 1,2,3,4,5 so I can place them correctly to the array.
package antiprosopeia;
import java.util.Random;
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int[] codes = new int[]{0,0,0,0,0};
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price) {
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
}
public Antiprosopeia() {
company = ""; colour = ""; model = 0; horsePower = 0; speed = 0; price = 0;
}
public void setRandomNumber(int metritis) {
Random rand = new Random();
int randNum2 = rand.nextInt(900) + 100;
specialCode = randNum2;
codes[metritis] = specialCode;
}
public void printarray() {
for(int i=0; i<codes.length; i++) {
System.out.println(" " + codes[i]);}
}
public void Info() {
System.out.println("Company : " + company + "\nColour : " + colour + "\nModel : " + model + "\nHorse Power : " + horsePower +
"\nSpeed : " + speed + "\nPrice : " + price );
}
public static void main(String[] args) {
Antiprosopeia car1 = new Antiprosopeia("Toyota","red",333,100,2223,8000);
car1.setRandomNumber(0);
Antiprosopeia car2 = new Antiprosopeia("Mercedes","yellow",233,100,2990,9000);
car2.setRandomNumber(1);
Antiprosopeia car3 = new Antiprosopeia("Volkswagen","green",153,100,2780,6000);
car3.setRandomNumber(2);
Antiprosopeia car4 = new Antiprosopeia("Mitsubisi","white",678,140,2600,7000);
car4.setRandomNumber(3);
Antiprosopeia car5 = new Antiprosopeia("Porsche","black",390,1000,2000,30000);
car5.setRandomNumber(4);
}
}
[EDIT] Now when i call the printarray() method it seems that at my array only one value is hold and all the others are zer0s as i defined the array at start of my program
If I were doing this, I would use a HashMap. This way you know that you have a unique 3 digit number, and if you wanted to, you could also store more data. You could do something like:
HashMap<Integer, Car> cars = new HashMap<Integer, Car>();
This example would allow you to add a car object to the map. You don't have to that, but it's an option. If you didn't want to do that, you could do:
HashMap<Integer, String> cars = new HashMap<Integer, String>();
and then do:
cars.put(123, "Description of car");
Using a HashMap would give you more options when storing the data. This would also prevent you from creating an array with 1000 elements, all of which are 0 until you have a value for them. You could easily print out all your numbers by doing:
for(int number : cars.entrySet()){
System.out.println("My car number: " + number);
}
Searching for keys would extremely easy, as you could do:
String description = cars.getKey(123);
If description was null, you would know that there is no key for it.
Your issue is that each Antiprosopeia object has its own codes array. They are not shared.
If you really want each object to have a Random ID, then assign that within the constructor.
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int randID;
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price){
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
this.randID = new Random().nextInt(900) + 100;
}
public Antiprosopeia(){
this("", "", 0, 0, 0, 0);
}
public int getID() { return this.randID; }
#Override
public String toString() {
return String.format(
"Company : %s\n" +
"Colour : %s\n" +
"Model : %s\n" +
"Horse Power : %d\n" +
"Speed : %d\n" +
"Price : %d\n",
company, colour, model, horsePower, speed, price
);
}
If you want to print all those objects,
public static void main(String[] args) {
List<Antiprosopeia> cars = new ArrayList<Antiprosopeia>();
cars.add(new Antiprosopeia("Toyota","red",333,100,2223,8000));
cars.add(new Antiprosopeia("Mercedes","yellow",233,100,2990,9000));
for (int i = 0; i < cars.size(); i++) {
Antiprosopeia c = cars.get(i);
System.out.println(c.getID());
System.out.println(c);
}
}

When the value of i++ operation taking place and store in its reference in Java ..?

I am reading Thinking in java book, which is quite interesting, there is an example in the book, and the behavior of the example and the output is not as I expected.
The Example:
package net.mindview.util;
import static net.mindview.util.Print.*;
class Shared {
private int refcount = 0;
private static long counter = 0;
private final long id = counter++;
public Shared() {
print("Creating " + this);
}
public void addRef() {
refcount++;
}
protected void dispose() {
if (--refcount == 0)
print("Disposing " + this);
}
public String toString() {
System.out.println(id);
return "Shared " + id;
}
}
class Composing {
private Shared shared;
private static long counter = 0;
private final long id = counter++;
public Composing(Shared shared) {
print("Creating " + this);
this.shared = shared;
this.shared.addRef();
}
protected void dispose() {
print("disposing " + this);
shared.dispose();
}
public String toString() {
return "Composing " + id;
}
}
public class ReferenceCounting {
public static void main(String[] args) {
Shared shared = new Shared();
Composing[] composing = { new Composing(shared), new Composing(shared),
new Composing(shared), new Composing(shared),
new Composing(shared) };
for (Composing c : composing)
c.dispose();
}
}
This is an example of dispose method, which I fully understand, my question is in the value of id in Shared class.
As I am learning from Thinking in java, the initialization of the field and objects should occur before any method get called, even the Constructor, But the output for the constructor of Shared class is "Creating Shared 0" which the value of id is considered to be 0 in spite of private final long id = counter++; has took a place and now as I imagine the id value should be 1 not zero. Could any one explain to me the behavior.
counter++ is post-increment, this means the value is assigned before incrementation. pre-increment on the other side would show the behavior you expected.
This is an example of post-increment. In other words, the old value is stored in a temporary variable and returned after incrementing. It is the equivalent of:
int i = 0;
int tmp = i;
i += 1;
System.out.println(tmp); //prints 0
The opposite is pre-increment, where the incremented value is returned:
int i = 0;
System.out.println(++i); //prints 1
When you say counter++ it is a post-increment operator (on the next line, counter is increased by one). Based on your question, I think you expected the behavior of the pre-increment operator. Change
final long id = counter++;
to something like
final long id = ++counter;
or even
final long id = counter + 1;
counter++;

Array from a seperate object not printing correctly

I have a program that currently I'm trying to create a player with customizable integers. I use this object:
public class Player {
public String player = null;
private int Strength=0;
private int Defense=0;
private int Magic=0;
private int Resistance=0;
private int Skill=0;
private int Luck=0;
public Player(String name, int int1, int int2, int int3, int int4, int int5, int int6) {
this.player = name;
this.Strength = int1;
this.Defense = int2;
this.Magic = int3;
this.Resistance = int4;
this.Skill = int5;
this.Luck = int6;
}
}
I use this main class to run it, and set the integer and string values.
public class Main {
public static void main(String[] args) {
Player[] playerList = new Player[] {new Player("Player1", 3, 3, 2, 1, 1, 3),new Player("Player2", 1, 1, 1, 1, 1, 1)};
}
}
However, whenever I attempt to print this, it prints this:Player#659e0bfd
I looked through similar questions, but I am not sure where to put the #Override in my program, and if I need to do something different since I have multiple integers, and a string. I only want the string to print out. (Also, is there a way to print out just one part of the playerList, ie. the first section "Player1")
In the Player class you need to put the override.
Someting like:
public class Player {
// fields here
#Override
public String toString() {
return Strength + " " + Defense; // plus all the fields here
}
}
Regarding your other question: yes, you can, but since all the fields are private, you need to create getters for those fields. Then you can do:
public class Player {
private int defense;
private String name;
public Player(int defense, String name) {
this.defense = defense;
this.name = name;
}
public int getDefense() {
return this.defense;
}
public String getName() {
return this.name;
}
}
Player player = new Player(9000);
System.out.println(player.getName + " has defense + " player.getDefense());
Also, it's a good idea to stick to Java conventions. This means that variables are written with a lower case, like strength instead of Strength.
What you are seeing is the output of the toString method in the Object class, which your Player class implicitly extends. If you wish for it to output something else, you must override the toString() method in your Player class.
For instance, add something like this:
#Override
public String toString() {
return "Player(Strength: " + Strength + ", Defense: " + Defense + ")";
}
So basically i assume u use the System.out.println(); method to display ur Object right? You defined your own class and objects. You have to define your own print method, which you have to override. The method is called
#Override
public String toString(){ return this.Strength + " " + this....);
This method will be called automatically if you insert your object in your System.outprintln();

Assigning current array index to a variable in order to increment it?

I have an array of messages which are called upon to display in a textfield. I would like to assign the array index i.e. [0] to a variable so that when the person enters the correct text I can get the current array index and increment it to the next one to be able to print out. How can I do this?
I have these methods:
#Override
public void actionPerformed(ActionEvent e) {
String text = commandInput.getText();
messageDisplay.append("\n \n" + text + "\n \n");
commandInput.selectAll();
}
public String getCurrentLevel() {
return currentLevel;
}
After commandInput.selectAll(); I would like to do getCurrentLevel() + 1 to get the next element in the array to append.
Here is the array class it is pulling from:
package com.game.main;
public class Message {
public String[] messageArray;
public Message() {
messageArray = new String[50];
messageArray[0] = "Welcome. ";
}
}
I am not quite sure if this is what you are looking for, but subsequent calls to getNextMessage() will return the next message in the array. Call it too many times and it will go out of bounds etc. This of course assumes you are not recreating the class between calls, if so, you need to make the indx static.
An alternative way to do this using an ArrayList instead of an array:
//using an ArrayList<String>
public class Message {
private int indx = 0;
private ArrayList<String> messages;
public Message() {
messages = new ArrayList<String>();
messages.add("Welcome. ");
}
public String getNextMessage(){
String s = messages.get(indx);
indx++;
return s;
}
// using an array
public class Message {
private int indx = 0;
private String[] messageArray;
public Message() {
messageArray = new String[50];
messageArray[0] = "Welcome. ";
}
public String getNextMessage(){
String s = messageArray[indx];
indx++;
return s;
}

Possible to store string and integers in one object

Is it possible to store a string and 11 integers in the same object.
Thanks,
Alex
Sure. You can put any members in an object you like. For example, this class stores a string and 11 integers. The integers are stored in an array. If you know there are going to be 11 of them (or any fixed number obviously) this tends to be preferable to storing 11 separate int members.
public class MyObject {
private String text;
private int[11] numbers = new int[11];
public String getText() { return text; }
public void setText(String text) { this.text = text; }
public int getNumber(int index) { return numbers[index]; }
public void setNumber(int index, int value) { numbers[index] = value; }
}
So you can write some code like:
MyObject ob = new MyObject();
ob.setText("Hello world");
ob.setNumber(7, 123);
ob.setNumber(3, 456);
System.out.println("Text is " + ob.getText() + " and number 3 is " + ob.getNumber(3));
Note: arrays in Java are zero-based. That means that a size 11 array has elements at indexes 0 through 10 inclusive.
You haven't really specified if 11 is a fixed number of what the meaning and usage of the numbers and text are. Depending on the answer that could completely change how best to do this.
Yes - make 12 private data members and you're there.
Whether they all belong in the same object is a different question.
You can put them in an array Objects as well:
private Object[] mixedObjs = new Object[12];
Yes. You will have to create this class. It is possible.
Create a class that implements an object containing a string and 11 integers:
public class StringAndInt extends Object
{
private int[] user = new int[11];
private String string = "";
public StringAndInt(String s, int[] i){
user = i;
string = s;
}
public StringAndInt setInt(int[] i){
number = i;
return this;
}
public StringAndInt setString(String s){
string = s;
return this;
}
public int getInt(){
return user;
}
public String getString(){
return string;
}
}

Categories

Resources