why is my ternary boolean operator showing the opposite - java

isnt the ternary operator suppose to work as arg ? true:false ??? so if duration and petroleum are more than the stated amount than field variables, it should return true.. but this returns false instead
public class test12 {
int duration = 260;
int petroleum = 300;
boolean result;
public void checktrain(){
boolean result = duration>=250 && petroleum>=235? true : false;
this.result = result;
}
public void run(){
System.out.print(result);
}
public static void main(String args[]){
test12 tr = new test12();
tr.run();
}
}

Result is false because you have never called the method checktrain and default value of member variable result is false.

You forgot to call checktrain().So as it remains with default value false of boolean.
Try to call that method.
public static void main(String args[]){
test12 tr = new test12();
tr.checktrian();
tr.run();
}
And check train method can be written simply as
public void checktrain(){
this.result= duration>=250 && petroleum>=235;
}
And even you can avoid that boolean by writing
public boolean checktrain(){
return duration>=250 && petroleum>=235;
}

Related

How can I pass a value from one constructor to another constructor?

I'm working with Java. I have a class with 2 constructors. The first constructor takes an int value as a parameter and sets an int variable as that value. The second constructor takes a string and prints it out. The idea is that when I call the first constructor from my main class, it sets an integer value. And when I call the second constructor in the main class, it takes the string representation of int variable of the first constructor and prints it out.
Here's how I made the constructors:
public class Test
{
int val;
public Test(int x)
{
val = x;
return val; //I know this won't work. So I'm looking for an alternative
}
public Test(String y)
{
System.out.println("The value is " + y);
}
}
And the main method (in a different class) looks like this:
public static void main(String [] args)
{
Test t1 = new Test(6);
Test t2 = new Test(String.valueOf(t1)); //This won't work because the first constructor can't return a value
}
So how exactly can I change the contents of the constructors so that I can pass val into the 2nd constructor?
Override toString() to return value so when you so String.valueOf(t1) it will do the toString() method;
public class Test
{
int val;
public Test(int x)
{
val = x;
}
public Test(String y)
{
System.out.println("The value is " + y);
}
#Override
public String toString()
{
return String.valueOf(val);
}
}
I think what you are probably actually trying to do is to override the toString() method of Test.
public class Test
{
int val;
public Test(int x)
{
val = x;
}
#Override
public String toString() {
return "Test:"+val;
}
}
Then you can do this:
public static void main(String [] args)
{
Test t1 = new Test(6);
String s = t1.toString();
// or this
System.out.println( t1 ); // prints "Test: 6"
}
What you're describing is actually impossible without some changes.
First and foremost, t1 and t2 are two separate instances and the values inside of them have no bearing on one another. So t1 has x=6 and t2 has x=0 (because of default values).
If you want your second constructor to have a value of x that isn't 0, then you'll need to pass that in too.
public Test(int x, String s) {
super(x);
System.out.println(x);
}
I think you don't really want two constructors. It seems like you're wanting to do something like the following:
public class Test
{
int val;
public Test(int x)
{
val = x;
}
public void printVal()
{
System.out.println("The value is " + val);
}
public static void main(String [] args)
{
Test t1 = new Test(6);
t1.printVal();
}
}
Your requirement is kinda weird. But this will work even it is kinda weird
public class Test {
private static int val;
public Test(int x) {
val = x;
}
public Test() {
System.out.println("The value is " + String.valueOf(val));
}
public static void main(String[] args) {
Test t1 = new Test(6);
Test t2 = new Test();
}
}

Assigning a new boolean value to method?

This is what I have:
public static void main(String[] args){
Main main = new Main();
boolean shouldBeTrue = main.shouldBeTrue();
shouldBeTrue = true;
System.out.println(shouldBeTrue);
System.out.println(main.shouldBeTrue());
}//close main
public boolean shouldBeTrue(){
return false;
}
It prints: true false
However I would to assing main.shouldBeTrue() = true;
which does not work.
My goal is to print main.shouldBeTrue() and have it print true instead of false.
Any ideas?
Thank you all so so much!
System.out.println(main.shouldBeTrue());
The above is line is actually calling shouldBeTrue(), which is returning false.
Either pass a boolean variable to a method and return that values.
public boolean shouldBeTrue(boolean myValue) {
return myValue;
}
For main.shouldBeTrue() to return true, the reference it returns should point to a value of true.
public class Main {
private boolean whatDoIReturn = false;
public static void main(String[] args){
Main main = new Main();
Boolean shouldBeTrue = main.shouldBeTrue();
main.shouldBeTrue( shouldBeTrue = true);
System.out.println(shouldBeTrue);
System.out.println(main.shouldBeTrue());
}//close main
public Boolean shouldBeTrue(){
return whatDoIReturn;
}
public void shouldBeTrue(boolean value){
this.whatDoIReturn = value;
}
}
As others have already mentioned, you can not assign a value to a method! What you need to do is maintain a variable that the method will return.
class MyClass
{
private boolean myReturnValue = false; // can be set to either true or false
public boolean shouldBeTrue()
{
return myReturnValue;
}
// Use this method to set the return value.
public void setMyReturnValue( boolean newValue )
{
myReturnValue = newValue;
}
public static void main( String[] args )
{
MyClass myClass = new MyClass();
System.out.println(myClass.shouldBeTrue()); // this will return false, which is currently the defined value of myReturnValue
// Now we will change the return value.
myClass.setMyReturnValue(true);
System.out.println(myClass.shouldBeTrue()); // Now it will return true.
}
}

Implementing Static Methods In A Class

From a book I'm going through:
"Design a class name MyInteger. The class contains:
...blah, blah, blah...
The methods isEven(), isOdd(), and isPrime() that return true if the value in this object is even, odd, or prime, respectively.
The static methods isEven(int), isOdd(int), and isPrime(int) that return true if the specified value is even, odd, or prime, respectively.
The static methods isEven(MyInteger), isOdd(MyInteger), isPrime(MyInteger), that return true if the specified value is even, odd, or prime, respectively."
Here's what I've got so far. The top is easy to implement with object.isEven()...
The second, I assume this is just to display results without actually setting the value and changing the object? So I could just do object.isEven(2)?
The last one... that's throwing me off a lot. I have no idea. =/ Please help me out. Thanks in advance.
To clarify:
1.
public boolean isEven(){
// code
}
MyInteger object = new MyIntger(50);
object.isEven();
2.
public boolean isEven(int num){
// code
}
MyInteger.isEven(50)???
3.
public boolean isEven(int MyInteger)???
???
class MyInteger {
int number;
// CONSTRUCTOR
public MyInteger(int a) {
number = a;
}
public int getNumber() {
return number;
}
static boolean isEven(MyInteger myint) {
if (myint.getNumber() % 2 == 0)
return true;
else
return false;
}
}
Now the main class:
public class MainClass {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyInteger myInteger=new MyInteger(10);
boolean result=MyInteger.isEven(myInteger);
if(result==true)
System.out.println("true result");
else
System.out.println("false result");
}
}
This seems to be the one that's confusing
boolean odd2 = MyInteger.isOdd(new MyInteger(5)); // static call
You use use an instance of MyInteger to pass as an argument. Another way to pass MyInteger as an argument is:
MyInteger num = new MyInteger(5);
boolean odd2 = MyInteger.isOdd(num); // static call
class MyInteger{
int num;
public MyIntger(int num){
this.num = num;
}
// Method 1
public static boolean isOdd(int num){
...
}
// Method 2
public boolean isOdd(){
...
}
// Method 3
public static boolean isOdd(MyInteger num){
...
}
}
public class TestMyInteger{
public static void main(String[] args){
// Method 1 call
boolean odd1 = MyIntger.isOdd(5); // static call
// Method 3 call
boolean odd2 = MyInteger.isOdd(new MyInteger(5)); // static call
// Method 2 call
MyIntger num = new MyIntger(5); // create instance
boolean odd3 = num.isOdd(); // instance call
System.out.println(odd1);
System.out.println(odd2);
System.out.println(odd3);
}
}
For second one, the method is belong to the class. But not the created object.
If Your code like this :
MyInteger myInteger = new MyInteger(100);
You can call the method by this
MyInteger.isEven(50);
or
myInteger.isEven(50);
It is not related to 100 which set in object.
Consider this as a pointer, and then you might want to look at this question.
public class MyInteger {
private int value;
public MyInteger(int value) {
super();
this.value = value;
}
public static boolean isPrime(int value) {
// I would increment counter then test if the result of value modulo counter
// (that is if value % counter != 0) until counter >= square_root(value).
// Then the value is prime, otherwise
return false;
}
public static boolean isEven(int value) {
return (value & 1) == 0;
}
public static boolean isEven(MyInteger m) {
return isEven(m.value);
}
public static boolean isPrime(MyInteger m) {
return isPrime(m.value);
}
public static boolean isOdd(int value) {
return !isEven(value);
}
public static boolean isOdd(MyInteger m) {
return isOdd(m.value);
}
public boolean isEven() {
return isEven(this.value);
}
public boolean isOdd() {
return isOdd(this.value);
}
public boolean isPrime() {
return isPrime(value);
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
You would be performing actions upon the MyInteger object rather than just a straight int.
Let's say your private variables and constructor look like this (we don't know exactly because it isn't posted):
private int myInt;
public MyInteger(int thisInt) {
myInt = thisInt;
}
You will need to implement an accessor method that returns the value of myInt within an instance of the MyInteger class and then use this accessor method in your static method to perform the operation.
So as an accessor method:
public int getInt()
{
return myInt;
}
And then your static method would reference this method in the same way you would in another program. Note that you have to specify the use of the MyInteger object even within the class:
public static boolean isEven(MyInteger myInteger)
{
//Code here
}
In terms of calling the static method, it would look something like this:
MyInteger myInteger = new MyInteger(50);
MyInteger.isEven(myInteger);
Here, you are referencing an instance of the MyInteger object (myInteger) rather than the primitive int, but because isEven isn't directly connected to a specific object, you have to tell your code where to find the isEven() method, the MyInteger class.

How to determine the primitive type of a primitive variable?

Is there a "typeof" like function in Java that returns the type of a primitive data type (PDT) variable or an expression of operands PDTs?
instanceof seems to work for class types only.
Try the following:
int i = 20;
float f = 20.2f;
System.out.println(((Object)i).getClass().getName());
System.out.println(((Object)f).getClass().getName());
It will print:
java.lang.Integer
java.lang.Float
As for instanceof, you could use its dynamic counterpart Class#isInstance:
Integer.class.isInstance(20); // true
Integer.class.isInstance(20f); // false
Integer.class.isInstance("s"); // false
There's an easy way that doesn't necessitate the implicit boxing, so you won't get confused between primitives and their wrappers. You can't use isInstance for primitive types -- e.g. calling Integer.TYPE.isInstance(5) (Integer.TYPE is equivalent to int.class) will return false as 5 is autoboxed into an Integer before hand.
The easiest way to get what you want (note - it's technically done at compile-time for primitives, but it still requires evaluation of the argument) is via overloading. See my ideone paste.
...
public static Class<Integer> typeof(final int expr) {
return Integer.TYPE;
}
public static Class<Long> typeof(final long expr) {
return Long.TYPE;
}
...
This can be used as follows, for example:
System.out.println(typeof(500 * 3 - 2)); /* int */
System.out.println(typeof(50 % 3L)); /* long */
This relies on the compiler's ability to determine the type of the expression and pick the right overload.
You can use the following class.
class TypeResolver
{
public static String Long = "long";
public static String Int = "int";
public static String Float = "float";
public static String Double = "double";
public static String Char = "char";
public static String Boolean = "boolean";
public static String Short = "short";
public static String Byte = "byte";
public static void main(String[] args)
{
//all true
TypeResolver resolver = new TypeResolver();
System.out.println(resolver.getType(1) == TypeResolver.Int);
System.out.println(resolver.getType(1f) == TypeResolver.Float);
System.out.println(resolver.getType(1.0) == TypeResolver.Double);
System.out.println(resolver.getType('a') == TypeResolver.Char);
System.out.println(resolver.getType((short) 1) == TypeResolver.Short);
System.out.println(resolver.getType((long) 1000) == TypeResolver.Long);
System.out.println(resolver.getType(false) == TypeResolver.Boolean);
System.out.println(resolver.getType((byte) 2) == TypeResolver.Byte);
}
public String getType(int x)
{
return TypeResolver.Int;
}
public String getType(byte x)
{
return TypeResolver.Byte;
}
public String getType(float x)
{
return TypeResolver.Float;
}
public String getType(double x)
{
return TypeResolver.Double;
}
public String getType(boolean x)
{
return TypeResolver.Boolean;
}
public String getType(short x)
{
return TypeResolver.Short;
}
public String getType(long x)
{
return TypeResolver.Long;
}
public String getType(char x)
{
return TypeResolver.Char;
}
}
There are two ways that you can use to determine the type of the Primitive type.
package com.company;
public class Testing {
public static void main(String[] args) {
int x;
x=0;
// the first method
System.out.println(((Object)x).getClass().getName());
if (((Object)x).getClass().getName()=="java.lang.Integer")
System.out.println("i am int");
// the second method it will either return true or false
System.out.println(Integer.class.isInstance(x));
}
}

Java 'this' keyword

I'm just beginning in programming and I'd like to make exercise from a book, but I can't. That's my problem:
public class increment {
int increment() {
return this + 1; // aka this++
}
public static void main(String[] args) {
int a = 0;
System.out.println(a.increment());
}
}
As you for sure guessed already, that it doesn't works, I want to ask you how to get outputed integer a incremented by one, but using keyword 'this'.
Regards and sorry for stupid questions.
It is strange to name a class like a method.
I guess you wanted this:
public class Counter {
int val;
public Counter (int start) {
val = start;
}
public void increment() {
val ++;
}
public String toString () {
return Integer.toString (val);
}
public static void main(String[] args) {
Counter counter = new Counter (0);
counter.increment ();
System.out.println(counter.toString ());
}
}
this is an object (the current object). You cannot "increment" it.
A way to do it is:
public class Increment {
int a = 0;
int increment() {
return a + 1;
// or: return this.a + 1;
// or: a++; return a; if you want a to be incremented from now on
}
public static void main(String[] args) {
Increment inc = new Increment();
System.out.println(inc.increment());
}
}
The this keyword in Java refers to the current scope's object instance. I don't think it's what you're looking for in this case.
In your example, a isn't an object of the class increment, it is a primitive int. In order to use the .increment() function you defined, it would have to be an object of type increment.
One option that may be what you're looking for would be the following.
public class Increment { //Java likes capitalized class names
private int myInt;
public Increment(int a) { //constructor
myInt = a;
}
public int increment() {
return ++myInt;
}
public static void main(String[] args) {
Increment a = new Increment(0);
System.out.println(a.increment());
}
}
In this example, we make a new class of type increment, which internally contains an integer. Its increment method increments that internal integer, and then returns the number.
you are using operator + for your current object (this). Operator overloading is not supported in java.
Something like this will work:
class MyInteger {
private int internal;
public MyInteger( int value ){
this.internal = value;
}
public int incerment(){
return ++this.internal;
}
}
public class Increment {
public static void main(String[] args) {
MyInteger a = new MyInteger(0);
System.out.println(a.increment());
}
}
You see, you can only implement methods for your own classes, not for existing classes, or for primitives like int.
i don't think you can use this to return the value, except if you're making a new class like this:
class Increment1
{
private int a;
public int increment2(int a)
{
this.a=a;
return this.a + 1;
}
}
public class Increment
{
static Increment1 b = new Increment1();
public static void main(String[] args)
{
int a = 0;
System.out.println(b.increment2(a));
}
}
You cannot increment a class like this.
You have to use a member variable that you can increment.
public class Test {
private int var;
public Test(int i) {
this.var = i;
}
int increment() {
this.var++;
}
}
public static void main(String[] args) {
Test t = new Test(0);
System.out.println(t.increment());
}
This refers to the current instance of the class, not a particular member.
You want to increment a property (I'm guessing of type long or int), and not the instance of your increment class (should be Increment, by the way).
Something like this would work:
public class increment {
private int innerValue = 0;
int increment() {
innerValue+=1
return innerValue; // aka this++
}
public static void main(String[] args) {
increment a = new increment()
System.out.println(a.increment());
}
}

Categories

Resources