Im having a problem. when i write for example "18" in the console, it just prints "0". I also want to know how i am able to print all the instance variables when i create a new car object. Thanks a lot.
public class mad {
public static void main(String[] args) {
java.util.Scanner tastatur = new java.util.Scanner(System.in);
int answer = tastatur.nextInt();
car carA = new car();
carA.createCar(answer);
System.out.println(carA.number);
}
}
class car {
int number;
void createCar(int n) {
n = number;
}
}
You wrote "n = number" instead of "number = n"
Should be this:
void createCar(int n) {
this.number = n;
}
For printing all instance variables, see this: printing all variables
Your assignment in the class car is the opposite of what you wanted to do. You're assigning the field number (which is always 0) to the parameter n. What you wanted to do is assigning the parameter n to the field number.
So the solution is to replace
n = number;
with
number = n;
By the way: By convention class names should start with a capital letter.
In your car class, you're currently doing this:
int number;
void createCar(int n) {
n = number; // you're assigning n to the value of number
}
Switch those around so it reads:
int number;
void createCar(int n) {
this.number = n; // now you're assigning number to the value of n
}
In constructor line n = number; should be number = n;.
You are getting 0 because instance variables are initialized bt 0 or equivalent by default.
To print all variables you must have to define a function to do so. Best way is to override toString() method of Object class.
Related
I am making a program with two classes, one to create methods and the other as the tester class. I am having difficulties assigning the input to a new variable, which needs to be used to invoke the methods from the other class.
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int obj = new NumberUtility(0);
System.out.println("Enter a number. Enter 0 to end");
obj = scan.nextInt();
As example here is the beginning of the other class
public class NumberUtility {
int n = 0;
public NumberUtility(int n) {
getN();
isEven();
isOdd();
}
public int getN() {
return n;
}
public boolean isEven() {
if((n % 2 == 0)) {
return true;
} else
return false;
}
My code is incomplete elsewhere but that is the main issue I have been trying to work around. Since if I set it to an int, it won't work. Sorry if this is a stupid question, I am new to java coding.
With this line:
int obj = new NumberUtility(0);
you are attempting to assign a new NumberUtility object to the variable obj which is of type int. You cannot do that! That's like trying to create a doghouse, and then shoving your dog into a birdhouse. They're just not compatible.
As well, later, you try to reassign obj to the result of scan, which would work, but probably not what you want, as obj is still an int:
obj = scan.nextInt();
I think what you want to do is something like the following:
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Enter a number. Enter 0 to end");
// Read a number from the scanner
int number = scan.nextInt();
// Create a new NumberUtility from this primitive integer
NumberUtility obj = new NumberUtility(number);
System.out.println("Even? " + obj.isEven());
By the way, you can simplify your isEven method as well:
public boolean isEven() {
return (n % 2 == 0);
}
Edit: I see I'm not done yet.
In the NumberUtility class, you have defined a constructor for the class:
public NumberUtility(int n) {
getN();
isEven();
isOdd();
}
This seems like an odd thing to do. You are ignoring the input (int n) and then calling all the methods of the class which don't really do much.
I think you want your constructor to be something like this:
public NumberUtility(int input_n) {
// Save the constructor's input parameter to the member field 'n'
this.n = input_n;
}
I'm trying to check if a number is a square, and if a number is triangular.
The issue is happening at sqrt(num) which is returning 0 for all numbers I test.
I'm using an online compiler, tried several compilers, so it's not a compiling issue. Tried to declare num as a double and as an int, same results.
I'm new to Java, but not new to programming, I searched online, checked my code several times, everything looks fine, it even worked as expected before adding the variables for checking triangular number, but after declaring the variables checkTri and checkTriSqr, this started to happen. I'm sure this have nothing to do with declaring these variables (almost sure), could anyone please help me understand what's going on here?
import static java.lang.Math.sqrt;
import static java.lang.Math.round;
public class Parent{
public static void main(String[] args){
class Number
{
public int num ;
double numSqr = sqrt(num );
double roundNumSqr = round(numSqr) ;
double checkTri = 8 * num + 1 ;
double checkTriSqr = sqrt(checkTri) ;
public void prinTest()
{
System.out.println(num);
System.out.println(numSqr);
System.out.println(roundNumSqr);
System.out.println(checkTri);
System.out.println(checkTriSqr);
}
public boolean isSqr()
{
if (numSqr == roundNumSqr)
{
return true;
}
else
{
return false;
}
}
public boolean isTriangular(){
if (checkTriSqr * checkTriSqr == checkTri )
{
return true;
}
else
{
return false;
}
}
}
Number number = new Number();
number.num = 350;
number.prinTest();
System.out.println(number.isSqr());
System.out.println(number.isTriangular());
}
}
EDIT: The following screen shot is from the tutorial I'm following, concerning declaring classes within methods!
This:
public int num ;
double numSqr = sqrt(num );
initialises num to 0 upon instance construction (the default value for an integer in the absence of assignment), and numSqr is set immediately afterwards (to zero).
You need to recalculate the sqrt() each time you subsequntly set num (perhaps by providing a method setNum() and recalculating everything within that method)
I wouldn't call your class Number, btw. There's already a Number class in the standard Java class set.
numSqr is created in the constructor, whereas number.num = 350;is declared after the construction of your object.
You can use a constructor like this :
public Numer(int num){
this.num=num;
this.numSqr=sqrt(num)
//.... ... ...
}
You can also use an empty constructor and a setter to set the number attribute :
public void setNumber(int num){
this.num=num;
this.numSqr=sqrt(num)
//.... ... ...
}
The values numSqr, roundNumSqr, etc, are all set at the point of the object's creation, however you don't set num to anything until after the object is created. The result is that, for instance,
At creation:
num = 0
therefore
numSqr = 0
roundNumSqr = 0
etc
Then, you set num = 350
But you don't reset the values of numSqr, etc, so this is still the case:
numSqr = 0
roundNumSqr = 0
You need to make a constructor for this class that takes in the value of num and then sets all of the corresponding values, so that they're only set after num has been set (or, add a "calculate" function that updates all the values).
You can modify in this way and compare with technology you have worked on .
import static java.lang.Math.sqrt;
import static java.lang.Math.round;
public class Number {
public int num = 0;
public void prinTest() {
System.out.println(this.num);
System.out.println(this.getSqrt(this.num));
System.out.println(this.getCheckTri());
}
private double getSqrt(double value) {
return sqrt(value);
}
public boolean isSqr() {
if (this.getSqrt(this.num) == round(this.getSqrt(this.num))) {
return true;
} else {
return false;
}
}
private double getCheckTri() {
return 8 * this.num + 1;
}
public boolean isTriangular() {
if (this.getSqrt(this.getCheckTri()) * this.getSqrt(this.getCheckTri()) == this.getCheckTri()) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Number number = new Number();
number.num = 49;
number.prinTest();
System.out.println(number.isSqr());
System.out.println(number.isTriangular());
}
}
You should read some basic tutorials as you have added class inside main method,which means you need more time to check out the syntax.
The other answers alreade said, that the field num was not set to the input number, and that the other fields were actually evaluated on object creation, and hence zero too.
The purpose however is achieved by simple functions:
public static boolean isSquare(int num) {
int root = (int) Math.round(Math.sqrt(num));
return root*root == num;
}
public static boolean isCubic(int num) {
int root = (int) Math.round(Math.cbrt(num));
return root*root*root == num;
}
This exploits the cubic root.
As a comparison of doubles, a sqrt result and its rounded long value are still imprecise, I prefer to recalculate the original parameter.
public int num ;
double numSqr = sqrt(num);
By default, declared instance integer variables (variables declared inside class body) are initialized with 0 (zero). Hence, your code does nothing but take a square root of zero, which is zero.
I am calling a method from another class. The method contains an integer array. I am trying to stay away from inputting the index manually.
I am trying to search for numbers within a range.
example:
ArrayList: {1,5}, {5,10}, {10,15}
Input: enter 3
Process: search for number within range
output: 1,5
The driver class is storing the objects from the main class called Numbers into ArrayList. The main class have an accessor call getNumbers. getNumbers contains an integer array with 2 elements. The driver is calling getNumbers to validate the entry that users input.
The code below works but I'm told it's consider bad coding to code entering the indexes. I want to know how to output the array from getNumber method without knowing the array length of getNumber?
example of what I have:
for(int i = 0; i < example.size(); i++)
//number is the integer that is inputted.
if(example.get(i).getNumbers()[1] > number &&
example.get(i).getNumbers()[0] <= numbers)
System.out.println(example.get(i));
Should I add another for loop?
example of what I am thinking of:
for(int i = 0; i < example.size(); i++)
for(int j = 0; j < example.get(i).getNumbers.length; j++){
if(example.get(i).getNumbers()[j] > number &&
example.get(i).getNumbers()[j] <= numbers)
System.out.println(example.get(i));
}
}
Edit: Changed how I worded some things and fixed the code of what I think I should do.
The code below works but I'm told it's consider bad coding to code
entering the indexes. I want to know how to output the array from
getNumber method without knowing the array length of getNumber ?
If you don't want to do the validations with array indexes for your first element and second element in the array, then you can solve the problem by modifying your Numbers class as shown below:
(1) Define two int variable members (currently you have only one)
(2) Add a method isInLimits(int input) to validate the range
(3) Override toString() which can be used to print the object as String
Numbers class (modified):
public static class Numbers {
private int firstElement;
private int secondElement;
public int getFirstElement() {
return firstElement;
}
public void setFirstElement(int firstElement) {
this.firstElement = firstElement;
}
public int getSecondElement() {
return secondElement;
}
public void setSecondElement(int secondElement) {
this.secondElement = secondElement;
}
//checks the input is in the range of this object elements
public boolean isInLimits(int input) {
if(input >= firstElement && input < secondElement) {
return true;
} else {
return false;
}
}
#Override
public String toString() {
return "{"+firstElement+","+secondElement+"}";
}
}
Usage of Numbers Class:
public static void main(String[] args) {
int userInput = 10; //get it from user
List<Numbers> example = new ArrayList<>();
//Add Numbers objects to example list
for(int i=0;i< example.size();i++) {
Number numberTemp = example.get(i);
//call Numbers object's isInLimits
if(numberTemp.isInLimits(userInput)) {
System.out.println(numberTemp);
}
}
}
I have declared a default and a parameterize constructor. Using a single object I am calling both the constructor and an function. When I run the program I am getting the output as 0 instead of getting the factorial. I have initialize f=1 still the output is 0.
class Factorial
{
int num, f;
Factorial()
{
f = 1;
}
Factorial(int n)
{
num = n;
}
public int getFactorial()
{
for(int i = 1; i <= num; i++)
{
f = f * i;
}
System.out.println("Factorial= " + f);
return f;
}
public static void main(int m)
{
Factorial obj = new Factorial();
obj = new Factorial(m);
obj.getFactorial();
}
}
This is because the initial value of f remains zero when the class is initialized with the factorial(int n) constructor.
Set f to 1 in the initializer to fix this problem:
int n, f = 1;
Factorial() {
}
Factorial(int n) {
num = n;
}
This leaves your class with a big problem: calling getfactorial multiple times will change the state of the class, increasing the value of the factorial. You can fix this by creating a boolean variable that indicates whether the factorial has been computed or not, and returning f after the computation has been performed.
If you do not need "lazy" computation, make f a local variable in the method.
As a good practice, a variable should have the minimal possible scope (preferred local, then instance). Or in other words: state variables should be used just when you want to share some date between several methods of the same class. But what in your case? Factorial is an operation that may be computed in just one step, from one single parameter: No need to further processing.
So, I recommend you to refactorize your class to:
Drop off the state variables: Convert them to local variables or parameters to the method.
Set the factorial method as static (precisely because it does not need state variables).
Another small detail: Parameters are passed from command line to the main method through an array of Strings - always.
Leave all the inputs and outputs to/from the user in just one method, preferrably the main method.
So it will remain like this:
class Factorial
{
public static int getFactorial(int num)
{
int f=1;
for (int i = 1; i <= num; i++)
{
f = f * i;
}
return f;
}
public static void main(String[] args)
{
int m=Integer.parseInt(args[0]);
int factorial=Factorial.getFactorial(m);
System.out.printf("factorial of %d is %d\n", m, factorial);
}
}
Much simplier, isn't it?
I need to generate a program that generates the Fibonacci Sequence
Here is what I have so far:
import java.util.Scanner;
public class FibonacciRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter n:");
int n = in.nextInt();
EP64 fg = new EP64();
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber());
}
}
public class EP64
{
public static void nextNumber(int n)
{
int fold1 = 1;
int fold2 = 1;
int fnew = fold1 + fold2;
fold1 = fnew;
}
}
I get an error on:
System.out.println(fg.nextNumber());
saying:
method nextNumber in class EP64 cannot be applied to given types:
required: int
found: no arguments
reason: actual and formal argument lists differ in length
and can someone also tell me if I am doing this program right? If not, help! I looked at other similar questions but I cannot make much sense of them
Thank you all!
method nextNumber in class EP64 cannot be applied to given types: required: int found: no arguments reason: actual and formal argument lists differ in length
Your
public static void nextNumber(int n)
^^^^^^^
says that any call to the method must provide an integer as argument. But here:
System.out.println(fg.nextNumber());
^^ you need to add an integer argument
you violate this by providing no argument.
As your code reads now, I'd probably drop the int n argument.
and can someone also tell me if I am doing this program right?
Naah, not really...
fold1 and fold2 should probably be member variables (so they don't get reset in every call to the method),
You're forgetting to update fold2 (you only update fold1),
Also, you probably want to return an int from the nextNumber method.
Read up on
Official Java Tutorial: Defining Methods
You are calling a static method to a object reference instead of the class itself.
And
Not passing any argument at all for nextNumber() method.
Make the method non-static as :
public void nextNumber(int n) {}
Pass arg to the method as :
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber(n));
And also don't forget to return the processed number from your nextNumber method,which you collecting in System.out.println.
Your declaration of nextNumber says it takes an int argument, but you are calling it with no arguments.
Also, your code isn't going to do what you want. You probably should make fold1 and fold2 members of class EP64 and make the method an instance method rather than a static method. You also need to do fold2 = fold1; before you update fold1.
Finally, you need to declare nextNumber to return an int value, and then actually have it return an int value.
You have two problems. Firstly, your method doesn't return anything, i.e. it is void. You need to make it int and add a return fnew; at the end. The other problem is you are starting from scratch every time, it will return 2 each time. You need to make fold1 and fold2 fields by moving them above the nextNumber line. Oh, and drop the int n argument as it doesn't do anything.
I agree on the diagnostics of the other posts, but don't suggest a member variable, but a rename and local variables.
You can ask for the 5th Fibonacci-Number with 5 calls to
fib.next ();
or with a single call to
fib (5);
Since the fibonacci-sequence increases very rapidly, you have very few calls (54) before hitting the overflow boundary. So if you repeatedly recalc the same sequence, to print the sequence, it's not a big problem. A recursive solution would be fine.
Btw.: EP64 is a very bad name.
I think this is enough:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
int a=0,b=1,c;
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
If you want to call this as a method then:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
callFibonocci(n);
}
public static void callFibonocci(int n)
{
int a=0,b=1,c;
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
You can call this method out of the class;
// Fibnocci Using c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeProject
{
class FibnocciSeries
{
public int[] FibonacciArray(int length)
{
int[] fseries = new int[length];
fseries[0] = 0;
fseries[1] = 1;
if (length == 0)
return null;
//Iterating through the loup to add adjacent numbers and create the memeber of series
for (int i = 2; i < length; i++)
{
fseries[i] = fseries[i - 1] + fseries[i - 2];
}
return fseries;
}
}
}
////////////////////
class Program
{
static void Main(string[] args)
{
FibnocciSeries fb = new FibnocciSeries();
Console.WriteLine("Please Enter Integer Length of Fibnocci series");
int length = Convert.ToInt32(Console.ReadLine());
int[] result = fb.FibonacciArray(length);
foreach(int i in result)
Console.Write(i.ToString()+ " ");
Console.ReadLine();
}
}
|