How to use boolean statements and return - java

I am trying to create a piece of code which will;
return true if given an int n, which is with in 10 of 100 or 200.
import java.util.Scanner;
class nearHundred{
public boolean nearHundred(int n){
Scanner input = new Scanner(System.in);
n = input.nextInt();
if(10>=Math.abs(100-n) || 10>=Math.abs(200-n)){
return true;
}
return false;
}
}
Where have I gone wrong?

From comments it looks like your main method is misplaced, wherever it is I hope it exists only once in a project. Call your class from that main() method, for example -
new nearHundred().nearHundred(100); // a call from main method
Now coming to your code there are several things to correct here. Your method should not take care about Scanner, its job is to take input and check for the logic.
For example;
public class Utils {
public static boolean isNearToHundered(int num) {
return Math.abs(num-100)<=10 || Math.abs(num-200)<=10;
}
}
Give the responsibility to main method for parsing the input, this is how it should work.
Now since I made method static, you can call like
Utils.isNearToHundred(105); // TRUE

Here is how the method should look:
public void mainMethod() {
Scanner input=new Scanner(System.in);
int val=input.nextInt();
boolean nearHundredBoolean=nearHundred(val);
//do something with nearHundredBoolean....
//Same logic, but passes the input to the method nearHundred
public boolean nearHundred(int n) {
if(Math.abs(100-n)<=10 || Math.abs(200-n)<=10)
return true;
else return false;
}
You should pass the value of the scanner input into this method's parameter requirement, instead of not using the parameter n in your current method. If there is a problem, it may be due to the 'input.nextInt()' method that overwrites the value of the parameter n.

Related

Method read() not invoked, however its code is executed [duplicate]

recently, i read in a book about passing a user defined class as an input to scanner but it didn't explained much about the logic behind it. here's the program
import java.nio.CharBuffer;
import java.util.Random;
import java.util.Scanner;
class ScannerInputBase implements Readable
{
private int count;
Random rand = new Random();
ScannerInputBase(int count) { this.count = count; }
public int read(CharBuffer cb) //read is a method in Readable interface
{
if(count-- == 0)
return -1;
for(int i=0;i<2;i++)
{ cb.append('a'); }
return 1;
}
}
public class ScannerInput {
public static void main (String args[]) {
Scanner input = new Scanner(new ScannerInputBase(5));
while(input.hasNext())
{
print(input.next()+"-");
}
}
}
and it's output is
aaaaaaaaaa-
i have 2 questions here
how read() function is getting called here?
i mean i understand it's implicitly geting called somehow but from where it's getting called.
a single hyphen in the output suggests that while loop in main function is iterated only once. but why only once. i was expecting output like aa-aa-aa-aa-aa-
how read() function is getting called here? i mean i understand it's
implicitly geting called somehow but from where it's getting called.
Answer lies in the source code of Scanner class for method next():
public String next() {
....
while (true) {
.....
if (needInput)
readInput();
...
}
}
Which takes us to readInput method which is defined as follows:
private void readInput() {
......
try {
n = source.read(buf);
} catch (IOException ioe) {
.....
}
.....
}
We see that readInput method is calling the read method of source object which is instance of Reader class and is passed as an argument to the Scanner constructor during Scanner's object creation.
Now, Since you have passed the object of subclass of Reader as an argument to the Scanner constructor. And also, You have overridden the read(CharBuffer) method witin your class, So
the overridden version of read method is being called by the Scanner.readinput method.
A single hyphen in the output suggests that while loop in main function is iterated only once. but why only once. I was expecting output like aa-aa-aa-aa-aa-
Because , there is no whitespace in the string aaaaaaaaaa which is the default delimiter Pattern. Consequenty, all string is read in single iteration. So, hasNext is returning false after first iteration and the while loop terminates.
Note: Always use #Override annotation while overriding a method
within subclass.
Scanner class is a wrapper class around streams to read and write data. It has a few overloaded constructors. In your case:
public Scanner(Readable source) {
this(source, WHITESPACE_PATTERN);
}
is invoked. Because interface Readable has only one method read(CharBuffer cb), ScannerInputBase is an instaceof Readable, so the Scanner object just invokes the read() method of whatever Readable is passed.
On the second point, look at the documentation of next()
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
The default pattern used is :
Pattern WHITESPACE_PATTERN = Pattern.compile(
"\\p{javaWhitespace}+");
SO, it your scanner's next() call, reads everything in just one go by making multiple read()calls.

I want to check the number of characters in a String method

I want to check that a certain number of characters in a method that inputs and returns string
public static String watsonCrick(String dna){
dna = "ATA";
int length = dna.length();
char firstCharacter = dna.charAt(0);
char secondCharacter = dnaSequence.charAt(1);
char thirdCharacer = dna.charAt(2);
}
This is my code so far but I dont know what to put as my return and I don't know how to call the method from my main method? All I need is to make sure the string "dna" has three characters in it.
The method doesn't return anything as of yet, I really just want to make sure I'm on the right track and this is how I have to restrict the number of characters in my string.
EDIT: Sorry to add one more thing but if I wanted to add a condition to the method, like let's say I already made a boolean method beforehand and wanted to check if the char firstCharacter was true according to the method how would I add it?
I don't know how to call the method from my main method?
Like this:
public static void main(String[] args) {
watsonCrick("ATA");
}
or if the watsonCrick method is in a different class, like this:
public static void main(String[] args) {
OtherClass.watsonCrick("ATA");
}
All I need is to make sure the string "dna" has three characters in it.
You can do this by putting this at the beginning of the watsonCrick method:
if (dna.length() != 3) { throw new IllegalArgumentException(); }
Assing dna variable in Main method and then write just methodName(Parameters) for calling the method in Main. i.e
String dna;
public static void main(String[] args) {
dna = "ATA";
watsonCrick(dna);
}
And if you need to make sure the string has three characters, use this;
public static String watsonCrick(String dna){
int length = dna.length();
if(length == 3) {
return "true";
}
return "false";
}
If you want you can change the return type to Boolen. (True or False)

Return statement not working when calling another method

I have recently started experimenting with the return statement, and I have a small doubt relating to it- When I have a method which calls another method, will the return statement of that method which I am calling be displayed?
Let be give an example to make it clearer-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
If I were to simply remove the main method(or even make the second method public and run that directly), my return statement is displayed however if I attempt to call the method and run the program my return statement isn't displayed.
So is this just a problem I am facing or is it a general rule in Java that the return statement doesn't work when you call another method(which has a return statement)?
If it is the latter, then I apologise, I was not aware of this.
Thanks...
***UPDATE***
It seems that nobody has understood what I exactly mean. I will give another example-
Please run this program-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
A return statement only returns the value ,does not Display it
If you don’t catch the return value , how can it be displayed? add something like this and try
,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
And Please try learning some good Naming Conventions , Classes are Named like this ,
FirstSecond,TestException(Each Word Starts with a Capital Letter) etc , methods start with a small letter , isPrime() , isEven(),
What a lot of other responders don't know is that when you run a method in BlueJ, it executes the method, and if the the return value of the method is non-void, it is shown in a popup dialog by invoking toString. That's what the questioner means by the value being displayed.
The answer to the user's original question is that by surrounding the method with a void return, it "hides" the result. So this code:
public void callMe1(int a)
{
EvenOrOdd(a);
}
will not display the return. But if you adjust the return type and actually return the value of the inner call:
public int callMe2(int a)
{
return EvenOrOdd(a);
}
Then BlueJ will display the returned value. The display aspect is down to BlueJ, but the rules for whether or not the value gets returned are the same as in Java; void means no return.
Within the body of the method, you use the return statement to return the value. It will not print anything on its own.
Changes done - System.out.println(EvenOrOdd(5));
public class Test {
public static void main(String[] args) {
System.out.println(EvenOrOdd(5));
}
private static boolean EvenOrOdd(int a) {// I can declare as public and run directly but then what is the point in
// calling the method?
if (a % 2 == 0) {
System.out.println("The output is true.");// Displays
return true;// Does not display
} else {
System.out.println("The output is false.");// Displays
return false;// Does not display
}
}
}
Output
The output is false.
false
You never actually display the return result from the method...
The name of the method is consuming EvenOrOdd returning true or false is ambigious, may isEven would be better...
You could try something like...
System.out.println(a + " is even = " + EvenOrOdd(a));
You should also avoid using multiple return statements within a single method, it can quickly become confusing as to how the method actually works, in your case, you can reduce the over complexity at the same time, for example...
private static boolean isEven(int a)
{
boolean isEven = false;
if(a%2==0)
{
System.out.println("The output is true.");//Displays
isEven = true;//Does not display
}
return isEven;
}
first change your main signature from main(int a) to main(String [] args) otherwise you will get following runtime exception :
Error: Main method not found in class yourpackagename.Test, please define the main method as:
public static void main(String[] args)
well you didn't print the value return from function :
in your main do this:
System.out.println(EvenOrOdd(5));

Reference a method within a method in java?

Ok, so I am going to see if this makes sense. In the second method below (int numAdd) I want to be used for the private method (int searchingNum). I don't really understand how private methods work, but whatever number the user enters for the (int numAdd) I want to be duplicated for the parameters in the first method. How is this possible?
//See if user input returns -1 to test whether or not number exists in the array
private int indexOf(int searchingNum)
{
}
//Add number in the array
public boolean addNumber(int numAdd)
{
if (list.contains(numAdd))
{
return false;
}
else
{
list.add(numAdd);
count++;
return true;
}
}
that's it? indexOf(numAdd);
public boolean addNumber(int numAdd)
{
// somewhere, in the middle of nowhere
indexOf(numAdd);
// more of code
}
You can call method of same class directly. No need to do anything. Like this :
public boolean addNumber(int numAdd)
{
int abc = indexOf(numAdd);
//Whatever you want to do...
}

Try and Catch into a method

I'm trying to put a try-catch into a procedure type method but I'm 95% sure it has to be a function type. What I'm trying to accomplish is to make my code shorter in the main. One of the biggest things I thought of was to put a try-catch into a method and call the method.
The thing is, it will validate the input if it is a integer or not- it even catches the exceptions the problem is that it doesn't "remember" the validated input once it continues on with the program/calculates. Here's the part of the code I'm having trouble with.
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
And here is the entire program:
import java.util.Scanner;
public class ch7exercise1
{
public static double compound(double oA, double cI)
{
return roundCent((oA*(Math.pow((1+(percent(cI))),10))));
}
public static double percent(double interest)
{
return interest/100.0;
}
public static double roundCent(double amount)
{
return ((Math.round(amount*100))/100.0); //100.0 is mandatory.
}
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
#SuppressWarnings("unused")
public static void main(String[] args)
{
boolean f = true;
boolean f2 = true;
double origAmount = 0;
double compInterest = 0;
double total = 0;
Scanner iConsole = new Scanner(System.in);
System.out.println("10 year Compound Interest Claculator\n");
System.out.println("Input amount of money deposited in the bank");
tryCatchNum(origAmount);
System.out.println("Input compouded interest rate. (If the compound interest is 3% input 3)");
tryCatchNum(compInterest);
total = compound(origAmount,compInterest);
System.out.println("$"+total);
}
}
Java arguments are passed by value. You're passing 0 to the tryCatchNum method. A copy of the value is passed to the method. This method assigns a new value to its own copy, and then returns. So the original value is still 0.
You must not pass anything to the method. Instead, the method must return the value it has validated. Also, consider using a more appropriate method name:
public double readDoubleValue() {
...
return value;
}
And in the main method:
double origAmount = readDoubleValue();
Since double is a primitive in Java it is passed by value to the method, therefore when you alter the value of the primitive the changes to the method parameter are not reflected in the original variable passed into the method call.
Read the cup story on Java ranch which explains pass by value and pass by reference.
http://www.javaranch.com/campfire/StoryCups.jsp
The next story to read is the Pass By Value story on Java Ranch.
http://www.javaranch.com/campfire/StoryPassBy.jsp
You should alter your method so that it returns a double which is assigned to value in the main method of your program.
I am also very curious as to why you are using a while loop that checks true. I think it is highly likely your program will encounter an infinite loop if the value entered cannot be converted to a double.

Categories

Resources