Intro to java programming
Using classes
As briefly introduced in part 1. Classes can be used to hold different methods used throughout a program. For example, the main
method we create to run every program. We have also encountered this in the form of the Scanner
class we use for user input. But what if we wanted to make our own. Start by creating a class like we did for our main program however don’t include the main method. Instead, we’ll create our own:
public class newClass {
public void message() {
System.out.println("I'm printing from class 2");
}
}
We can’t run this class alone, we need to use this from within our main class:
public class Main {
public static void main(String[] args) {
newClass messenger = new newClass();
messenger.message();
}
}
Methods with arguements
When we use methods, we often want to be able to pass data between them. We can build off of our previous example. What if we wanted to print a user’s name after reading it? We can do that by adding arguments:
public class newClass {
public void message(String name) {
System.out.println("Hello " + name);
}
}
In order for our message method to work, we need to pass a string which is then stored in a variable called name
. We can take multiple arguments by separating values by commands. Now, when we call this method, we need to pass a name:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter your name \n");
String name = userInput.nextLine();
newClass messenger = new newClass();
messenger.message(name);
}
}
Multiple methods and constructors
A single class can have many methods, for example. If I also wanted to be able to print an age, we can add a method and display an age:
public class newClass {
public void message(String name) {
System.out.println("Hello " + name);
}
public void printAge(int age) {
System.out.printf("You are %d \n", age);
}
}
Instead of passing the arguments to the specific functions, we can create a constructor and pass them both together:
public class newClass {
private String name;
private int age;
public newClass(String inputName, int inputAge) {
name = inputName;
age = inputAge;
}
public void message() {
System.out.println("Hello " + name);
}
public void printAge() {
System.out.printf("You are %d \n", age);
}
}
A few things to note, private variables are initialized and can only be used within the newClass
class. Our constructor is also given the same name as the class and doesn’t have a return type as this isn’t intended to return a value. If we want to now call this, we can use:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter your name\n");
String name = userInput.nextLine();
System.out.println("Please enter your age\n");
int age = userInput.nextInt();
newClass messenger = new newClass(name, age);
messenger.message();
messenger.printAge();
}
}
We take both inputs and pass them both when we initialize the class, these are then stored in the private variables we defined within newClass
and can be used when the methods are called
First program: Averages
We’re going to create a program using all the information we’ve learned so far. I created a new java project but you can re-use what we’ve already created. We’ll start with the main part of our program, we need to take user input so as usual, we’ll import the scanner class from the java standard library.
package averageCalculator;
import java.util.Arrays;
public class averageCalc {
private int total;
private int values[];
private float average;
public averageCalc(String userValues) {
values = Arrays.stream(userValues.split(",")).mapToInt(Integer::parseInt).toArray();
}
public float getAverage() {
int valueLen = values.length;
total = 0;
for(int i = 0; i < valueLen; i ++) {
total += values[i];
}
average = total/(float)valueLen;
return average;
}
}
A quick run down of this class. We want to create a constructor to parse user input and convert it into a valid array of integers. Java comes with a built in method for that, we can simply import and use it. We also need to calculate the average. Since averages are often decimal values, we want to create a method that returns a float value. Another issue we come across is that to add each value in the number array to get a total, we need to cycle through the values.
This is typically done with a for
loop however we don’t have a predefined length, we can obtain this by adding .length
to the end of an array. Now to create the main function:
package averageCalculator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter a comma seperated list of values: ");
String values = userInput.nextLine();
values = values.replaceAll("\\s", "");
averageCalc calc = new averageCalc(values);
float average = calc.getAverage();
System.out.printf("The average of your values is: %f", average);
}
}
After taking user input, we need to remove all spaces between the numbers and the comma due to parsing issues found in the Array.stream
method we call onto in the average calculator. We then create an instance of the averageCalc
class, passing our values to the constructor then calculating the average using calc.getAverage()