using static boolean method [duplicate] - java

This question already has an answer here:
Primitives/Objects Declaration, default initialization values
(1 answer)
Closed 7 years ago.
My code:
import java.util.Scanner;
public class MonthMapper{
static String month;
static int month_num;
public static boolean isMonthNumber (String str) {
month = str;
month_num = Integer.parseInt(month);
return (month_num >= 0 && month_num < 12);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter Month: ");
month = sc.next();
System.out.println (isMonthNumber (Integer.toString(month_num)));
}
}
I have to write a static class method boolean isMonthNumber(String str) that takes a String as an input and returns boolean value. The method returns True if the input string represents an integer value between 1 and 12, otherwise the method returns should return False.
Currently for some reason my program always returns true even when i enter a value greater than 12.

You pass mounth_num variable to a method, but the month variable has the read value.
Replace with this:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter Month: ");
System.out.println(isMonthNumber (sc.next()));
}

Related

Why do I need the static keyword here? [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 2 years ago.
import java.util.Scanner;
public class Info {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n1,n2;
System.out.print("Enter n1: ");
n1 = input.nextInt();
System.out.print("Enter n2: ");
n2 = input.nextInt();
System.out.println(sumTotal(n1,n2));
}
public static int sumTotal(int n1sum, int n2sum) { // *why static includes here*
return n1sum+n2sum;
}
}
I don't understand why do I need to put static in here?
Some other codes with return statement doesn't need static, like this one. So why?
public class FirstProgram {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in); // for scanning
int age;
System.out.println("Enter your age");
age = userInput.nextInt();
var a = new FirstProgram();
a.userAge(age);
}
public int userAge(int age1)
{
if ( age1 < 18 )
{
System.out.println("You are a YOUNG!");
}
else if (age1 > 18 && age1 <=25)
{
System.out.println("Young adult! ");
}
else
{
System.out.println("Wise!");
}
return age1;
}
}
I don't understand why do I need to put static in here.
Java does not allow calling non-static method from a static method directly.
Some other codes with return statement doesn't need static, like this
one. so whyy?
This is how (i.e. using the instance of the class) Java allows you to call a non-static method from a static method.
Learn more about static keyword here.

why I will print "NaN" in java? [duplicate]

This question already has answers here:
In Java, what does NaN mean?
(11 answers)
Closed 3 years ago.
I pass a file into the method. Then, I read the method by line. After that, if the line fulfills my condition, I will read the line by token-based, and update i. My question is, from the output, It looks like my I do not successfully update because my output is NaN. Could you help me to take look at this method, and tell me is anywhere going wrong?
import java.util.*;
import java.io.*;
public class ReadingData {
static Scanner console=new Scanner(System.in);
public static void main(String[] args)throws FileNotFoundException{
System.out.println("Please input a file name to input:");
String name1=console.next();
Scanner input=new Scanner(new File(name1));
choosegender(input);
}
public static void choosegender(Scanner input){
boolean judge=false;
while(judge==false) {
System.out.println("Parse by gender(m/f/M/F):");
String gender=console.next().toUpperCase();
if(gender.contains("F")||gender.contains("M")) {
count(input,gender);
judge=true;
}else {
System.out.println("Wrong...please select again!");
}
}
}
public static void count(Scanner input,String gender){
int i=0;
int totalage=0;
while(input.hasNextLine()) {
String line=input.nextLine();
if(line.contains(gender)) {
Scanner token=new Scanner(line);
int id=token.nextInt();
String name=token.next();
String sex=token.next();
int age=token.nextInt();
i++;
totalage=totalage+age;
}
}
double average=(double)totalage/i;
if(gender.equals("F")) {
System.out.printf("the number of female is "+" "+i+",and the average age is %.1f\n ",average);
}else {
System.out.printf("the number of male is"+" "+i+",and the average age is %.1f\n",average);
}
}
}
My output is :
Please input a file name to input:
student.txt
Parse by gender(m/f/M/F):
f
the number of female is 0,and the average age is NaN
NaN stands for Not a Number.
In javadoc, the constant field NaN is declared as following in the Float and Double Classes respectively.
public static final float NaN = 0f / 0f;
public static final double NaN = 0d / 0d;
If you divide a float or double number by 0, you will get NaN(not a number, see the answer from #Anup Lal)
In your case, if there is no line that contains gender, i will be 0 and you average will be NaN.

Java - how to use variables in static methods [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
I can't figure out how to use variables when methods are static (which "main" has to be?). Here is an example:
import java.util.Scanner;
public class Yatzy {
Scanner input = new Scanner(System.in);
protected static int reply;
public static void main(String[] args){
startGame();
}
public static void startGame(){
System.out.println("How many players? 1 - 3.");
reply = input.nextInt(); // Option 1: class variable
int userinput = input.nextInt(); // Option 2: instance variable
}
}
No matter which way I try, I keep getting this error:
Error: non-static variable input cannot be referenced from a static context
How can I use user inputs (or more generally, variables) within static methods?
The error message is clear, and this is a fundamental as well as a very basic concept in java. You are trying to refer to a variable within the static area, so you should create that variable in the static area.
static Scanner input = new Scanner(System.in);
will do the trick.
Using Static variables and methods
import java.util.Scanner;
public class Yatzy {
static Scanner input = new Scanner(System.in);
static int reply;
public static void main(String[] args){
startGame();
}
public static void startGame(){
System.out.println("How many players? 1 - 3.");
reply = input.nextInt();
int userinput = input.nextInt();
}
}
In the above example, all methods and variables are in the static area.
Using Instance variables and methods
import java.util.Scanner;
public class Yatzy {
Scanner input = new Scanner(System.in);
int reply;
public static void main(String[] args){
new Yatzy().startGame();
}
public void startGame(){
System.out.println("How many players? 1 - 3.");
reply = input.nextInt();
int userinput = input.nextInt();
}
}
Create a new object of your class in the main method and call startGame().

working with variable number of arguments using scanner input class

While working with scanner input can we use var.. args with sc.nextInt()??
for example..(below code)
import java.util.Scanner;
class Sample
{
public static void run(int... args){
System.out.println(args[1]);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("please enter values: ");
int values = sc.nextInt();
run(values);
}
}
the output was ArrayIndexOutOfBoundsException:1 can any one explain about this...
values is just one variable, so args's length is 1, which means the only valid index is 0 (arrays are zero-based entities)
Your array size is 1 and trying to access 2nd value so use below code. I have change from args[1] to args[0].
ArrayIndexOutOfBoundsException arise when we try to access index value which is not present in array, not only for integers array but for all types of arrays.
import java.util.Scanner;
class Sample
{
public static void run(int... args){
System.out.println(args[0]);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("please enter values: ");
int values = sc.nextInt();
run(values);
}
}
use args[0] instead args[1] because your value store on

methods in Java will not work?

So I'm learning Java in class and I'm really loving it so far but its really hard to understand sometimes. Right now I'm trying to understand how methods work. My question is why my code is not working. I am trying to read in an integer from user input then square it.
Here is my code:
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
square(number);
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Let's say I input 5 on the console, the program immediately terminates and I cannot figure out why.
As mentioned by others, you don't print the value and the console will close as soon as the program ends. So you could try something like this
public class ScannerTest {
public static void main(String []args){
while(true){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number (-1 to stop)");
int number = input.nextInt();
if(number == -1){
break;
}
int output = square(number);
System.out.println(output);
}
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
This will print the result and loop ask for new input as long as you don't stop the program.
In Java, when main method comes to end and if there aren't any non-deamon threads running, the JVM ends. Your program came to an end without printing out the result of the square() call.
/*here is your solution :*/
import java.util.*;
import java.lang.*;
import java.io.*;
/*in java everything has to be in a class */
class SquareNumber
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
System.out.println(square(number));
/*something to print the squared number*/
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Your program is terminated because there is no other statement after square(number); statement. So your program executes square(...) method and after then it found end of main function so the program is terminated. To see some output you must print result of square(...) method.
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
int result=square(number);//executing square(...) method and store the returned value of square method to result variable
System.out.println("Square of "+number+" is : "+ result);//printing result
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}

Categories