Shorten Code in Java when creating objects - java

Im just wondering if there is a nice shortcut in creating a Scanner object, getting user input and storing it into a variable. cheers
my crappy long code:
String userInput;
public String getUserInput(){
Scanner UI= new Scanner(System.in);
userInput = UI.nextLine();
return userInput;
}

Firstly, there's no reason to reinitialize your Scanner every time you want to get user input. For example, you can make it an instance variable:
Scanner ui = new Scanner(System.in);
You also don't need to declare the next line of your Scanner a separate variable within method getUserInput(). If you need it as a variable, you can initialize the variable wherever you call getUserInput().
Write the method like this to be more concise:
public String getUserInput() {
return ui.nextLine();
}

The scanner should be initialized only once, as Jashaszun's comment mentions:
static final Scanner in = new Scanner(System.in);
The actual input can be read by using several methods, each tailored to a specific type of input. In general, if is a line, and you want to obtain it as a String, use this:
public String getUserInput() {
return in.nextLine();
}

Related

How to take user input using StringBuffer in java?

I tried this code but its not working
import java.util.*;
class StringBuffer
{
public static void main(String[] args)
{
StringBuffer Name1=new StringBuffer();
Scanner in=new Scanner(System.in);
System.out.println("Enter a string: ");
Name1.append(in.nextLine());
System.out.println(Name1);
}
}
If the StringBuffer is per-defined then its works. But it fails to take input from user.
You are using class StringBuffer which is already a built-in class in Java.
Ref: Oracle doc
When you instantiate an object like StringBuffer Name1=new StringBuffer(); within your custom defined class StringBuffer, then it creates an object with reference to your custom defined class StringBuffer.
You need to create an object of Java's inbuilt StringBuffer class.
Change your class name to something else or use StringBuilder which is not thread safe but faster than StringBuffer.
Additionally, using Scanner class to read your input.
How can I read input from the console using the Scanner class in Java?
your code is correct but the class name is wrong. change your class name and run it.
StringBuffer is a predefined class in java.lang package which you are trying to use but as the name of your class clashes with it, it uses your class definition instead of the predefined one.
Here Name1.append(in.nextLine()); you are calling append method which is not implemented by your class hence will raise an error cannot find symbol.
Change your class name to something unique and you are good to go. Nothing wrong with the input.
no need to change your class name wheather it's StringBuffer or not.
But do one change in your class. Surely it'll take input from user side
public class StringBuffer {
public static void main(String[] args) {
java.lang.StringBuffer Name1 = new java.lang.StringBuffer();
Scanner in=new Scanner(System.in);
System.out.println("Enter a string: ");
Name1.append(in.nextLine());
System.out.println(Name1);
}
}
It will solve your problem.

Is there any way to make the input from a scanner into an interface?

I am trying to take the input from a user and make it into an interface. Is there any way for me to do that directly from the scanner input? I don't really know how else I would do it. Thanks for the help. My code is
Scanner sc = new Scanner(System.in);
SetInterface target = sc.nextLine();
Is there any way for me to make this string input equal to an interface?
You can never directly equal a Scanner input with an Interface defined by you.
Short answer. You can't assign a String to an interface ever.
interface SetInterface {
void doSomething(String s);
}
SetInterface target = "";
Compile error
incompatible types: java.lang.String cannot be converted to SetInterface

Java import not working

I'm very new to Java, and this is probably a very dumb question. I'm trying to get a simple input from the user, and to do that I get the Scanner class, or BufferedReader. Yet when I try to import java.io.*, the classes show up undefined.
Here's my code:
package testing;
import java.io.*;
import java.util.Scanner;
public class Something {
public static void logln(String content) {
System.out.println(content);
}
public static void main(String [] args) {
}
void getInput(String prompt) {
Scanner s = new Scanner();
}
}
Scanner s is showing up undefined. Why might this be?
Here's your problem:
Scanner s = new Scanner(); // no constructor exists
You need to pass a parameter into the Scanner constructor as this class does not have a default no-parameter constructor. You will want to read the error message critically as it will often tell you exactly what is wrong, here that "The constructor Scanner() is undefined".
If you have similar questions in the future, always post the exact and complete error message.
Also, get real friendly with the Java API as it will help you understand the classes that you're using. Here the Scanner API will tell you exactly what constructors are available for this class.
Hovercraft Full Of Eels, has pointed to the correct error.
I would like to add a couple of things -
the correct constructor would be
Scanner s = new Scanner(System.in);
Also I don't quite understand why your getter method, getInput() is parametrized. Would you like to elaborate on that?
Your problem has nothing to do with java import.
If you want to take input from inputStream which is typically connected to keyboard input, change your constructor to
Scanner sc = new Scanner(System.in);
Read the entered input using,
String content = sc.nextLine();

where to close the scanner used more then once in the class

As i know its better practice to have as less code duplication as possible, So i decided to declare only one scanner throughout the class, but where shall I close the scanner object or is it not necessarily to close it, what does closing the scanner do.
private Scanner scanner;
/**
* Constructor for objects of class Scanner
*/
public Ssss()
{
// initialise instance variables
scanner = new Scanner(System.in);
}
public void enterYourName()
{
System.out.println("Enter your Name");
String name = scanner.nextLine();
System.out.println("Your name is:" + name);
}
public void enterYourAge()
{
System.out.println("Enter your Age");
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
}
Assuming this code is in a class Ssss (as it appears), consider:
Your class contains and uses a Scanner object, so it is responsible for closing it.
The Scanner represents an internal resource, and state of your class... different methods will refer to it at different times.
You cannot know when the user of your class (the main program?) is done with it, so you cannot unilaterally close the Scanner -- where would you close it?
The solution is that your class Ssss must provide its own method that allows the code using Ssss to say "I'm done with you". This method is traditionally called close(), and in it you would close the Scanner (and clean up any other resources).
The client (calling class) must wrap usage of your class Ssss in a try-finally block and call your close() method in the finally clause.
If you are using Java7, your class Ssss should implement AutoCloseable so it can be used in a try-with-resources statement to take advantage of that Java7 feature.

Do I have to write "BufferedReader ..." in every method?

I am learning java programming. Do I have to write BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); again and again in every method in which I have to take input from user? If some other alternatives exist, kindly suggest them.
Probably you should think more carefully at the design of your application.
Usually separating the interaction with the user and the logic of your application is a very good idea.
Ideally you will have a class encapsulating both a BufferedReader and something to print to the console and providing methods to get the input you need and to show the user the information he should be aware of.
In order to have this work you will have to create a new instance of that class and pass it to all the classes that need to interact with the user.
In this way you clearly separate the distinct concerns of your application and this separation will improve the maintainability of your application. Think for instance what would happen if you are required to write a graphical user interface in addition to the textual user interface.
Depending on your use case, there are two possible answers:
If you are using the output stream for debugging, do whatever you like (as long as it works for you), it's your code. Other user's answers are suitable for this.
If, however, you are using it for the actual program, you should do one of the following:
Pass the output stream as a parameter to each method that will use it, or
Have each method return a string that the main program will output.
For major input/output methods, like a 'prompt user for input until they input a valid value', you should pass the stream as a parameter, like so:
Incorrect:
public static void main(String[] args){
promptUserForInput();
}
public static int promptUserForInput(){
Scanner in = new Scanner(System.console().reader());
PrintWriter out = System.console().writer();
out.print("Enter an integer:");
// [...]
}
Correct:
public static void main(String[] args){
promptUserForInput(System.console());
}
public static int promptUserForInput(Console io){
Scanner in = new Scanner(io.reader());
PrintWriter out = io.writer();
out.print("Enter an integer:");
// [...]
}
The other case, where the method does not need live interaction with the user, it should return a String object that the interaction methods will use.
Incorrect:
public static void main(String[] args){
printMsg("bob", "tuna fish", "pickles", "rye");
}
public static String printMsg(String person, String type, String topping, String bread){
System.out.printf("%1$s wants a %2$s sandwich with %3$s on %4$s bread%n",
person, type, topping, bread);
}
Correct:
public static void main(String[] args){
System.out.println(generateMsg("bob", "tuna fish", "pickles", "rye"));
}
public static String generateMsg(String person, String type, String topping, String bread){
return String.format("%1$s wants a %2$s sandwich with %3$s on %4$s bread",
person, type, topping, bread);
}
There is one other improvement, and this I think reaches more to the point of your question. You can create a factory class to instantiate your readers and writers for you:
public class InputFactory {
public static InputStreamReader inStreamReader(InputStream in){
return new InputStreamReader(in);
}
public static BufferedReader bufferedReader(InputStream in){
return new BufferedReader(inStreamReader(in));
}
public static Scanner scanner(InputStream in){
return new Scanner(inStreamReader(in));
}
}
You can add as many overloads to that as you like, so you can call just one function to construct the desired input stream type from any input stream, or even other potential input sources, like files. To get a BufferedReader from an InputStream, call InputFactory.bufferedReader(myInputStream). While that still is a little long, the auto-completion features in eclipse can help enter it quickly, which it won't do as well if you just use the chained constructors.
It depends, you can pass it as a argument to your methods or make it class atribute like
public class Something {
private BufferedReader reader = new BufferedReader(new InputStreamReaddoinger(System.in));
}
or even make it public static variable in order to access it from other classes
public static BufferedReader reader = new BufferedReader(new InputStreamReaddoinger(System.in));
You can make it a static variable:
public static BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
and access it from each relevant method accordingly.
Also, take a look at Scanner, a utility class that makes reading input from the user easier.
As #mariosangiorgio points out, it is important to take into consideration what parts of your program are doing what. You should generally split up your code into logically consistent chunks, and this means separating code that deals with I/O from code that deals with core logic. Consequently, when designing any serious application, the static-variable approach might not be the best one as it could undermine this philosophy of "code separation" in certain contexts. Nevertheless, for someone who is just learning, it should pose no problem.

Categories