Create a Struct In Java Like C++ - java

i want to create an struct in java , like c++ :
struct MyStruct {
int x;
};
#include <iostream>
int main() {
MyStruct Struct;
Struct.x = 0;
std::cout << Struct.x;
return 0;
}
can anyone help me ?

You can use a class, which functions similarly to a struct in C++.
For example, a C++ point struct may look like
typedef struct __point {
int x, y;
} point;
A Java point class has the form
final class Point {
private final double x; // x-coordinate
private final double y; // y-coordinate
// point initialized from parameters
public Point(double x, double y) {
this.x = x;
this.y = y;
}
// accessor methods
public double x() { return x; }
public double y() { return y; }
// return a string representation of this point
public String toString() {
return "(" + x + ", " + y + ")";
}
}
We may then call the following:
Point q = new Point(0.5, 0.5);
System.out.println("q = " + q);
System.out.println("x = " + q.x());

public class ircodes {
public ircodes(String msg_id, String node_id, String frequency, String data) {
this.hdr = new msg_hdr(4 + data.length(), Integer.parseInt(msg_id), Integer.parseInt(node_id));
this.frequency = Integer.parseInt(frequency);
this.data = data;
}
public class msg_hdr {
int msg_len;
int msg_id;
int node_id;
public msg_hdr(int msg_len, int msg_id, int node_id) {
this.msg_len = 12 + msg_len;
this.msg_id = msg_id;
this.node_id = node_id;
}
}
msg_hdr hdr;
int frequency;
String data;
public ByteBuffer serialize() {
ByteBuffer buf = ByteBuffer.allocate(hdr.msg_len);
buf.putInt(hdr.msg_len);
buf.putInt(hdr.msg_id);
buf.putInt(hdr.node_id);
buf.putInt(frequency);
buf.put(data.getBytes());
return buf;
}
}

Java doesn't have structs like C or C++, but you can use Java classes and treat them like a struct. On top of that, you can of course declare all its members as public. (to work exactly like a struct)
class MyClass
{
public int num;
}
MyClass m = new MyClass();
m.num = 5;
System.out.println(n.num);
One of the differences between a struct and a class is that a struct do not have methods. If you create a class without methods, it will work like a struct.
However, you can always put in methods (getters and setters) and set the variables as private like this (it doesn't hurt).
class MyClass
{
private int num;
public void setNum(int num){
this.num = num
}
public int getNum(){
return num
}
}
MyClass m = new MyClass();
m.setNum(5);
System.out.println(n.getNum());
Java doesn't have structs, but a Class can do exactly the same things a struct does.

Related

Java Interfaces/Callbacks for Using 1 of 2 Possible Methods

I have read up on Java Interfaces (callbacks) because I was told by a professor I should use callbacks in one of my programs. In my code, there are two Mathematical functions I can 'pick' from. Instead of making a method activate() and changing the code inside (from one function to the other) when I want to change functions, he said I should use callbacks. However, from what I've read about callbacks, I'm not sure how this would be useful.
EDIT: added my code
public interface
//the Interface
Activation {
double activate(Object anObject);
}
//one of the methods
public void sigmoid(double x)
{
1 / (1 + Math.exp(-x));
}
//other method
public void htan(final double[] x, final int start,
final int size) {
for (int i = start; i < start + size; i++) {
x[i] = Math.tanh(x[i]);
}
}
public double derivativeFunction(final double x) {
return (1.0 - x * x);
}
}
If you want to use interfaces something like this would work.
I have a MathFunc interface that has a calc method.
In the program I have a MathFunc for mutliplication and one for addition.
With the method chooseFunc you can choose one of both and with doCalc the current chosen MathFunc will do the calculation.
public interface MathFunc {
int calc(int a, int b);
}
and you can use it like that:
public class Program {
private MathFunc mult = new MathFunc() {
public int calc(int a, int b) {
return a*b;
}
};
private MathFunc add = new MathFunc() {
public int calc(int a, int b) {
return a+b;
}
};
private MathFunc current = null;
// Here you choose the function
// It doesnt matter in which way you choose the function.
public void chooseFunc(String func) {
if ("mult".equals(func))
current = mult;
if ("add".equals(func))
current = add;
}
// here you calculate with the chosen function
public int doCalc(int a, int b) {
if (current != null)
return current.calc(a, b);
return 0;
}
public static void main(String[] args) {
Program program = new Program();
program.chooseFunc("mult");
System.out.println(program.doCalc(3, 3)); // prints 9
program.chooseFunc("add");
System.out.println(program.doCalc(3, 3)); // prints 6
}
}

Returning multiple values java

Say I have a java function as follows,
public static int my(int a, int b)
{
int c = a + b;
return c;
String d = "Some Data";
return d;
float f = a/b;
return f
}
So, how do I get the 3 return values separately?
all the values are of different data types.
I've seen this question and this question but couldn't understand properly.
any function can only return one value. What you can do is to create an objet containing all your answers and return this object.
class ResultObject
{
public int c;
public int d;
public int e;
public int f;
}
in your function white
public static ResultObject my(int a, int b)
{
ResultObject resObject = new ResultObject();
resObject.c = a + b;
resObject.d = a*b;
resObject.e = a-b;
resObject.f = a/b;
return resObject;
}
You can return only one value. You have to make that value to "contain" other values.
There are two ways.
If you returning uniform values, e.g. hundred values for temperature over a period of time - use arrays.
If values are non-uniform, e.g. first name, last name and age - introduce a new class.
Reason for this is that Java is a strongly-typed programming language. Wanna describe a new data structure - write a new class.
return array of int.. e.g. int[]...
public static int[] my(int a, int b) {
int res[] = new int[4];
int c = a + b;
res[0] = c;
int d = a * b;
res[1] = d;
int e = a - b;
res[2] = e;
int f = a / b;
res[3] = f;
return res;
}
You can try something like this
public static int[] my(int a, int b) { // use an array to store values
int[] arr = new int[4];
int c = a + b;
arr[0] = c;
int d = a * b;
arr[1] = d;
int e = a - b;
arr[2] = e;
int f = a / b;
arr[3] = f;
return arr; // return values
}
You can return only one element but the element may be array or list.you may return list of values.(some exercise). I hope this may bring some solution.
public class DataStorage{
private int a;
private String data;
private float f;
public DataStorage(int a, String data, float f){
this.a = a;
this.data = data;
this.f = f;
}
/* standard get/set method. */
}
public static DataStorage my(int a, int b)
{
int c = a + b;
String d = "Some Data";
float f = a/b;
DataStorage dataStorage = new DataStorage(c,d,f);
return dataStorage;
}

How do this subclass interact with the main class

I'm stuck on a mock exam question. I created a class called Power which allowed a number to be raised to any power.
The third part of the question asks me to create another class BoundedPower which would extend Power. I was given the MAX-X variable (x cannot exceed this value) and told that the BoundedPower class must: behave like the Power class, use a constructor and use thepowN method.
My code is below, i am not sure what to do to make the BoundedPower class work.
public class Power {
private double x = 0;
Power(double x) {
this.x = x;
}
public double getX() {
return x;
}
public double powN(int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
public static void main(String[] args) {
Power p = new Power(5.0);
double d = p.powN(3);
System.out.println(d);
}
}
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
// invariant: x <= MAX_X
Power x;
BoundedPower(double x) {
super(x);
// this.x=x; x is private in Power class
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * getX();
}
return result;
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
There is no need for that instance Power variable x in your class. Any BoundedPower instance IS a Power instance, and as such, to reference a method from Power, do super.blah(), so for x.getX(), do super.getX()
Also, in your comments, you said this.x=x fails because its private. When you do the super call, it calls the constructor of the superclass (Power), which sets x there, so there is no need for this.x=x
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
BoundedPower(double x) {
super(x);
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
return super.powN(n);
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
You don't have to copy your computation formular to the subclass (just call super.powN(..)). You also don't need another instance of Power within BoundedPower.
This is probably what they had in mind:
public class Power {
public double powN(double x, int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
}
public class BoundedPower extends Power {
private final double maxX;
public BoundedPower(double maxX) {
this.maxX = maxX;
}
public double powN(double x, int n) {
if (x > maxX) {
throw new IllegalArgumentException("x value [" + x + "] " +
"greater than expected max [" + maxX + "]");
}
return super.powN(x, n);
}
}
I would do it in a different way. From what you're saying the BoundedPower class makes sense only for a bounded x (up to MAX_X).
Consequently, I would not allow the creation of an object with an x greater than MAX_X (i.e. a BoundedPower object cannot exist for unbounded x's)
So the implementation would be exactly as the the Power implementation excepting the way you build BoundedPower instances : you first check whether it makes sense to build it
public class BoundedPower extends Power {
private static final double MAX_X = 1000000; //makes no sense to be public
public static BoundedPower newBoundedPower(int n)
throws IllegalNumberException{
if(x > MAX_X) throw new IllegalNumberException();
return new BoundedPower(x);
}
private BoundedPower(double x) {
super(x);
}
}

store X and Y coordinates

Hi im new to this site and need help with a program im working on. the problem im having is that i cant seem to store string and two integers (as the coordinates). i have looked at other code but dont see how the values are stored. below is the code ive been using. the code seems to be fine but when trying to stored the values i cant put multiply integers. thanks for your time
import java.util.HashMap;
public class map {
class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, Character> map = new HashMap<Coords, Character>();
map.put(new coords(65, 72), "Dan");
}
}
There is a class in java called Class Point.
http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html
This is the same information provided on Java docs API 10:
https://docs.oracle.com/javase/10/docs/api/java/awt/Point.html
A point representing a location in (x,y) coordinate space, specified in integer precision.
You can see an example, and also other important topics related in this link: http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/Pointclass.htm
import java.awt.Point;
class PointSetter {
public static void main(String[] arguments) {
Point location = new Point(4, 13);
System.out.println("Starting location:");
System.out.println("X equals " + location.x);
System.out.println("Y equals " + location.y);
System.out.println("\nMoving to (7, 6)");
location.x = 7;
location.y = 6;
System.out.println("\nEnding location:");
System.out.println("X equals " + location.x);
System.out.println("Y equals " + location.y);
}
}
I hope this can help you!
There seems to be several issues:
"Dan" is a String, not a Character
case is important in Java (new coords(65,72) should be new Coords(65,72))
Coords needs to be static to be instantiated without a reference to an instance the enclosing map class.
This should work:
static class Coords {
...
}
Map<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
ps: although you are allowed to name a local variable map within a class map, it is not a good idea to have such name collision. In Java, classes generally start in upper case, so you could rename your class Map. But it happens that Map is a standard class in Java. So call your class Main or Test or whatever is relevant. ;-)
Adding to #assylias
Make you inner class static in order to insert new objects like you have or new Outer().new Inner() .
Take care of Java Naming Convention
Code like:
public class XYTest {
static class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
map.put(new Coords(68, 78), "Amn");
map.put(new Coords(675, 89), "Ann");
System.out.println(map.size());
}
}
package Lecture3;
import java.util.Scanner;
public class lecture9 {
private int nInleste;
public lecture9() {/*
* tabell/ // T/*chapter 6 in the books.
**/
}
public static void main(String[] args) {
Scanner inn = new Scanner(System.in);
int nInleste = 3;
double[] tall = new double[nInleste];
double sum = 0;
for (int i = 0; i < nInleste; i++) {
System.out.println("Leste en tall!");
tall[i] = inn.nextDouble();
sum += tall[i];
}
System.out.println(sum);
double snitt = nInleste / nInleste;
System.out.println("Gjennomsnittsverdien:" + snitt);
for (int i = 0; i < nInleste; i++) {
double aavik = tall[i] - snitt;
int avvivk = 0;
System.out.println(i + 1 + " Tal sitt avvik fra gjennomsnittet " + avvivk);
}
}/* end of the main methods */
}
if you have problem with your code you can try this , simple code to store string and two int values into a map
class MyCoord{
private int X;
private int Y;
public MyCoord() {
this(0,0);
}
public MyCoord(int X, int Y) {
this.X = X;
this.Y = Y;
}
public int getX() {
return X;
}
public int getY() {
return Y;
}
public void setX(int X) {
this.X = X;
}
public void setY(int Y) {
this.Y = Y;
}
}
//main class begins
public class PointDemo{
public static void main(String[] args) {
Map <String,MyCoord> multiplePoints=new HashMap<String, MyCoord>();
multiplePoints.put("point1", new MyCoord(10, 20));
multiplePoints.put("point2", new MyCoord(100, 2000));
MyCoord coord=multiplePoints.get("point1");
System.out.println(coord.getX() +" : "+coord.getY());
}
}

Comparison on different classes

Let me give some code so you can see what I'm doing with the following java code for android. Say for example I have the following two classes, one extended from the other:
class MyClassOne {
protected float x, y;
MyClassOne(float x, float y) {
this.x = x; this.y=y;
}
public void printY(){
System.out.print(y);
}
}
class MyClassTwo extends MyClassOne {
protected String stringSpecificToThisClass;
private long longSpecificTothisClass;
MyClassTwo(float x, float y, String s, long l) {
this.x=x; this.y=y;
this.longSpecificTothisClass= l; this.stringSpecificTothisClass=s;
}
}
These classes are then initialized in the following way
private ArrayList<MyClassOne> mClassOne = new ArrayList<MyClassOne>();
private ArrayList<MyClassTwo> mClassTwo = new ArrayList<MyClassTwo>();
for(int i=0;i<5;i++){
Random random = new Random(10);
mClassOne.add(new MyClassOne(i*12, random.nextInt()));
mClassTwo.add(new MyClassOne(i*11, random.nextInt()));
}
now, what I want to do is compare and sort both arraylists according to the value of y.
The way i do this for a single list is like so:
private Object[][] mSort(){
Object[][] mSort = new Object[mClassOne.size()][2];
for(int i = 0; i<mClassOne.size(); i++){
mSort[i][0] = i;
mSort[i][1] = mClassOne.get(i).y;
}
Arrays.sort(mSort, new Comparator<Object[]>(){
#Override
public int compare(Object[] obj1, Object[] obj2){
Float comp1 = (Float)obj1[1]; Float comp2 = (Float) obj2[1];
return comp1.compareTo(comp2);
}
});
return mSort;
}
Object[][] mSort = mSort();
for(int i=0;i<mClassOne.size();i++){
int z = (Integer)mSort[i][0];
mClassOne.get(z).printY();
}
which could output something like this:
2, 4, 5, 6, 9
Hopefully the code above is clear enough so others can see what I'm trying to do; the question is:
"How could I combine both ArrayLists then sort them by their respective y value."
The Answer I was looking for
ArrayList<MyClassOne> mTest = new ArrayList<MyClassOne>();
mTest.addAll(mClassOne);
mTest.addAll(mClassTwo);
Collections.sort(mTest, new Comparator<MyClassOne>(){
#Override
public int compare(MyClassOne obj1, MyClassTwo obj2) {
return (int) (obj1.getY() - obj2.getY()); }
}
);
// mTest is now sorted, verified by ~ foreach(mTest) {print mTest.getY(); }
Well, you could use a Comparator<MyClassOne> which should be able to handle MyClassTwo instances as well, since MyClassTwo extends MyClassOne.
Just create a single List<MyClassOne>, add all elements of the other lists and sort.
In cases where the classes don't extend each other, introduce a common interface.

Categories