Online Course Discussion Forum

APCSA Hw06 Q23 Age Converter Errors

 
 
zselina的头像
APCSA Hw06 Q23 Age Converter Errors
zselina - 2022年07月2日 Saturday 15:10
 

Hello!

I am working on question 23 to convert human years to dog years. 

I got the error of "non-static method" convertToHumanAge(int) "cannot be referenced from a static context", where the parameter I passed into this method was a variable from main(String[] args). Java also said "no suitable constructor found for scanner(no arguments). I typed Scanner sc = new Scanner(); and Java pointed an ^ at the "new". 

I'm not sure what is causing the scanner issue? I also don't understand the meaning of the "non-static method can't be referednced from static context?" Thank you!


EDIT 1: I realized I did not input System.in into the constructor of the Scanner(); , however I am tring to run interactive code using Scanner on Visual Studio Code. The input (such as in the FeetToInches.java) shows up but I can't input anything, possible reasons for this occuring? Thank you!

This is my code:

import java.util.Scanner;
import java.math.*;

public class hw06q23{
    public int convertToHumanAge (int dogYears){
        if (dogYears = 1){
            return 13;
        }

        else{
            return (int)(Math.round(16.0/3 * (dogYears - 1) + 13));
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner();
       
        System.out.println("Human years to dog years: ");
        int humanYear = sc.nextInt();
        int answer = convertToHumanAge(humanYear);
        System.out.println("You are " + answer + " dog years old.");


        sc.close();
    }
}



 
WangDr. Kevin的头像
Re: APCSA Hw06 Q23 Age Converter Errors
WangDr. Kevin - 2022年07月2日 Saturday 17:40
 

Regarding the Scanner: it should run after you add "System.in" as parameter.  I am not sure why it doesn't take your input, but maybe it is the following error that prevents your code from being compiled, so you are not at the step of typing input yet.

The "convertToHumanAge" method is an instance method, (not static), so it cannot be called this way from the "main" method.  "main" should be considered an outside method, because it is where the system starts your program, and you must instantiate this class to run the "convertToHumanAge" method.  Here is how you should do it:

After the "int humanYear=sc.nextInt();" line, add the following line:  (btw, isn't this supposed to be named "dogYear"?)

hw06q23  hw = new hw06q23();

Then, call the method this way:

int answer = hw.convertToHumanAge(humanYear);

Please let me know if it works.  Also, as good style, the class name is supposed to start with a capital letter.