How to retrive itrms froma set (hashset) - java

Good afternoon.
I am stuck in helping my son in a Java program. Hope someone can help.
Here is the problem.
In Main i have, amoung other.... the read from scanner like this:
Scanner in = new Scanner(System.in);
Chord c1 = createChord(in); // este chama o private static Chord createChord(Scanner in)
Chord c2 = createChord(in);
Chord c3 = createChord(in);
Chord c4 = createChord(in);
executeCommand(in);
executeCommand(in);
executeCommand(in);
executeCommand(in);
in.close();
}
private static Chord createChord(Scanner in) {
int n1 = in.nextInt();
int n2 = in.nextInt();
int n3 = in.nextInt();
in.nextLine();
//System.out.print(n1);
//System.out.print(n2);
//System.out.print(n3);
return new Chord (n1, n2, n3);
}
Lets assume the method returns values 1,2 and 3 into the hash Chord.
The question is
How can i, in the program, retrieve the vaules from c1 to c4, for instance, the first or the third element from one of them?
I would greatly appreciate anny help.
Peter Rodrigues

If I understand you correctly your question is how to get the values you passed into Chord?
You passed those values via the constructor and than you can save them as members in the object of the class. Those members can be made accessible via "Getters".
Example:
public class Chord {
final int a;
final int b;
final int c;
public Chord(final int a, final int b, final int c) {
this.a = a;
this.b = b;
this.c = c;
}
public int getA() { return a; }
public int getB() { return b; }
public int getC() { return c; }
}
You can read up on that e.g. here.

Related

How to transform this class to immutable?

I am in process of learning immutability but I am not able to exactly digest how this works. So in order for me to understand immutability, I created a test program.
The funtion getArray(Box b) will make an ArrayList of Box objects.
Expected output: Actual output:
Output Output
a is 5 a is 5
b is 10 b is 10
Output Output
a is 0 a is 4
b is 0 b is 40
Output Output
a is 1 a is 4
b is 10 b is 40
Output Output
a is 2 a is 4
b is 20 b is 40
Output Output
a is 3 a is 4
b is 30 b is 40
Output Output
a is 4 a is 4
b is 40 b is 40
Logic:
public class Box {
static int a;
static int b;
public Box() {
a = 5;
b = 10;
}
public int getA() {
return a;
}
public void setA(int x) {
a = x;
}
public int getB() {
return b;
}
public void setB(int x) {
b = x;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Main Class
import java.util.ArrayList;
public class Check {
public static void main(String[] args) {
Box b = new Box();
b.display();
ArrayList<Box> arr2 = new ArrayList<Box>();
arr2 = getArray(b);
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box>();
for (int i = 0; i < 5; i++) {
b.setA(i);
b.setB(i * 10);
arr.add(b);
}
return arr;
}
}
How do I change the logic in such a way that I get the desired output? How do we decide how and where to edit the code to ensure immutability?
This would be an immutable:
public final class Box {
final int a;
final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
}
And then your array method would be:
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box> ();
for(int i =0 ;i <5; i++) {
arr.add(new Box(i, i*10));
}
return arr;
}
The data members are declared final because they're immutable, and so getters are pointless and setters just make no sense.
The class is declared final so you cannot subclass it.
In short, an immutable object is an object whose state cannot be modified after it's created. Your immutable Box object would look like this:
public final class Box {
private final int a;
private final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Notice that the variables a and b are assigned exactly once, during the construction of the Box instance. There are no setters, because Box's immutability means that its state (including variables a and b) will not change over its lifetime.
The final keyword in front of a and b means that you must assign them exactly once. It's actually considered good practice to make all your variables final unless you specifically need them not to be; but for an immutable object it's essential.
You were using the static keyword. Static has nothing to do with immutability. It means the variable is shared among all instances of the Box class. In my example, each Box instance has its own copies of a and b, because I didn't make them static.
To wrap this up, I'll give an example of your main class which has the desired output:
public class Check {
public static void main(String[] args) {
final List<Box> arr2 = getArray();
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray() {
final ArrayList<Box> arr = new ArrayList<>();
for (int i = 0; i < 5; i++) {
final Box box = new Box(i, i * 10);
arr.add(box);
}
return arr;
}
}
Note that a new instance of box is created at every iteration of the loop.

Averaging grades using objects in java

I'm trying to average 6 grades for two different people for school, I have all the grades for each student in different classes I was wondering
How can I import the numbers that I enter for each students object that I create?
//first class
public class GradesA {
int art;
int math;
int science;
int AddGrades(int a, int b, int c){
art = a;
math = b;
science = c;
return a+b+c;
}}
//second class
public class GradesB {
int english;
int carpentry;
int geography;
int AddGradesB(int a,int b,int c){
english = a;
carpentry = b;
geography = c;
return a+b+c;
}}
//final class
public class Classes {
public static void main(String[]args){
GradesA objGrades = new GradesA();
System.out.println(objGrades.AddGrades(100,85,95));
GradesB objGradesB = new GradesB();
System.out.println (objGradesB.AddGradesB(95,85,75));
}}
Hope I understood what you are looking for
Since
int addGrades(int a, int b, int c){
return and integer
why do not you just divide return number from this function by 3 and get your average that you are looking for.
If you want to have access to data fields art, math, and science values
you need getters and setters like follwing example for art data filed
setter function is
public void setArt(int art){
this.art = art;
}
getter function is
public int getArt(){
return this.art;
}
Read More About Setter and Getter

Multiple returns of different data types

I'm completely lost and getting desperate.
I'm working with Netbeans and what I'm trying to do is just have 2 or more variable of different types be sent to one class, be modified at that location, and then all be returned to the starting location along with the modifications they went under.
I can't put them into an array because in this instance I'm using an Integer and a Double and in the actual code I'm using a lot more than just 2 variables.
public class Passing_Objects {
public void main(String[] args) {
int a = 5;
double b = 10;
? = Extra.Carry(a, b);
System.out.println("A = " + a + ", B = " + b);
}
class Extra {
public int a;
public double b;
public Extra(int _a, double _b) {
this.a= _a;
this.b= _b;
return ?;
}
Either what I'm looking for can't be done or my feeble incompetent mind is too stupid to comprehend the solution everyone else is using.
Either way I can't make any progress in my code unless I solve this problem.
Could someone please help me understand what I need to do and would the solution be any different if variables A or B were arrays?
Something like this ?
public class Passing_Objects {
public void main(String[] args) {
int a = 5;
double b = 10;
Extra extra = new Extra(a, b);
System.out.println("A = " + extra.getA() + ", B = " + extra.getB());
}
class Extra {
public int a;
public double b;
public Extra(int a, double b) {
this.a= a;
this.b= b;
}
public int getA(){
return a;
}
public double getB(){
return b;
}
}
}
Edit :
To alter the values after a first initialization, you need setters.
Something like these two methods in your Extra class.
public void setA(int a){
this.a = a;
}
public void setB(double b){
this.b = b;
}
then in your Passing-Objects class, you can set new values by invoking the setter methods.
extra.setA(20);
extra.setB(20d);
Hope it helps.

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

Getting a function to return two integers

I am writing a function and I want it two return two integers as results. However, I cannot get it to do this. Could someone help me? Here is my best shot
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return s;
else if (s+b==g)
return s && b;
else if (s + c==g)
return s && c;
else if (s+d==g)
return s && d;
else
System.out.println("No Answer");
}
You could have the method return an array of int:
public static int[] calc (int s, int b, int c, int d, int g)
Make a "pair" class and return it.
public class Pair<T,Y>
{
public T first;
public Y second;
public Pair(T f, Y s)
{
first = f;
second = s;
}
}
Make a small inner class that has two integers.
private static class TwoNumbers {
private Integer a;
private Integer b;
private TwoNumbers(Integer a, Integer b) {
this.a = a;
this.b = b;
}
}
You create a instance of the class and return that instead.
For this specific problem, since the answer always returns s:
....
return s;
....
return s && b;
....
return s && c;
....
return s && d;
....
you could just return the 2nd value. I use 0 to indicate "just s" since the first case (if (s==g)) could be thought of as if (s+0==g). Use a different sentinel value than 0 for this, if necessary.
public static int calc (int s, int b, int c, int d, int g)
{
if (s==g)
return 0;
else if (s+b==g)
return b;
else if (s+c==g)
return c;
else if (s+d==g)
return d;
else {
// System.out.println("No Answer");
// Probably better to throw or return a sentinel value of
// some type rather than print to screen. Which way
// probably depends on whether "no answer" is a normal
// possible condition.
throw new IndexOutOfBoundsException("No Answer");
}
}
If no exception is thrown, then s is always the first result:
try {
int result1 = s;
int result2 = calc(s, b, c, d, g);
} catch (IndexOutOfBoundsException ex) {
System.out.println("No Answer");
}
package calcultor;
import java.util.*;
import java.util.Scanner;
public class Calcultor{
public static void main(String args[]){
input();
}
public static void input(){
Scanner FirstNum = new Scanner(System.in);
System.out.print("Enter the First number: ");
int num01 = FirstNum.nextInt();
Scanner secondNum = new Scanner(System.in);
System.out.print("Enter the second number: ");
int num02 = secondNum.nextInt();
output(num01, num02);
}
public static void output(int x ,int y){
int sum = x + y;
System.out.println("Sum of Two Number: "+sum);
//return sum;
}
}
why do you want to do this? and if you have some need like this can't you change your return type to string, because in case of string you can have separator between two values which will help you in extracting values.... say 10&30 ,
I agree this is a wrong way of solving...i assumed that there is limitation of sticking to primitive datatype

Categories