I've looked all over the internet, but I can't figure out what I'm doing wrong. I'm trying my hand at using private variables from another class using get/set methods. Something's going wrong, but I can't figure it out.
public class Character
{
private int atk = 0;
private int def = 0;
private int spd = 0;
public void setStat(String stat, int n)
{
stat = stat.toLowerCase();
if(stat.equals("def") || stat.equals("defence") || stat.equals("defense"))
{
def = n;
}
if(stat.equals("atk") || stat.equals("attack"))
{
atk = n;
}
if(stat.equals("spd") || stat.equals("speed"))
{
spd = n;
}
}
public int getStat(String stat)
{
stat = stat.toLowerCase();
int n = -1;
if(stat.equals("def") || stat.equals("defence") || stat.equals("defense"))
{
n = def;
}
if(stat.equals("atk") || stat.equals("attack"))
{
n = atk;
}
if(stat.equals("spd") || stat.equals("speed"))
{
n = spd;
}
return n;
}
public Character(int a, int d, int c)
{
atk = a;
def = d;
spd = c;
}
}
This is my first class, Character which will be used as the template for the object, complete with get/set methods.
public class newCharacters
{
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
This is my second class, which constructs a character object and then tries to get a variable. Problem is, whenever I compile, it says that the object method needs an identifier. Exact quote: <identifier> expected
I can't figure out what it means, or what I'm doing wrong? I made get/set methods for each class, created the object in both classes, even constructed and called the object method within the Character class. Same problem every time. Can someone help?
public class newCharacters
{
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
This should not be in a class. This does not mean anything. A class can have bunch of instance variables and methods.
Please study the basics well ;)
Put it in a main method inside the Character class
public static void main(String [] args) {
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
public class NewCharacters
{
public static void main(String[] args) {
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
}
A program starts a main method like above.
Inside a class, at the top level only fields and methods may be declared (and constructors and initializer blocks, and other classes).
Related
How do i print the value of variable which is defined inside another method?
This might be a dumb question but please help me out as i am just a beginner in programming
public class XVariable {
int c = 10; //instance variable
void read() {
int b = 5;
//System.out.println(b);
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println("How to print value of b here? ");
//d.read();
}
}
You can't. b is a local variable. It only exists while read is executing, and if read executes multiple times (e.g. in multiple threads, or via recursive calls) each execution of read has its own separate variable.
You might want to consider returning the value from the method, or potentially using a field instead - it depends on what your real-world use case is.
The Java tutorial section on variables has more information on the various kinds of variables.
You need to return value from your read() methods.
public class XVariable {
int c = 10; //instance variable
int read() {
int b = 5;
return b;
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println(read());
//d.read();
}
}
Return b from the read method and print it
public class XVariable {
int c = 10; //instance variable
int read() {
int b = 5;
return b;
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println(d.read());
}
}
I'm taking an introduction to java programming course at university and have an exam next week. I'm going through past exam papers am sort of stuck on this question:
Consider the following class X: class X { private boolean a; private int b; ... }
(i) Write a constructor for this class. [2 marks]
(ii) Show how to create an object of this class. [2 marks]
(iii) Add a method out, which returns b if a is true, and -b otherwise. This method must be usable for any client of
this class. [2 marks]
I've included my code below, but what i'm stuck on is in the final part to this question. How does one call a method on a new object (as we haven't been taught that in class)? Or, does the question imply that the method has to be usable with any object, not just the created object?
Sorry for my awful code and dumb question, i'm really struggling with Java.
public class X {
private boolean a;
private int b;
X(final boolean i, final int j) {
a = i;
b = j;
}
static int Out(boolean a, int b) {
if (a == true) {
return b;
}
return -b;
}
public static void main(String[] args) {;
X object1 = new X(true, 5);
System.out.println(Out(object1));
}
}
You're very close to the solution. Simply make a method like this:
public int out() {
if (a) {
return b;
} else {
return -b;
}
}
Then you can call it in your main method like this:
X object1 = new X(true, 5);
System.out.println(object1.out());
NB: remove the semicolon at the end of public static void main(String[] args) {;
I think you were meant to create a non-static method named out, which can be called by the client of the class (any place where you create a new object of type X) using the dot notation
public int out() {
if(a)
return b;
else
return -b;
}
public static void main(String[] args) {
X object1 = new X(true, 5);
int result = object1.out();
System.out.println(result);
}
I just started with java and I create a class Range() inside my superclass with a method inside makeRange but when I tried to access to that method throws an error. Whats wrong here?
Here is my code...
public class iAmRichard {
class Range{
int[] makeRange(int upper, int lower){
int[] ary = new int[(upper - lower)+1];
for(int i = 0; i > ary.length; i++ ){
ary[i] = lower++;
}
return ary;
}
}
public static void main(String[] args) {
int foo[];
Range fui = new Range();
foo = Range.(here do not apear makeRange method)
You're creating an inner class here called Range. I don't believe that's what you intended to do, but I'll answer it as stated.
You're referring to this class in a static context, and the inner class can't be referenced with a static context. To address that, you need to make the change to Range: make it static.
public class iAmRichard {
static class Range {
}
}
Further, you're already getting an instance of Range, so all you need to do is use it.
foo = fui.makeRange(1, 10);
If you elected to only create a class called Range, you wouldn't have to deal with any inner classes at all, which I think would be the cleaner approach here.
public class Range {
int[] makeRange(int upper, int lower) {
int[] ary = new int[(upper - lower) + 1];
for (int i = 0; i > ary.length; i++) {
ary[i] = lower++;
}
return ary;
}
public static void main(String[] args) {
int foo[];
Range fui = new Range();
foo = fui.makeRange(1, 10);
}
}
To access a method without creating an instance you have to declare it static. In your case you have also to declare the class Range as static.
Or you can just use the instance you already have with a few changes:
iAmRichard richard=new iAmRichard();
Range fui=richard.new Range();
foo = fui.makeRange(...);
Note tha you need an instance of iAmRichard to create a Range.
Since the call is made from a static block in a static way(No instance is used for calling makeRange method) we need to have the called method to be either static or we need the object of the class to call instance methods.
statically you can use this example to access your method. Here is a link for more information on static methods.
public class IAmRichard {
public static void main(String[] args) {
int foo[];
foo = Range.makeRange(10,1);
}
static class Range{
static int[] makeRange(int upper, int lower){
int[] ary = new int[(upper - lower)+1];
for(int i = 0; i > ary.length; i++ ){
ary[i] = lower++;
}
return ary;
}
}
}
I'm trying to write a program that takes the output of adding two numbers in one class together and adds it to a different number. Here is the first class:
public class Add{
public static void main(String[] args) {
int a = 5;
int b = 5;
int c = a + b;
System.out.println(c);
}
}
And the second:
public class AddExtra{
public static void main(String[] args) {
Add a = new Add();
int b = 5;
int c = a.value+b;
System.out.println(c);
}
}
How do I get this to work? Thanks.
Suggestions:
You need to give the Add class a public add(...) method,
have this method accept an int parameter,
have it add a constant int to the int passed in,
and then have it return the sum.
If you want it to add two numbers, rather than a number and a constant, then give the method two int parameters, and add them together in the method.
Then create another class,
In this other class you can create an Add instance,
call the add(myInt) method,
and print the result returned.
You could try
public class Add{
public int c; // public variable
public Add() { // This is a constructor
// It will run every time you type "new Add()"
int a = 5;
int b = 5;
c = a + b;
}
}
Then, you can do this:
public class AddExtra{
public static void main(String[] args) {
Add a = new Add(); // Here, the constructor is run
int b = 5;
int c = a.c + b; // Access "a.c" because "c" is a public variable now
System.out.println(c);
}
}
Read more about constructors here.
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.