Possible to store string and integers in one object - java

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;
}
}

Related

Make String from String[] and int

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]

Add data from file into ArrayList and sorting

I am trying to take data from a text file containing Strings and Integers into an ArrayList, and then sort it (which will depend on the integer values).
The text in the file pattern looks like this "Höllviken;23642". Seperated by a ";" character.
So far I've gotten this:
public class SorteraOrter{
public static void main(String[] args)throws IOException{
// scans file orter
File stad = new File("C:\\Users\\Johan\\Desktop\\orter.txt");
Scanner n = new Scanner(stad);
ArrayList<Object> city = new ArrayList();
while(n.hasNext()){
String ln = n.nextLine();
String[] arr = ln.split(";");
Ort ort = new Ort(arr[0],Integer.valueOf(arr[1]));
city.add(ort);
}
System.out.println(city.toString());
}
}
For sorting i have declared some methods and made a compareTo method to use with sort.
:
package soter_orter;
public class Ort implements Comparable<Ort> {
// fields
private int postnr = 0;
private String ort = "";
// constructor
public Ort(String s, int p){s = ort; p = postnr;}
// method names
public int postnr() {
return postnr;
}
public String ort() {
return ort;
}
public int compareTo(Ort o){
return o.postnr - postnr;
}
public String toString(){
return ort + " " + postnr;
}
}
So to do this first i have to succeed in adding these Strings and Integers into my ArrayList. I also need to have them connected in some way since the number and the text file belong to eachother.
My current problem is the output im getting after trying to move the file-input to the ArrayList -
[ 0, 0, 0, 0, 0, 0, 0]
I've come a bit further and added the elemets of my ArrayList to an Object Array. I am able to sort this but unable to view it using my toString method.
Object[] arr = new Object[city.size()];
for (int i = 0; i<city.size(); i++){
arr[i] = city.get(i);
}
Arrays.sort(arr);
for (Ort o : arr){
}
I am unable to print this in the for loop. I get the message: "Type mismatch: cannot convert from element type Object to Ort"
So, so far I am unable to print the ArrayList neither the Object Array.
your constructor in Ort class should be
public Ort(String s, int p){ort=s; postnr=p;}
Your constructor ir wrong.
replace
public Ort(String s, int p){s = ort; p = postnr;}
for
public Ort(String s, int p){ort = s; postnr = p;}

Can Multidimensional Arrays how two different types in them within java

Can a multidimensional array in java have two types like a string and double in it?
Like: {name, num},{name, num}
Zoyd has it right, that this should be done with a class. Here's a more complete example.
class MyClass
{
private String name;
private int num;
public MyClass(String name, int num)
{
this.name = name;
this.num = num;
}
public String getName()
{
return name;
}
public int getNum()
{
return num;
}
}
MyClass[] array = new MyClass[5];
array[0] = new MyClass("name1", 5);
array[1] = new MyClass("name2", 8);
...
If name or num ever need to change after original creation, then you can add setters for them.
In Java, this is normally done with a class.
class C {
public String name;
public int num;
}
(later)
C[] myArray = new C[5];
myArray[3] = new C();
myArray[3].name = "Ford";
myArray[3].num = 42;
name and num should typically be made private and accessed with getters and setters, but this is beyond the point.
int row=10;
int col=10;
Object [][] objArray=new Object[row][col];
objArray[0][0]=181818;
objArray[0][1]="Hello String";
System.out.println(objArray[0][0]);
System.out.println(objArray[0][1]);
You can use Object for that.
Plus you need to search before you post it. There is already answer here. Two-dimensional array of different types
This solution has nothing to do with arrays, but if you've got {name, num}, {name, num} data, you might want to consider using a map.
Map<String, Double> map = new HashMap<String, Double>();
Double valueX = 123.456;
Double valueY = 654.321;
map.put("nameX", valueX);
map.put("nameY", valueY);
Double valueX = c.get("name");
for(String name:c.keySet()) {
System.out.println("name:"+name+"\tvalue:"+c.get(name));
}

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;
}

Sorting 2D array of strings in Java

I know that this question might have been asked before, but I was not able to find a fit answer. So say I have this array:
String[][] theArray = {
{"james", "30.0"},
{"joyce", "35.0"},
{"frank", "3.0"},
{"zach", "34.0"}};
Is there a way to descendingly sort this array by the second element of each sub-element. So I would get something like this.
theArray = {
{"joyce", "35.0"},
{"zach", "34.0"},
{"james", "30.0"},
{"frank", "3.0"}};
Use Arrays.sort(arr, comparator) with a custom comparator:
Arrays.sort(theArray, new Comparator<String[]>(){
#Override
public int compare(final String[] first, final String[] second){
// here you should usually check that first and second
// a) are not null and b) have at least two items
// updated after comments: comparing Double, not Strings
// makes more sense, thanks Bart Kiers
return Double.valueOf(second[1]).compareTo(
Double.valueOf(first[1])
);
}
});
System.out.println(Arrays.deepToString(theArray));
Output:
[[joyce, 35.0], [zach, 34.0], [james, 30.0], [frank, 23.0]]
Beware:
you will be sorting the array you passed in, Arrays.sort() will not return a new array (in fact it returns void). If you want a sorted copy, do this:
String[][] theCopy = Arrays.copyOf(theArray, theArray.length);
And perform the sorting on theCopy, not theArray.
You must use the Arrays.sort() method. This method takes a Comparator as argument. The sort method delegates to the comparator to determine if one element of the array must be considered bigger, smaller or equal to another element. Since every element of the outer array is an array, the comparator will have to compare arrays (of Strings).
The arrays must be compared based on the value of their second element. This second element is a String which in fact represents a double number. So you'll have to transorm the strings into numbers, else the order will be lexicographical (20 come before 3) rather than numerical.
The comparator could thus look like this :
public class StrinArrayComparator implements Comparator<String[]> {
#Override
public int compare(String[] array1, String[] array2) {
// get the second element of each array, andtransform it into a Double
Double d1 = Double.valueOf(array1.[1]);
Double d2 = Double.valueOf(array2.[1]);
// since you want a descending order, you need to negate the
// comparison of the double
return -d1.compareTo(d2);
// or : return d2.compareTo(d1);
}
}
If you want to move away from arrays, here's a variation that uses List<Record> and a RecordComparator that implements Comparator<Record>.
Console:
joyce 35.0
zach 34.0
james 30.0
frank 23.0
Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/** #see http://stackoverflow.com/questions/5064027 */
public class ComparatorTest {
public static void main(String[] args) {
List<Record> list = new ArrayList<Record>(Arrays.asList(
new Record("james", "30.0"),
new Record("joyce", "35.0"),
new Record("frank", "23.0"),
new Record("zach", "34.0")));
print(list, Sort.DESCENDING, Field.D);
}
private static void print(List<Record> list, Sort s, Field f) {
RecordComparator rc = new RecordComparator(s, f);
Collections.sort(list, rc);
for (Record r : list) {
System.out.println(r);
}
}
}
class Record {
private String s;
private Double d;
public Record(String name, String number) {
this.s = name;
this.d = Double.valueOf(number);
}
#Override
public String toString() {
return s + " " + d;
}
public int compareTo(Field field, Record record) {
switch (field) {
case S: return this.s.compareTo(record.s);
case D: return this.d.compareTo(record.d);
default: throw new IllegalArgumentException(
"Unable to sort Records by " + field.getType());
}
}
}
enum Sort { ASCENDING, DESCENDING; }
enum Field {
S(String.class), D(Double.class);
private Class type;
Field(Class<? extends Comparable> type) {
this.type = type;
}
public Class getType() {
return type;
}
}
class RecordComparator implements Comparator<Record> {
private Field field;
private Sort sort;
public RecordComparator(Sort sort, Field field) {
this.sort = sort;
this.field = field;
}
#Override
public final int compare(Record a, Record b) {
int result = a.compareTo(field, b);
if (sort == Sort.ASCENDING) return result;
else return -result;
}
}
You seem to be living in object denial. Those inner arrays look a lot like information about a Person (with the name and some value, maybe a score).
What you'd want to do is to write a custom class to hold that information:
public class Person {
private final String name;
private final double score;
public Person(final String name, final double score) {
this.name=name;
this.score=score;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
}
Then, when you want to sort them, you simply implement a Comparator<Person> that specifies how you want them sorted:
public PersonScoreComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getScore(), p2.getScore());
}
}
Alternatively, you could have the Person class itself implement Comparable<Person> by adding this method:
public int compareTo(Person other) {
return Double.compare(getScore(), other.getScore());
}
-Create list out of this array using Arrays.toList()
-Design comparator using java.lang.comparator and write logic for sorting every even elements
There are several sort methods in java.util.Arrays. Two of them take custom Comparators. Simply provide a comparator comparing the second element of the inner arrays.
public static void main(String[] args)
{
String Name[][]={{"prakash","kumar"},{"raj","kappor"},{"vinod","bhart"}};
String str[]=new String[2];
for(int j=0; j<Name.length;j++)
{
for (int i=0 ; i<2; i++)
{
str[i]=Name[j][i];
}
for(int i=0;i<str.length;i++)
{
for(int k=i+1;k<str.length;k++)
{
if(str[i].compareTo(str[k])>0)
{
String temp= str[i];
str[i]=str[k];
str[k]=temp;
}
}
System.out.print(str[i]+ " ");
}
System.out.println();
}
}
}
/**
*
* #param array - 2D array required to be arranged by certain column
* #param columnIndex - starts from 0; this will be the main comparator
* #param hasHeaders - true/false; true - ignore the first row. False -
* first row it's also compared and arranged
* #return - the new arranged array
*/
private String[][] arrangeArray(String[][] array, int columnIndex, boolean hasHeaders) {
int headersExists = 0;
if (hasHeaders) {
headersExists = 1;
}
for (int i = headersExists; i < array.length; i++) {
for (int j = headersExists; j < array.length; j++) {
if (array[i][columnIndex].compareTo(array[j][columnIndex]) < 0){
String[] temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}

Categories

Resources