Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-static method next() cannot be referenced from a static context

I am trying to parse out a mm/dd/yyyy formatted date into separate fields, but I get the following error when I try to compile:

non-static method next() cannot be referenced from a static context

What could be causing the error?

import java.util.Scanner;

public class Problem39
{

    public static void main(String [ ] args)
    {

    boolean isLeapYear =false;
    int maxDay=0;
    String stringDate;

    System.out.println("Enter the date in mm/dd/yyyy format. ");  //user input
    Scanner keyboard = new Scanner(System.in);                    //read input
    String date=Scanner.next();                                //store input
    String temp=date.split("/");  //parse date
    int month=IntegerParseInt(temp[1]);
    int day=IntegerParseInt(temp[0]);
    int year=IntegerParseInt(temp[2]);
like image 755
Ian Conner Avatar asked May 23 '26 23:05

Ian Conner


2 Answers

Change:

String date = Scanner.next();  

to:

String date = keyboard.next();  

next() is an instance method, so you must call it on an instance of the class Scanner.

Also, change:

String temp = date.split("/"); 

to:

String[] temp = date.split("/"); 

the split() method returns a string array.

like image 107
driangle Avatar answered May 26 '26 11:05

driangle


You mean

String date = keyboard.next();

instead of

String date = Scanner.next();
like image 31
Louis Wasserman Avatar answered May 26 '26 12:05

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!