I have an assignment to create a class Input and have method public static int readInt(Scanner in, String prompt, String error, int min, int max) I was provided the main method but have no idea what I'm supposed to be putting in the class Input. This is what I have:

import java.util.Scanner;

public class Input
{
	public static int readInt(Scanner in, String prompt, String error, int min, int max)
	{
		Scanner age = in;
		if (age > 1 && age < 150)
		return age;
		return age;
	}

}
import java.util.Scanner;

public class AgePrinter
{
	public static void main(String[] args) 
	{
		Scanner in = new Scanner(System.in);
		int age = Input.readInt(in, "Please enter your age", "Illegal Input--try again", 1, 150);
		System.out.println("Next year, you'll be " + (age + 1));

	}

}

Have you learned anything about what methods you can use on the "Scanner" class? (Like ".nextInt()" maybe? ;-)

If you want to keep asking them the question until they give you a valid value, then you will need some form of looping. Me, I'm partial to 'while (true) { ... }'. One might use a 'break;' statement, or maybe just use 'return <something>;' to exit the loop.

You probably want to print the 'prompt' every time. And print 'error' every time there's an error.

You might want to use 'min' and 'max' instead of hard-coding '1' and '150'. Be careful to consider what should happen if the user enters the value '1'. Or '150'.

also: don't put two return statements in one method, that's bound to give errors.
you do realise there's a big difference between a Scanner object and an integer (primitive) I assume?

Actually, the two 'return' statements in his code are not a problem. The first one is not indented, making it look like a problem. And the the rest of the code in the method is confused and wrong. :-/ But the two return statements aren't actually a problem. (...yet. ;-)

nyeah .. ok, misread that. but the check and the one return are redundant, since he returns the same either way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.