What is wrong with my main method? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am a java noob. I keep getting errors in the main method. Please help! I think I'm not calling the methods the right way. Everything else should be working.
import java.util.Scanner;
public class Assignment5 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
inputName(kbd);
inputIncome(kbd);
inputMarried(kbd);
calculateThreshold();
incomeBelowThreshold();
incomeAboveThreshold();
taxBelowThreshold();
taxAboveThreshold();
totalTaxes();
displayResults();
}
public static String inputName (Scanner kbd) {
System.out.print("What is your name?");
String name = kbd.nextLine();
return name;
}
public static double inputIncome (Scanner kbd) {
System.out.print("What is your annual income?");
double userIncome = kbd.nextDouble();
return userIncome;
}
public static char inputMarried (Scanner kbd) {
System.out.print("Are you married? (y for yes, n for no)");
char married = kbd.next().charAt(0);
return married;
}
public static double calculateThreshold (char married) {
double incomeThreshold;
if (married == 'y') {
incomeThreshold = 80000;
} else {
incomeThreshold = 40000;
}
return incomeThreshold;
}
public static double incomeBelowThreshold (double userIncome , double incomeThreshold) {
double incomeBelowThreshold;
if (userIncome <= incomeThreshold) {
incomeBelowThreshold = incomeThreshold - userIncome;
} else {
incomeBelowThreshold = userIncome;
}
return incomeBelowThreshold;
}
public static double incomeAboveThreshold (double userIncome, double incomeThreshold) {
double incomeAboveThreshold;
if (userIncome >= incomeThreshold) {
incomeAboveThreshold = incomeThreshold - userIncome;
} else {
incomeAboveThreshold = 0;
}
return incomeAboveThreshold;
}
public static double taxBelowThreshold (double incomeBelowThreshold) {
double taxBelowThreshold;
taxBelowThreshold = incomeBelowThreshold * .25;
return taxBelowThreshold;
}
public static double taxAboveThreshold (double incomeAboveThreshold) {
double taxAboveThreshold;
taxAboveThreshold = incomeAboveThreshold *.35;
return taxAboveThreshold;
}
public static double totalTaxes (double taxBelowThreshold, double taxAboveThreshold) {
double totalTaxes;
totalTaxes = taxBelowThreshold + taxAboveThreshold;
return totalTaxes;
}
public static void displayResults (String Name, char married, double income, double totalTaxes) {
System.out.print("Name:" + Name);
String marriedStatus;
if (married == 'y') {
marriedStatus = "Married";
} else {
marriedStatus = "Single";
}
System.out.print("Marital Status:" + marriedStatus);
System.out.printf("Income: %.2f" + income);
System.out.printf("Taxes: %.2f" + totalTaxes);
}
}

It looks like some of your methods are expecting arguments and you are not providing them.
For example
public static double calculateThreshold (char married){}
you cannot call this method calculateThreshold();
You need to pass in the char for married
calculateThreshold ('y');

THANK YOU!!!!!!
calculate threshold(char) in the type Assignment 5 is not applicable for the arguments ()
In the future, please ALWAYS post as much information about the actual error as possible. Don't make everybody guess :)
In this case:
1) Save the return value of "married":
public static void main(String[] args) {
...
char married = inputMarried(kbd);
2) Then pass it to "calculateThreshold()". Save the return value of "threshold() while you're at it:
...
double threshold = calculateThreshold (married);
3) Be sure to do the same for the rest of your program.

One error is that you have methods that require a parameter, but you are not passing one. calculateThreshold(), for instance, takes one parameter, and incomeBelowThreshold() takes two. You are also not returning values from your input routines; this is not an error, but may be flagged as a warning (depending on how you're editing and compiling your stuff), but you're going to need the values from your input routines to pass to your other routines, possibly converting them beforehand.

Actually all your methods return some answers in which it is suppose to deliver to the next method or so...
Your mistake is you are not assigning the returned values to a variable..so please correct it

public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
inputName(kbd);
inputIncome(kbd);
inputMarried(kbd);
// modify this line calculateThreshold();
calculateThreshold('a');
// modify this line incomeBelowThreshold();
incomeBelowThreshold(2.1, 2.2);
// modify this line incomeAboveThreshold();
incomeAboveThreshold(2.1, 2.2);
// modify this line taxBelowThreshold();
taxBelowThreshold(2.1);
// modify this line taxAboveThreshold();
taxAboveThreshold(2.1);
// modify this line totalTaxes();
totalTaxes(2.1, 2.1);
// modify this line displayResults();
displayResults("",'a', 2.1, 2.1);
}

Related

Create a simple math game using java objects

I am trying to create a Simple math game using Java objects. My goal is to create a question class, which contains a method to show a question with random numbers, a method to check the answer, a question constructure.
How can I generate 10 random questions using these objects? With additions, substraction and multiplication questions. And print the how many correct answers, at the end.
I have created my question class and my first method shows a random question using the variables "a" and "b". and store the answer.
My second method check the answer with the user input and print the result. So far when I run my program it only shows the same question over and over again.
This is my Question class
import java.util.*;
public class Question {
private int a;
private int b;
private String Question;
private int correct;
Random rand = new Random();
Scanner input = new Scanner(System.in);
int count = 0;
Question(int c, int d) {
x = rand.nextInt(20);
y = rand.nextInt(20);
}
public void askQuestion() {
if (a > b) {
System.out.println("What is " + a + " - " + b + " ?\n");
correct = a - b;
} else {
System.out.println("What is " + a + " + " + b + " ?\n");
correct = a + b;
}
}
public void Check() {
int response = Integer.parseInt(input.next());
if (response == correct) {
System.out.printf("yes.\n");
count++;
} else {
System.out.printf("No. It is " + correct + ".\n");
}
}
}
my main method looks like this
public class Main {
public static void main(String[] args) {
Question q1 = new Question(1,2);
for (int i = 1; i < 10; i++) {
q1.askQuestion();
q1.check();
}
}
}
In my output it shows the question with two random numbers but it prints the same question over and over again. EX:
What is 13 - 1 ?
12
That is correct.
What is 13 - 1 ?
12
That is correct.
What is 13 - 1 ?
3
Wrong!. The answer is 12.
What is 13 - 1 ?
Eventually I want my output to look like:
What is 4 + 6?
What is 7 - 3?
Any help to fix this? and make this game more interactive? Appreciate it.
Your problem is due to the fact that you are creating one Question object, that generates two random numbers (13 and 1 in your case). You then go through a loop of asking 10 Questions, but you use the same Question object - so you are using the same random numbers every time. To fix this, do the following changes:
In your Question constructor, get rid of the parameters, you do not need them. Assign to variables a and b:
private Question(){
a = rand.nextInt(20);
b = rand.nextInt(20);
}
So every time you create a Question, you will generate two random numbers which you assign to your variables you declared earlier in the code at the top (in your code, a and b are declared, but not used).
Then in your main, change it to the following:
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
Question q1 = new Question();
q1.askQuestion();
q1.check();
}
System.out.println("Number correct: " + count); //print amount correct, to use this make variable "count" static.
}
The changes are that now you are creating a new Question object every time you go through the loop, and get new random values. Every time it asks a new Question, it will create a new Question object with new random values and overwrite the old ones. It will ask the question 10 times after you give and check the answer, after which the program will output number of correct answers and stop.
Example output for 3 questions:
What is 17 - 15 ?
2
yes.
What is 8 + 11 ?
19
yes.
What is 9 - 0 ?
5
No. It is 9.
Number correct: 2
If you want a way to dynamically ask a question with random numbers and operators, you can create an Operator enum as seen below to handle calculating the result of a left-hand and right-hand value.
Also, the calls to System.out.print should be in the main program as much as possible. Instead, you should return strings from the Question.
All you need to do is pass the two randomly-generated numbers to the Operator enum and ask it to calculate the result.
Exam (main)
package exam;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Exam {
private static int correctCount = 0;
private static List<Question> questions = randomQuestions(10);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
questions.stream().forEach(question -> ask(question, input));
input.close();
stats();
}
private static void ask(Question question, Scanner input) {
System.out.print(question.askQuestion());
double guess = input.nextDouble();
boolean isCorrect = question.makeGuess(guess);
System.out.println(question.explain(isCorrect));
System.out.println();
correctCount += isCorrect ? 1 : 0;
}
private static void stats() {
double percentage = (correctCount * 1.0d) / questions.size() * 100;
System.out.printf("Correct: %.2f%% (%d/%d)%n", percentage, correctCount, questions.size());
}
private static List<Question> randomQuestions(int count) {
List<Question> questions = new ArrayList<Question>();
while (count --> 0) questions.add(new Question());
return questions;
}
}
Question (class)
package exam;
import java.util.Random;
public class Question {
private static final Random RAND = new Random(System.currentTimeMillis());
private double left;
private double right;
private Operator operator;
public Question(double left, double right, Operator operator) {
this.left = left;
this.right = right;
this.operator = operator;
}
public Question(int max) {
this(randInt(max), randInt(max), Operator.randomOperator());
}
public Question() {
this(10); // Random 0 -> 10
}
public String askQuestion() {
return String.format("What is %s? ", operator.expression(left, right));
}
public String explain(boolean correct) {
return correct ? "Correct" : String.format("Incorrect, it is: %.2f", calculate());
}
public boolean makeGuess(double guess) {
return compareDouble(guess, calculate(), 0.01);
}
private double calculate() {
return operator.calculate(left, right);
}
#Override
public String toString() {
return String.format("%s = %.2f", operator.expression(left, right), calculate());
}
private static boolean compareDouble(double expected, double actual, double threshold) {
return Math.abs(expected - actual) < threshold;
}
private static double randInt(int range) {
return Math.floor(RAND.nextDouble() * range);
}
}
Operator (enum)
package exam;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public enum Operator {
ADD("+", (left, right) -> left + right),
SUB("-", (left, right) -> left - right),
MUL("*", (left, right) -> left * right),
DIV("/", (left, right) -> left / right);
private static final Random RAND = new Random(System.currentTimeMillis());
private static final List<Operator> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
public static Operator randomOperator() {
return VALUES.get(RAND.nextInt(SIZE));
}
private String symbol;
private Operation operation;
private Operator(String symbol, Operation operation) {
this.symbol = symbol;
this.operation = operation;
}
public double calculate(double left, double right) {
return operation.calculate(left, right);
}
public String expression(double left, double right) {
return String.format("%.2f %s %.2f", left, symbol, right);
}
#Override
public String toString() {
return symbol;
}
}
Operation (interface)
package exam;
public interface Operation {
double calculate(double left, double right);
}

I was trying to add a balance system in my JAVA program, but i failed

As a new programmer, I don't know how methods are really works. But when I used Object, can they give me any int, float or double value? And can it be used as integer, float, double!? Please help me. Thanks.
import java.util.Scanner;
public class ProjectBookShop {
static Scanner scan= new Scanner(System.in);
static String[] books = {"Java", "C", "CSS"};
static final double studentDiscount = 0.3;
static final double teacherDiscount = 0.4;
static final double alienDiscount = 0.0;
static final int balance = 150;
public static void main(String[] args) {
prln("<---- WELCOME TO OUR BOOK SHOP --->");
prln("Today we are offering you" +balance + "Taka");
prln("Which books do you want:\n Ans:");
String usersChoice= scan.nextLine();
if(books[0].toLowerCase().equals(usersChoice.toLowerCase()))
{
prln("You opted for Java.");
calculatePrice(books[0]);
//Problem starts from this line.
if(balance => showPrice(calculatePrice(books[0])))
{
prln("You are eligible for buying this book!");
}
}else if(books[1].toLowerCase().equals(usersChoice.toLowerCase()))
{
prln("You opted for C.");
calculatePrice(books[1]);
}else if(books[2].toLowerCase().equals(usersChoice.toLowerCase()))
{
prln("You opted for Css.");
calculatePrice(books[2]);
}
else
{
prln("We dont have this book.");
}
}
// These are called methods!
static void calculatePrice(String bookName)
{
double price = 200;
prln("Are you a student, teacher or alien:\n Ans:");
String answer = scan.nextLine();
if(answer.toLowerCase().equals("student"))
{
price = price - (price*studentDiscount);
showPrice(price);
}else if(answer.toLowerCase().equals("teacher"))
{
price = price - (price * teacherDiscount);
showPrice(price);
}else if(answer.toLowerCase().equals("alien"))
{
price = price - (price * alienDiscount);
showPrice(price);
}else
{
prln("We dont offer any books for you!!");
showPrice(price);
}
}
static void showPrice(Object price)
{
prln("Your total price will be: "+ price);
prln("<---- Thanks for shoping with us. --->");
}
static void prln(Object anyObject)
{
System.out.println(anyObject);
}
static void pr(Object anyObject)
{
System.out.print(anyObject);
}
}
Yes, primitive types like int, double or boolean can be assigned to Objects. It is done using wrapper types:
byte - Byte
short - Short
int - Integer
long - Long
float - Float
double - Double
char - Character
boolean - Boolean
void - Void
Note Void is special. As void has no value, the only value assignable to Void is null.
Objects cannot be used as primitive types unless you cast them to right type:
Object ob = myObjectStream.readObject();
Integer intg = (Integer) ob;
Warning: attempting to cast a float wrapped as Float and assigned as Object to Integer will result in ClassCastException being thrown. To prevent it, you may use instanceof:
Object ob = myObjectStream.readObject();
if(ob instanceof Integer) {
int x = (Integer) ob;
// Do something
} else if(ob instanceof Float) {
float f = (Float) ob;
// Do something else
} else {
System.err.println("I don't support provided object class!!!");
}
Did you notice an assignment to float from Float? This works in both sides:
float x = 1.0f;
Float y = x;
float z = y; // == 1.0f
That is automatic boxing/unboxing. If you don't want to use it, you may still do it by hand:
float x = 1.0f;
Float y = Float.valueOf(x);
float z = y.floatValue(); // == 1.0f
This works for all wrapper types except Void.
Also, instead of:
String s1, s2;
if(s1.toLowerCase().equals(s2.toLowerCase()) {
// ...
}
Use:
String s1, s2;
if(s1.equalsIgnoreCase(s2) {
// ...
}
This deals properly with some corner-case Unicode characters.
Operator => does not exist. Did you mean >=?
If method showPrice is always given doubles, wrapped into Doubles, there's no sense to make it wrap them; wrapping takes time. If it is given only Doubles, rewrite it to following:
static void showPrice(double price)
{
prln("Your total price will be: "+ price);
prln("<---- Thanks for shoping with us. --->");
}
This works the same and is faster.
pr is never used! Remove it and save code. Also, when class is loaded, all its methods are loaded. So, if you remove it, you can also make your program boot faster.
As some comments suggest, you try comparing void. Rewrite showPrice once again:
static double showPrice(double price)
{
prln("Your total price will be: "+ price);
prln("<---- Thanks for shoping with us. --->");
return price;
}
This makes the comparison work.
You do not want to use Object for your method arguments. Object is the base Object that every other object in Java is derived from, but in your case, when a parameter is passed (such as a double) to a method that has an Object argument, the receiving method no longer "sees" it as a double, so it can not interpret it as a number.
You should change your prln and pr methods and instead use:
static void showPrice(double price)
{
prln("Your total price will be: "+ price);
prln("<---- Thanks for shoping with us. --->");
}
static void prln(String str)
{
System.out.println(str);
}
static void pr(String str)
{
System.out.print(str);
}

Need a solution for using method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
public class WaterHeater{
//public fields set to private
private double water = 1;
private double kilowatts= 2;
private double joules = 3600;
private double temp = 70;
private double jkg = 4200;
private double energy;
private double time;
//Constructor method
public WaterHeater (double water, double kilowatts, double joules, double temp, double jkg) {
}
//Accessors and mutators
//Accessor for Water
public double getWater() {
return water;
}
public void setWater(int water) {
this.water = water;
}
//Accessor for Kilowatts
public double getKilowatts() {
return kilowatts;
}
public void setKilowatts(int kilowatts) {
this.kilowatts = kilowatts;
}
//Accessor for Temperature
public double getTemp() {
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
//Method for Energy used
public double getEnergy() {
energy = water*jkg*temp;
return energy;
}
public void setEnergy() {
this.energy = energy;
}
//Method for Time to boil
public double getTime() {
time = energy/kilowatts;
return time;
}
public void setTime() {
this.time = time;
}
}
public class Kettle extends WaterHeater{
public Kettle(double water, double kilowatts, double joules, double temp, double jkg) {
super(water, kilowatts, joules, temp, jkg);
}
public static void main( String args[] )
{
userInput kettleinput = new userInput();
System.out.println("\nEnergy used: ");
System.out.println("Time to boil: ");
}
}
public class userInput {
public static void main(String args[])
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
double getWater;
// These must be initialised
String strWater = null;
int intWater = 0;
System.out.print("Enter amount of water used: ");
System.out.flush();
// read string value from keyboard
try {
strWater = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intWater = Integer.parseInt(strWater);
}
catch (NumberFormatException nfe) {
System.out.println("Whoops: " + nfe.toString());
System.exit(1);
}
double getKilowatts;
// These must be initialised
String strKilowatts = null;
int intKilowatts = 0;
System.out.print("Enter amount of Kilowatts used: ");
System.out.flush();
// read string value from keyboard
try {
strKilowatts = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intKilowatts = Integer.parseInt(strKilowatts);
}
catch (NumberFormatException nfe) {
System.out.println("Whoops: " + nfe.toString());
System.exit(1);
}
double getTemp;
// These must be initialised
String strTemp = null;
int intTemp = 0;
System.out.print("Enter the temperature of water raised by: ");
System.out.flush();
// read string value from keyboard
try {
strTemp = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intTemp = Integer.parseInt(strTemp);
}
catch (NumberFormatException nfe) {
System.out.println("Whoops: " + nfe.toString());
System.exit(1);
}
}
}
Sorry for the long code. I have a problem finding a solution to display the result of the user inputs. I have the methods created in WaterHeater and i want to use them to calculate energy used and time to boil when the user enters Water, Kilowatts and Temp. The methods are already done i just cant find a way to use them. So when the Kettle class is running the user enters Water, Kilowatts and Temp and it will give a result. Any help is appriciated.
I would change the following:
move your code from the userInput main method into the constructor. Then all your variables that you need to use like intWater and intKilowatts i would make member variables. I would then provide public accessor methods.
Then your Kettle class main method you need to instantiate a new kettle and pass through the values from the user input class. Then you can just get the values you need from the kettle class which inherits from that water heater class and provides the required methods to output.
First off, you need to explain yourself a little better. I do not really understand what you really need but here is my try.
WaterHeater
You aren't setting the object's values within the custom constructor.
If some values are constants, just treat them as they are (private static final).
Values such time, energy don't need to be fields as they are calculated every time the user gets them.
Kettle & userInput
Both have a static function called main. That's illegal. I recommend you to move all the code in the latter function into the first one.
Kettle's main function's code do NOT make sense. That wouln't even compile.
userInput is a class so call it UserInput (be consistent).
Please, take a deep breath, get focused and explain better what you need and what you already have. Always try to show a code that, at least, compiles.

Beginner; Methods and Strings

Here is the code:
import java.util.Scanner;
public class sending {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(first);
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(String first, String second){
first = ("Give me a number and I run down and add five to it");
second = ("Lol");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}
As you can see I am new to this and I am having a problem with the main method and the method giveMe.
I want to have giveMe work as a collection of strings that I can call when I need them.
But when I try the above example I eclipse tells me that "first cannot be resolved to a variable" on line six String text = giveMe(first);
What am I doing wrong?
You are trying to use an enum and you never declared one... declare your enum like this outside your Main.
enum s {FIRST, SECOND} //add this
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(s.FIRST); //add the s. so it knows to use your enum
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
Then you want to modify your method to take an enum instead like this
public static String giveMe(s string) {
switch (string) {
case FIRST:
return "Give me a number and I run down and add five to it";
case SECOND:
return "Lol";
}
return "invalid string";
}
Beginner, your problem is resolved.
Firstly declaration is important in java. "First" variable is not intailzed in your block of code. Ideally it is not necessary for your scenario.
Try this
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe();
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(){
String first = ("Give me a number and I run down and add five to it");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}

How to turn static methods into non-static. Small explanation/examples related to java oop

I cant get how to use/create oop code without word static. I read Sun tutorials, have book and examples. I know there are constructors, then "pointer" this etc. I can create some easy non-static methods with return statement. The real problem is, I just don't understand how it works.I hope some communication gives me kick to move on. If someone asks, this is not homework. I just want to learn how to code.
The following code are static methods and some very basic algorithms. I'd like to know how to change it to non-static code with logical steps(please.)
The second code shows some non-static code I can write but not fully understand nor use it as template to rewrite the first code.
Thanks in advance for any hints.
import java.util.Scanner;
/**
*
* #author
*/
public class NumberArray2{
public static int[] table() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
int[] tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
return tab;
}
static public void output(int [] tab){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void max(int [] tab){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
//return maxNum;
System.out.println(maxNum);
}
static public void divide(int [] tab){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void average(int [] tab){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public static void isPrime(int[] tab) {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public static boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
int[] inputTable = table();
//int s = table();
System.out.println("Written numbers:");
output(inputTable);
System.out.println("Largest number: ");
max(inputTable);
System.out.println("All numbers that can be divided by three: ");
divide(inputTable);
System.out.println("Average value: ");
average(inputTable);
System.out.println("Prime numbers: ");
isPrime(inputTable);
}
}
Second code
public class Complex {
// datové složky
public double re;
public double im;
// konstruktory
public Complex() {
}
public Complex(double r) {
this(r, 0.0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public double abs() {
return Math.sqrt(re * re + im * im);
}
public Complex plus(Complex c) {
return new Complex(re + c.re, im + c.im);
}
public Complex minus(Complex c) {
return new Complex(re - c.re, im - c.im);
}
public String toString() {
return "[" + re + ", " + im + "]";
}
}
Let's start with a simple example:
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(personA.getFullName());
System.out.println(personB.getFullName());
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public String getFullName()
{
return (lastName + ", " + firstName);
}
}
I am going to make a minor change to the getFullName method now:
public String getFullName()
{
return (this.lastName + ", " + this.firstName);
}
Notice the "this." that I now use.
The question is where did "this" come from? It is not declared as a variable anywhere - so it is like magic. It turns out that "this" is a hidden parameter to each instance method (an instance method is a method that is not static). You can essentially think that the compiler takes your code and re-writes it like this (in reality this is not what happens - but I wanted the code to compile):
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(Person.getFullName(personA));
System.out.println(Person.getFullName(personB));
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public static String getFullName(final Person thisx)
{
return (thisx.lastName + ", " + thisx.firstName);
}
}
So when you are looking at the code remember that instance methods have a hidden parameter that tells it which actual object the variables belong to.
Hopefully this gets you going in the right direction, if so have a stab at re-writing the first class using objects - if you get stuck post what you tried, if you get all the way done post it and I am sure we help you see if you got it right.
First, OOP is based around objects. They should represent (abstract) real-world objects/concepts. The common example being:
Car
properties - engine, gearbox, chasis
methods - ignite, run, brake
The ignite method depends on the engine field.
Static methods are those that do not depend on object state. I.e. they are not associated with the notion of objects. Single-program algorithms, mathematical calculations, and such are preferably static. Why? Because they take an input and produce output, without the need to represent anything in the process, as objects. Furthermore, this saves unnecessary object instantiations.
Take a look at java.lang.Math - it's methods are static for that precise reason.
The program below has been coded by making the methods non-static.
import java.util.Scanner;
public class NumberArray2{
private int tab[]; // Now table becomes an instance variable.
// allocation and initilization of the table now happens in the constructor.
public NumberArray2() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
}
public void output(){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
public void max(){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
System.out.println(maxNum);
}
public void divide(){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
public void average(){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public void isPrime() {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// instatiate the class.
NumberArray2 obj = new NumberArray2();
System.out.println("Written numbers:");
obj.output(); // call the methods on the object..no need to pass table anymore.
System.out.println("Largest number: ");
obj.max();
System.out.println("All numbers that can be divided by three: ");
obj.divide();
System.out.println("Average value: ");
obj.average();
System.out.println("Prime numbers: ");
obj.isPrime();
}
}
Changes made:
int tab[] has now been made an
instance variable.
allocation and initialization of the
table happens in the constructor.
Since this must happen for every
instantiated object, it is better to
keep this in a constructor.
The methods need not be called with
table as an argument as all methods
have full access to the instance
variable(table in this case)
The methods have now been made
non-static, so they cannot be called
using the class name, instead we need
to instantiate the class to create an
object and then call the methods on
that object using the obj.method()
syntax.
It is easy to transform class methods from beeing static to non-static. All you have to do is remove "static" from all method names. (Ofc dont do it in public static void main as you would be unable to run the example)
Example:
public static boolean isPrimeNum(int n) { would become
public boolean isPrimeNum(int n) {
In public static void main where you call the methods you would have to chang your calls from beeing static, to refere to an object of the specified class.
Before:
NumberArray2.isPrimeNum(11);
After:
NumberArray2 numberarray2 = new NumberArray2(); // Create object of given class
numberarray2.isPrimeNum(11); // Call a method of the given object
In NumberArray2 you havent included an constructor (the constructor is like a contractor. He takes the blueprint (class file, NumberArray2) and follows the guidelines to make for example a building (object).
When you deside to not include a constructor the java compilator will add on for you. It would look like this:
public NumberArray2(){};
Hope this helps. And you are right, this looks like homework :D
I belive its common practice to supply the public modifier first. You haven done this in "your" first method, but in the others you have static public. Atleast for readability you should do both (code will compile ether way, as the compilator dosnt care).
The code is clean and easy to read. This is hard to do for someone who is "just want to learn how to code". Hope this helps you on your way with your "justlookslikehomeworkbutisnt" learning.
I'm guessing you're confused of what "static" does. In OOP everything is an object. Every object has its own functions/variables. e.g.
Person john = new Person("John",18);
Person alice = new Person("Alice",17);
if the function to set the 'name' variable would be non static i.e. string setName(string name){} this means that the object john has a name "John" and the object alice has a name "Alice"
static is used when you want to retain a value of something across all objects of the same class.
class Person{
static int amountOfPeopleCreated;
public Person(string name, int age){
amountOfPeopleCreated++;
setName(name);
setAge(age);
}
...
}
so if you'd the value of amountOfPeopleCreated will be the same no matter if you check alice or john.

Categories