I've looked around for answers for this but I cannot find it. My professor requires me to use an array.. not an arraylist
public static void main(String[] args) {
final int total = 30;
String[] animalType = new String[total];
Scanner input = new Scanner(System.in);
for (int x = 0; x < total; x++) {
System.out.println("Enter the type of animal " + x + 1);
animalType[x] = input.next();
for (int x1 = 0; x1 < total; x1++) {
System.out.println("Enter the weight of the animal " + (x1 + 1));
animalType[x1] = input.next();
}
input.close();
System.out.println("Your friends are");
for (int counter = 0; counter < total; counter++) {
System.out.println(animalType[counter] + "\n" + animalType[counter]);
}
}
}
The prompt is.. allow user to enter the type of the animal and the weight of the animal and then output the average weight by animal type.
I'm new to java and do not know how to use arrays properly.
I think you should create a class for this purpose.
First, create another file called Animal.java and write a class that stores a type and a weight:
public class Animal {
public String type;
public int weight;
}
Of course, it would be better if you add getters and setters, but that would be too hard for you I think. I'll show the code anyways, but I won't use it in the example below.
public class Animal {
private String type;
private int weight;
public String getType() {return type;}
public void setType(String value) {type = value;}
public int getWeight() {return weight;}
public void setWeight(int value) {weight = value;}
}
Now you have this class, you can create an array of it.
Animal[] animals = new Animal[total];
And you need to fill the array in with animals!
for (int i = 0 ; i < total ; i++) {
animals[i] = new Animal();
}
Actually, your for-loops are wrong. If you want to ask the user for the type first, then the weight, you should do it like this:
for (int x = 0; x < total; x++) {
System.out.println("Enter the type of animal " + x + 1);
animals[x].type = input.next();
}
for (int x1 = 0; x1 < total; x1++) {
System.out.println("Enter the weight of the animal " + (x1 + 1));
animals[x1].weight = Integer.parseInt(input.next());
}
Now you got the types and weights of the animals, hooray!
You need a second array to store the weight(s). Something like
String[] animalWeight = new String[total];
for(int x1 = 0; x1 < total; x1++){
System.out.println("Enter the weight of the animal "+(x1+1));
animalWeight[x1] = input.next();
}
Next, you print the values from your two arrays. And I would prefer calling println twice to embedding a \n (on some systems that can also cause issues, because they use other line termination characters such as \r\n). That might look something like,
// input.close(); // <-- Also closes System.in, can cause subtle bugs.
System.out.println("Your friends are");
for(int counter = 0; counter < total; counter++){
System.out.println(animalType[counter]);
System.out.println(animalWeight[counter]);
}
Related
I have the code below:
package Main; import java.util.*;
public class Generator {
List <List<String>>masterList = new ArrayList<List<String>>();
ArrayList memberList = new ArrayList<String>();
String leaderName, memberName;
int numLeaders, numMembers;
double x;
Scanner scanner = new Scanner(System.in);
// This program takes in total number of people first
// Then takes in number of leaders to assign peoples to
// Then takes in people to be assigned
// And then assigns people to given leaders randomly
public int getNumLeader() {
System.out.println("How many leaders are there??");
numLeaders = scanner.nextInt();
return numLeaders;
}
public void setNumLeader(int numLeaders) {
this.numLeaders = numLeaders;
}
public int getNumMembers() {
System.out.println("How many members are there?");
numMembers = scanner.nextInt();
return numMembers;
}
public void setNumMembers(int numMembers) {
this.numMembers = numMembers;
}
public void genLeaders() {
System.out.println("Please type the name of the leader on the following:");
for (int i = 1; i <= numLeaders; i++) {
if (i == numLeaders) {
System.out.println("What is the last leader's name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
} else {
System.out.println("What is the leader" + i + "'s name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
}
}
}
public void genMembers() {
System.out.println("Please enter the members on the following:");
for (int i = 1; i <= numMembers; i++) {
if (i == numMembers) {
System.out.println("What is the last member's name?");
memberName = scanner.next();
memberList.add(memberName);
} else {
System.out.println("What is the member" + i + "'s name?");
memberName = scanner.next();
memberList.add(memberName);
}
}
}
public void /*should return arraylist*/ brackets() {
double y = 1.0/numLeaders;
for (double j = 0.0; j <= 1.0; y++) {
//Generate Linked list with initial element of 0.0
//then 0.0 + y, then 0.0 + y + y ... till 1.0
}
}
public void assignMembers() {
System.out.println("Shuffling members..");
Collections.shuffle(memberList);
System.out.println("Assigning members to leaders now..");
int cellSize = memberList.size()/numLeaders;
for (int i = 0; i <= memberList.size(); i++) {
double x = Math.random();
double y = 1.0/numLeaders;
if (x <= y) {
masterList.get(0).add((String) memberList.get(i));
}
else if (y < x && x <= y + y) {
masterList.get(1).add((String) memberList.get(i));
}
else if (y < x && y + y < x && x <= y + y + y) {
masterList.get(2).add((String) memberList.get(i));
}
// assign given element's name from the big linkedList to the first leader's
// arrayList
}
}
public static void main(String[] args) {
Generator x = new Generator();
x.getNumLeader();
x.getNumMembers();
x.genLeaders();
x.genMembers();
System.out.println(x.memberList);
System.out.println(x.masterList);
System.out.println(x.masterList.get(0));
System.out.println(x.masterList.get(1));
System.out.println(x.masterList.get(2));
}
}
And I made lists within an arraylist, called masterList. I try to assign people in a list within that arraylist, in this manner: masterList.get(0).add((String) memberList.get(i)); Nothing's being added to the list within the arrayList.. what would be the 'correct' way to do this, and is there a way to pinpoint the list within the arraylist, other than 'masterList.get(0)'? Thanks in advance.
You are calling 4 methods, 2 to get numbers of leader and member, and another 2 to generate them. In your generateLeader method, you read name from console but never used it within this method. You are just adding emptylist to master list in this method. The other method generateMembers looks fine as you are adding this in the expected list. I dont see anywhere else that main method calls to populate the emptylist inside the masterlist you added in generateLeaders method.
Also, use nextln to read input, there are scenarios where the linebreak character will still be in buffer when you use just "next" and that linebreak will be read read as next input.
I am trying to figure out how to get my array to run correctly, I know I have to change the array value to an input but I cannot get the program to compile if any one can help that be great.
I am trying to have the program take input for grades and names of students and in the end output their name and grade.
Edit sorry this is my first it posting i have an error
Student.java:60: error: class, interface, or enum expected I am in java 101 so this is why it is such low level java, we only know the basics
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
and my second class is
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
} <--- error here
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
Add return statement in your multiplegradeinputs() method:
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
return null; //Add this line
}
Or change your methods to void return type if they dont return anything.
Class names have to be capitalized in java, so instead of
public class students
you should write
public class Students
Also instead of writing
keyboard.nextInt();
You should write
Integer.parseInt(keyboard.nextLine());
This is mainly because java is full of bugs and technical specifications that you won't find easily. Let me know if this fixes it for you, since you didn't post the exact error message you got.
As for the error that you pointed out, it's because your function expects a String as a return value no matter what, so either change that to void if you can or return a null string. To do that just add the following line at the very end of the method.
return null;
You should create a Student object which holds the properties of the student, e.g. Name and Grades. You should then store all the student objects in some kind of data structure such as an array list in the students class.
Adding to the answer provided by #hitz
You have a bug in the for loops:
for(int i = 1; i <multiplegradeinputs.length; i++)
for(int i = 1; i < multipleStudent.length; i++)
You will never populated multiplegradeinputs[0] and multipleStudent[0] because you start the loop at index == 1 and thus you will have only 9 student names stored instead of 10.
Change to:
for(int i = 0; i <multiplegradeinputs.length; i++)
for(int i = 0; i < multipleStudent.length; i++)
Remember even though the length in 10, the indices always start with 0 in Java and in your case will end with 9.
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public void multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
}
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
this is the 2nd class
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
You are missing a return value in the multiplegradeinputs() method.
I am practicing sorting of arrays, and I have successfully sorted a string array.
My little program allows users to enter first number of students, then the name of each one, and at last their grade of each one.
But I also want to sort the int studentGrade array so that the grades in the printout matches the student. Here I am really stuck. See further down for more explanation down in the method: public void sortingAlgorithm
package assignment8exam;
import java.util.Scanner;
import java.util.Arrays;
/**
*
* #author Anders
*/
public class Course {
Scanner sc = new Scanner(System.in);
public void MainMenu() {
System.out.println("Enter data about a student, start by entering how many");
int numbers = sc.nextInt();// amount of student
String studentNames[] = new String[numbers];
int studentGrade[] = new int[numbers];
for (int i = 0; i < numbers; i++) {
System.out.println("Enter name of student");
Scanner name = new Scanner(System.in);
String names = name.nextLine();
studentNames[i] = names;
}
for (int j = 0; j < numbers; j++) {
System.out.println("Enter grade of student");
Scanner gradeSc = new Scanner(System.in);
int grade = gradeSc.nextInt();
studentGrade[j] = grade;
}
sortingArray(studentNames);
System.out.println("------------------------------------\n");
sortAlgorithm(studentNames, studentGrade);
System.out.println("What do you want");
System.out.println("Exit application 1");
System.out.println("Print out all names of the students 2");
System.out.println("Print out all the grades of the students 3");
System.out.println("Print out pairs consisting of “namegrade 4");
System.out.println("Search for a student - 5");
Scanner choice = new Scanner(System.in);
int order = choice.nextInt();
switch (order) {
case 1:
System.exit(1);
case 2:
PrintOutNames(numbers, studentNames);
case 3:
PrintOutGrades(numbers, studentGrade);
case 4:
PrintOutAll(numbers, studentGrade, studentNames);
case 5:
search(numbers, studentGrade, studentNames);
}
}
public static void PrintOutNames(int numbers, String studentNames[]) {
for (int i = 0; i < numbers; i++) {
System.out.println(studentNames[i]);
}
}
public static void PrintOutGrades(int numbers, int studentGrade[]) {
for (int i = 0; i < numbers; i++) {
System.out.println(studentGrade[i]);
}
}
public static void PrintOutAll(int numbers, int studentGrade[], String studentNames[]) {
System.out.println("--------------------------------------------------------\n");
for (int i = 0; i < numbers; i++) {
System.out.println("Name----> " + studentNames[i] + " grade ---> " + studentGrade[i]);
}
}
public static void search(int numbers, int studentGrade[], String studentNames[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name on student you want to search on ");
String search = sc.nextLine();
for (int i = 0; i < numbers; i++) {
if (search.equals(studentNames[i])) {
System.out.println("Yes we have a student named " + studentNames[i] + " with the Grade " + studentGrade[i] + " \n ");
}
}
}
public static void sortingArray(String studentNames[]) {
Arrays.sort(studentNames);
System.out.println("-------------\n" + Arrays.toString(studentNames));
}
public static void sortAlgorithm(String studentNames[], int studentGrade[]) {
boolean flag = true;
while (flag) {
flag = false;
for (int j = 0; j < studentNames.length - 1; j++) {
for (int i = j + 1; i < studentNames.length; i++) {
if (studentNames[i].compareTo(studentNames[j]) < 0) {
String temp = studentNames[j];
studentNames[j] = studentNames[i];
studentNames[i] = temp;
// Here i want to place another array that sorts the grade?? how do i do that?
}
}
System.out.println(Arrays.toString(studentNames));
System.out.println(Arrays.toString(studentGrade));
}
}
}
}
The problem with your approach is that there is no relation between a student name and grade. If you sort the names and sort the grades you will end up with students with letter A having the least grades.
If that's a java assignment the best way to do it would be to create a data structure (class) called Student that has name and grade.
class Student{
String name;
int grade;
}
Then you will not have two arrays one with names and other with grades but just one array of Students and you will be able to sort that array by grades,names etc.
If you want a quicker solution that would be to use a map like Map<String,Integer> that will contain the grade for each student.
If you want to use multiple array you can make the sortAlgorithm method to swap the same indexes in both arrays (not only in the names array) and this way you will end up with grades sorted by names. This is the worst approach IMO because you depend too much on the array indexes instead of having some relation between the objects.
In this particular case, the solution is relatively easy. In this place, where you exchange the two student names:
for (int i = j + 1; i < studentNames.length; i++) {
if (studentNames[i].compareTo(studentNames[j]) < 0) {
String temp = studentNames[j];
studentNames[j] = studentNames[i];
studentNames[i] = temp;
}
}
You also exchange the corresponding grades at the same time:
for (int i = j + 1; i < studentNames.length; i++) {
if (studentNames[i].compareTo(studentNames[j]) < 0) {
String temp = studentNames[j];
studentNames[j] = studentNames[i];
studentNames[i] = temp;
int tempGrade = studentGrades[j];
studentGrades[j] = studentGrades[i];
studentGrades[i] = tempGrade;
}
}
So, whenever you do a switch of two student names, you switch the corresponding grades at the same time. This will keep the two arrays synchronized.
But as everybody else has been recommending, the better way is to create a class that represents a student - both name and grade. Why? Because in a real world case, a student may have other data, such as different subjects and their matching grades, an attendance record, contact information, whatever the university needs.
And having to add that to the loop for each such data item will make it intractable. If you have all the information in one record, you can just exchange record references, and then the whole data is exchanged together.
The basis for this is a class like:
class Student implements Comparable<Student> {
private String name;
private int grade = 0;
public Student( String name ) {
this.name = name;
}
public void setGrade( int grade ) {
this.grade = grade;
}
// In addition, you'll have getName(), getGrade(),
// and possibly a good `toString()` for printing a
// student record.
#Override
public int compareTo( Student otherStudent ) {
return this.name.compareTo( otherStudent.name );
}
}
Now you can define an array such as:
Student[] students = new Students[numbers];
And you can sort it directly with Arrays.sort() because Student implements Comparable, or you can do your own sorting algorithm and use the compareTo method. Your loop would be:
for (int i = j + 1; i < students.length; i++) {
if (students[i].compareTo(students[j]) < 0) {
Student temp = students[j];
students[j] = students[i];
students[i] = temp;
}
}
As noted above, the "correct" solution is probably to create a Student object and have it contain the student's name and grade. However, if you really need to have two separate arrays, you could just perform the same swapping on on the grade array that you do on the name array:
if (studentNames[i].compareTo(studentNames[j]) < 0) {
String temp = studentNames[j];
studentNames[j] = studentNames[i];
studentNames[i] = temp;
int tempGrade = studentGrade[i];
studentGrade[j] = studentGrade[i];
studentGrade[i] = tempGrade;
}
What you want to do, is Sort the grade array according to the student array i think, so in you for loop, everytime you switch a student, you want to switch the grade
for (int j = 0; j < studentNames.length - 1; j++) {
for (int i = j + 1; i < studentNames.length; i++) {
if (studentNames[i].compareTo(studentNames[j]) < 0) {
String temp = studentNames[j];
studentNames[j] = studentNames[i];
studentNames[i] = temp;
// Here i want to place another array that sorts the grade?? how do i do that?
int tempGrade = studentGrades[j];
studentGrades[j] = studentGrades[i]
studentGrades[i] = temp
}
}
System.out.println(Arrays.toString(studentNames));
System.out.println(Arrays.toString(studentGrade));
}
this design isn't that good, maybe take the advice from #Veselin Davidov in account
Your problem is that when you sort one array (say your student name list), your second array cant keep up with the same way.... apples and oranges.
You have somes solutions. The one that comes in mind right now is to use a map linking each name to its grade. You could also, well, use POO and declare a Studen object, that actually would look like a nicer solution, i'll let you read on Veselin's answer for that.
Let's look at the quickfix though, since i think that's why you're looking for :
Personally one workaround to your kinda-broken code would be to change your swap function to this :
if (studentNames[i].compareTo(studentNames[j]) < 0) {
String tmp = studentNames[j];
studentNames[j] = studentNames[i];
studentNames[i] = tmp;
int tmpGrade = studentGrade[i];
studentGrade[j] = studentGrade[i];
studentGrade[i] = tmpGrade;
}
But, i strongly recommend using either classes or a map.
You should really have an abstraction representing a Student, e.g.
public class Student {
Integer grade;
String name;
// getters and setters omitted
}
Then, you'll face the problem of extending the Comparator interface multiple times with different types (Integer and String). At this point, read this :
Using Comparable for multiple dynamic fields of VO in java
import java.util.Scanner;
import java.util.Arrays;
class StudentScores {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the # of students");
int numOfStudents = input.nextInt();
int[] scores = new int[numOfStudents];
String[] names = new String[numOfStudents];
for (int i = 0; i < numOfStudents; i++) {
input.nextLine();
System.out.print("Enter name: ");
names[i] = input.nextLine();
System.out.print("Enter score: ");
scores[i] = input.nextInt();
}
// This doesn't sort anything, it just prints out the result in unsorted way
/*for (int i = 0; i < numOfStudents; i++) {
System.out.println(names[i] + " " + scores[i]);
}*/
Arrays.sort(scores);
reverse(scores);
for (int u: scores) {
System.out.println(u);
}
}
public static int[] reverse(int[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
}
The original question is:
Write a program that prompts the user to enter the number of students, the students’ names, and their scores, and prints student names in decreasing order of their scores.
My question is how do you display the name with the sorted list of scores?
You necessarily don't have to give me a complete solution, just give me a hint so I can solve it myself.
You can encapsulate the related fields into a class, e.g. a StudentRecord can encapsulate the fields name and score.
Now, you sort a collection of these objects based on the second field, score. When it comes time to print the sorted result, you iterate through the collection and print the first field, name.
To illustrate:
public class StudentRecord implements Comparable<StudentRecord> {
private String name;
private int score;
public StudentRecord(String name, int score) {
this.name = name;
this.score = score;
}
#Override
public int compareTo(StudentRecord other) {
if (score == other.score) return 0;
else if (score < other.score) return -1;
else return 1;
}
#Override
public String toString() {
return name;
}
public static void main(String[] args) {
StudentRecord stu1 = new StudentRecord("Matt", 50);
StudentRecord stu2 = new StudentRecord("John", 90);
if (stu1.compareTo(stu2) == 0) {
System.out.println(stu1.toString() + " has the same score with " + stu2.toString());
}
else if (stu1.compareTo(stu2) < 0) {
System.out.println(stu1.toString() + " has a lower score than " + stu2.toString());
}
else {
System.out.println(stu1.toString() + " has a higher score than " + stu2.toString());
}
// output:
// Matt has a lower score than John
}
}
In many sorting algorithms, implementing the Comparable interface gives the algorithm enough information to sort a collection of such objects implementing said interface.
You're not going to be able to use Arrays.sort() for this problem because you need to sort both arrays together. Write a sorting function that sorts the scores in order, and every time it swaps two scores, swap the students with those scores as well.
Hopefully it's not too late for someone to help me out. I'm trying to create a program that has one class (TestCode) that asks the user to enter 4 integers. Then, I send the variables from that class to another class (MySmartDataType). Then, I use those integers to perform certain calculations. The problem is, I'm not sure how to get the second program to accept those integers properly. Here is the first class.
import java.util.*;
class TestCode{
public static void main(String args[]){
int n1 = 0;
int n2 = 0;
int n3 = 0;
int n4 = 0;
String repeat = "Y";
int evenTotal = 0;
int oddTotal = 0;
MySmartDataType msdt;
Scanner sc;
sc = new Scanner(System.in);
while (repeat == "Y"){
System.out.println("Enter number 1 ");
n1 = sc.nextInt();
System.out.println("Enter number 2 ");
n2 = sc.nextInt();
System.out.println("Enter number 3 ");
n3 = sc.nextInt();
System.out.println("Enter number 4 ");
n4 = sc.nextInt();
System.out.println("Would you like to continue? N for no and Y for Yes.");
repeat = sc.nextLine();
msdt = new MySmartDataType(n1,n2,n3,n4);
}
evenTotal = msdt.getEvenTotal();
System.out.println("Even total is: " + evenTotal);
oddTotal= msdt.getOddTotal();
System.out.println("Odd total is: " + oddTotal);
System.out.println("Grand Total is: " + msdt.getTotal() );
}
}
And here's the second one:
import java.util.*;
class MySmartDataType {
private int myArray[] = new int [4];
myArray[4] = {n1, n2, n3, n4};
int getEvenTotal(){
int sumEven = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 2 == 0){
sumEven += myArray[i];
}
}
System.out.println("The even total is: " + sumEven);
return sumEven;
}
int getOddTotal(){
int sumOdd = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 3 == 0){
sumOdd += myArray[i];
}
}
System.out.println("The odd total is: " + sumOdd);
return sumOdd;
}
int getTotal(){
int sumTotal;
for (int i = 0; i <= 3; i++){
sumTotal += myArray[i];
}
System.out.println("The total is: " +sumTotal);
return sumTotal;
}
}
Do a setter and getter method in order to get the variable to the other class.
Here is a tutorial on how to do it:
YOUTUBE link
declare the variables globally then create getter, setter for the declared variables. So you can get the variable's value in any other class you want by getter method.
Using public static modifier.
Example: public static int example, now you can using example in other class.
Add the following in your MySmartDataType class. Create 4 instance variables in your MySmartDataType which can hold the data being sent from other class.(eg: int var1...)
MySmartDataType(int num1,int num2,int num3,int num4)
{
var1 = num1;
var2 = num2;
var3 = num3;
var4 = num4;
}
Use var1...var4 in the methods to do the operations. You can replace var1...var4 with array, but then you need to loop every time to read the values and to do the opr's(which is not a bad option and up to you).
You missed the constructor in MySmartDataType class. This constructor will be called when you create the object of this class in your first class; i.e.
msdt = new MySmartDataType(n1,n2,n3,n4);
the following doesn't make sense, remove it
myArray[4] = {n1, n2, n3, n4};
The constructor in MySmartDataType class will set the values to the array;
public MySmartDataType (int n1, int n2, int n3, int n4) {
//this constructor will be called when the object of this class will be created with 4 integer parameters
myArray[0] = n1;
myArray[1] = n2;
myArray[2] = n3;
myArray[3] = n4;
}
I guess now you're learning OOP, right?
you can create some method with one or more parameters to fill your second class attributes.
for example :
function setData(int data, int pos){ myArray[pos] = data;}
and you can call that method from your first class
msdt.setData(something, 0);
Try this one:
import java.util.*;
class MySmartDataType {
private int myArray[] = new int [4];
public MySmartDataType(int n1, int n2, int n3, int n4) {
myArray[0] = n1;
myArray[1] = n2;
myArray[2] = n3;
myArray[3] = n4;
}
int getEvenTotal(){
int sumEven = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 2 == 0){
sumEven += myArray[i];
}
}
System.out.println("The even total is: " + sumEven);
return sumEven;
}
int getOddTotal(){
int sumOdd = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 3 == 0){
sumOdd += myArray[i];
}
}
System.out.println("The odd total is: " + sumOdd);
return sumOdd;
}
int getTotal(){
int sumTotal = 0;
for (int i = 0; i <= 3; i++){
sumTotal += myArray[i];
}
System.out.println("The total is: " +sumTotal);
return sumTotal;
}
}
Add following constructor to the MySmartDataType class.
public MySmartDataType(int n1, int n2, int n3, int n4)
{
myArray = new int[]{n1, n2, n3, n4};
}
http://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html
package greetings;
import javax.inject.Inject;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
#Named
#RequestScoped
public class Printer {
#Inject #Informal Greeting greeting;
private String name;
private String salutation;
public void createSalutation() {
this.salutation = greeting.greet(name);
}
public String getSalutation() {
return salutation;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Setters set a variable to your input parameters. Getters return the instance variable that one is "getting". For example,
Printer myobject = new Printer();
//sets instance variable 'name' to "Hello World"
myobject.setName("Hello World");
//gets instance variable 'name' with getter and sets it to mystring
String mystring = myobject.getName();
//will print "Hello World"
System.out.println(mystring);