How to send variables from one class to another. - java

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

Related

Finding unique numbers

I am trying to use a set to find the unique numbers and get the sum from user entered numbers. I heard that arrays are easier but a set might just do for me. I don't know much about sets or what they do so any input would be fantastic. Much appreciated everybody!
import java.util.Scanner;
public class getdistinct
{
int dialr;
Scanner scan = new Scanner(System.in);
public double go()
{
double a = 0
counter = 10;
int total = 0;
for (counter != 0)
{
int thisisnewnumber = scan.nextInt();
System.out.println("Enter number that you want to add: ");
if(newInteger < 0)
{
n = n + 1
dial = dial - 1;
}
else
{
System.out.println("wrong");
}
}
System.out.println("the total is ";
return a;
}
}
java.util.HashSet stores unique values. Made minor changes to your program to use Set to store unique values and calculate sum of unique values using for loop
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class quiz_assignment {
int counter;
Scanner scan = new Scanner(System.in);
public int go() {
int a = 0;
int n = 0;
counter = 10;
Set<Integer> unValues = new HashSet<Integer>();
while (counter != 0) {
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if (newInteger < 0) {
unValues.add(new Integer(newInteger));
n += newInteger;
counter = counter - 1;
a = a + newInteger;
} else {
System.out
.println("Must be negative integer, please try again");
}
}
int unSum = 0;
for (Integer value : unValues) {
unSum += value;
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("The sum of unique integers is: " + unSum);
return n;
}
public static void main(String[] args) {
quiz_assignment o = new quiz_assignment();
o.go();
}
}
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality
I used here (HashSet).
import java.util.Scanner;
public class quiz_assignment
{
int counter;
Scanner scan = new Scanner(System.in);
Set<Integer> ditinctSet = new HashSet<Integer>();
public int go()
{
int a=0;
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(!ditinctSet.contains(newInteger)){
ditinctSet.add(newInteger);
}
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
a=a+newInteger;
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("Distinct numbers are: ");
System.out.println(ditinctSet);
return n;
}
}
And here a link to start knoing more about sets.
Hashsets are useful because they don't store duplicate entries. You can use them to store your set of unique numbers that the user inputs. I also removed the variable "a" from your code because its purpose seemed identical to variable n's.
import java.util.Scanner;
public class quiz_assignment{
int counter;
Scanner scan = new Scanner(System.in);
public int go()
{
HashSet<Integer> distinctNumbers = new HashSet<>();
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
distinctNumbers.add(newInteger);
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
int size = distinctNumbers.size();
System.out.println("The sum of all ten integers is: " + n);
System.out.println("You inputed " + size + " numbers.");
System.out.println("Your numbers are:");
for(Integer i: distinctNumbers){
System.out.println(i);
}
return n;
}
}

Using arrays for user input

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

How to fix my Array class

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.

RollingDice Java Program Longest Streak

Can someone help me figure out how to make this program display the longest streak. I'm rolling two dice, and recording the percent each dice sum. Now I need something that will tell me what dice sum came up in the longest streak for example "The longest run was a run of 8 7's that began at roll 1479966."
import java.util.Scanner;
import java.text.DecimalFormat;
public class RollThoseDice {
/* Author: Name
* Assignment: Third Program
*/
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int timesRolled, randomOutSum;
DecimalFormat df = new DecimalFormat ("#.###");
System.out.println("Name: "
+ "\nAssignment: Third Program"
+"\nExtra Credit: Percentage is displayed in three decimal places");
int[] d = new int[13];
for (int i = 2; i < 13; i++) d[i] = 0;
int N=0;
boolean againA = true;
while(againA) {
try{
System.out.print("\nHow Many Rolls? ");
N =kbd.nextInt();
againA = false;
} catch(Exception e) {
System.out.println("Invalid Input");
kbd.next();
}
}
for (int k = 0; k < N; k++) {
int diceOut1 = (int) (Math.random()*6+1);
int diceOut2 = (int) (Math.random()*6+1);
int diceSum = diceOut1 + diceOut2;
d[diceSum]++;
}
for (int i = 2; i < 13; i++)
System.out.println("Total " + i + " happened "
+ df.format((double) (d[(int) i] / (double) N) * 100)
+ "% of the time.");
}
}
The longest run was a run of 8 7's that began at roll 1479966.
So, what are the parameters in that output?
Looks like roll, run length or roll count, and roll number.
Hmm, what can keep multiple variables, so we can treat them as one thing?
I know, we'll create a model class.
public class RollStreak {
private final NumberFormat NF = NumberFormat.getInstance();
private int roll;
private int rollCount;
private long rollNumber;
public RollStreak(int roll, long rollNumber, int rollCount) {
this.roll = roll;
this.rollNumber = rollNumber;
this.rollCount = rollCount;
}
public int getRoll() {
return roll;
}
public int getRollCount() {
return rollCount;
}
public long getRollNumber() {
return rollNumber;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("The computer rolled a ");
builder.append(roll);
builder.append(" ");
builder.append(rollCount);
builder.append(" times in a row starting at roll number ");
builder.append(NF.format(rollNumber));
builder.append(".");
return builder.toString();
}
}
A model class allows you to treat a group of fields as one object.
I don't want to give away the whole answer. You still have to determine how to create these model class instances and get the longest streaks. Hint: There can be more than one longest streak.

How can I fix this "OutOfBoundaryException" error?

import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
int students;
int rank[];
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Type in number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Type name");
name[i] = sc.next();
System.out.println("Type Korean score");
korean[i] = sc.nextInt();
System.out.println("Type math score");
math[i] = sc.nextInt();
System.out.println("Type English score");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3.0;
}
}
int stu() {
return students;
}
int[] sum() {
return sum;
}
}
class DataOutput {
DataInput data = new DataInput();
int sNum;
int[] rrank, sum;
DataOutput(int students, int[] sum) {
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
void ranker() {
int cnt = 1;
for (int i = 0; i < sNum; i++) {
for (int j = 0; j < sNum; j++) {
if (sum[i] < sum[j]) {
cnt++;
}
}
rrank[i] = cnt;
cnt = 1;
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean math English \t sum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.stu(); i++) {
System.out.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rrank[i]); // this is where i get an Exception
}
}
}
So, this is my program for getting ranks of students. But somehow when I run the code, I keep getting "OutOfBoundaryException". I checked my code, and realized that when I instantiate a new instance of DataOutput, it creates all new data. So I tried to fix this by setting a constructor. However I still can't solve this matter. I know that I can put the ranker method into DataInput class, and problem will be easily solved however I really want to keep DataOutput class.
Thank you for your time.
PS: Exception is thrown on line 98, out.rrank[i]
Your students field isn't set until the save() method is called. The value of sNum in main is then 0.
Change the order in main to:
DataInput data = new DataInput();
data.save();// <--
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
out.ranker();
the problem was that you initialize the rank[] before creating students, As soultion I suggest you to initialize after collection students/scores
public void init(int students, int[] sum){
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
And update main()
DataOutput out = new DataOutput();
data.save();
int sNum = data.stu();
int[] sum = data.sum();
out.init(sNum, sum);
out.ranker();

Categories

Resources