Is it wrong to use a separate method for a scanner? - java

An exercise in the introduction to java programming book I am currently working through requires me to retrieve input from the command line using the scanner class. Each example in the book (and the code I have seen here) creates and uses a scanner object in the same method it is needed in, such as:
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter your first name: ");
String firstName = inputDevice.nextLine();
System.out.println("Enter your middle name: ");
String middleName = inputDevice.nextLine();
System.out.println("Enter your last name: ");
String lastName = inputDevice.nextLine();
inputDevice.close();
System.out.println("Your name is " + firstName + " " + middleName + " " + lastName);
}
}
I was wondering why this method is preferred over something like the following (especially since the execise requires me to retrieve input for nine strings)
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
String firstName = prompt("Enter your first name: ");
String middleName = prompt("Enter your middle name: ");
String lastName = prompt("Enter your last name: ");
System.out.println("Your name is " + firstName + " " + middleName + " " + lastName);
}
private static String prompt(String message) {
Scanner inputDevice = new Scanner(System.in);
System.out.println(message);
return inputDevice.nextLine();
}
}
Please keep in mind I am new to both Java and programming in general.

There's nothing wrong with doing it that way, and it very well may save you a few lines in the long run, but it's not common because you can create a Scanner once and reuse it, as you've done above.
It's all style-based, but using one Scanner multiple times is fairly straightforward and avoids unnecessary complexity in your code, which is important (especially in larger-scale projects).
When you're going through the code line-by-line, your first example is much more readable to me, but that's just my opinion, as this is a fairly subjective question. The only real downside is that you're creating a new Scanner every time you call the prompt() method, which is unnecessary.
Also note that you forgot to close the Scanner in the method.

In your case you are creating the Scanner object for every call of the prompt method which is not great practice.
Also you are not closing the Scanner.
IMHO the book's code is reads easier...

Related

How do I initialize a result variable?

I need to make the result variable so that it is concatenated with my other strings to print my result and I tried multiple ways that are not working.
I have included my set of strings and first if statement to give an idea of my project.
My project rubric states "Initialize 'result' as a single string using concatenation. This string will contain the event type, party size, as as meal and preparation suggestions. Prints the result variable to the console." It also says " 'result' is a string that will be printed to the console.
import java.util.Scanner;
public class whatToEat {
public static void main (String[] args) {
int partySize;
String eventType;
System.out.println("Is your event Casual, Semi-Formal, or Formal?");
Scanner sc = new Scanner(System.in);
eventType = sc.next();
System.out.println("How many people will your event have?");
partySize = sc.nextInt();
if (eventType.equals("Casual") && partySize == 1) {
System.out.println("Since you're hosting a casual event for "
+ partySize +
" person, you should serve sandwiches prepared in the mircowave. ");
Because it says that 'result' is a string that you print in console, I suggest you saving your information in a String first:
String result = "";
Then:
result = "Since you're hosting a casual event for "
+ partySize +
" person, you should serve sandwiches prepared in the mircowave."
Finally:
System.out.println(result);

Why is indexOf() not recognizing spaces?

For this program it asks for the user to input their full name. It then sorts out the first name and last name by separating them at the space the put between the first and last name. However, indexOf() is not recognizing the space and only returns -1. Why is that? Thanks.
Here is the prompt off of PracticeIt:
Write a method called processName that accepts a Scanner for the console as a parameter and that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first and last name will be given. You should read the entire line of input at once with the Scanner and then break it apart as necessary. Here is a sample dialogue with the user:
Please enter your full name: Sammy Jankis
Your name in reverse order is Jankis, Sammy
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String fullName = inputScanner.next();
int space = fullName.indexOf(" "); // always return -1 for spaces
int length = fullName.length();
String lastName = fullName.substring(space+1,length+1);
String firstname = fullName.substring(0, space);
System.out.print("Your name in reverse order is " + lastName + ", " + firstname);
}
}
As next will return the next token use nextLine not next to get the whole line
see http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
When you do String fullName = inputScanner.next() you only read till the next whitespace so obviously there is no whitespace in fullName since it is only the first name.
If you want to read the whole line use String fullName = inputScanner.nextLine();

Input add text on line before input

The code below asks for your name, takes the input, and then displays your name.
Code:
public static void main(String args[]) {
System.out.println("What is your name?");
Scanner name = new Scanner(System.in); //Passed in "Vincent"
System.out.println("Hello, " + name.nextLine() + "!");
}
Output:
What is your name?
Vincent
Hello, Vincent!
Question:
How would I combine the first two lines, so that I can have something similar to:
"What is your name: namehere"
You are using println which adds the new line character at the end of your string.
Use this instead:
System.out.print("What is your name? ");
Read more here.
Just change println to print so the newline is not printed.
System.out.print("What is your name: ");

Basic Java work

I am learning Java. I am fairly new to this and just doing some practice exercises,
This is what it says I must do, I have attempted it (please see my coding below) I need some help with some error messages that I keep getting.
Create a class Student to describe a student with the following attributes:
student ID
name
level
with appropriate data types.
This information should be provided, when an object is created. The program should be able to provide each piece of information, when requested. Please also write a method to input a fixed number (for instance 5) of grades (using the Scanner class) and to calculate and print their average.
A main method to run the program should be devised so that the required information is inputted via the keyboard.
import java.util.Scanner;
public class student{
public static void main (String args []){
Scanner grade = new Scanner(System.in);
int studentgrade;
int studentid;
String studentname;
System.out.println("enter student grade") ;
int studentgrade = grade.nextInt();
System.out.println("enter your studentID here");
int studentid = grade.nextInt();
System.out.println("type your student name here");
String studentname = grade.next();
answer = studentgrade + studentid + studentname;
}
}
I have updated the coding after your feedback and now it says,
variable student grade is already defined in method main
I'm so confused i hate this :(
The error message tells you exactly what the problem is:
";"expected
Means that you are missing a semicolon in your code.
answer = studentgrade + studentid + student name
should be
answer = studentgrade + studentid + studentname;
//import java.util.scanner;
import java.util.*;
public class student
{
public static void main (String args [])
{
Scanner grade = new Scanner(System.in);
int studentgrade=0;
int studentid=0;
String studentname="";
System.out.println("enter student grade");
studentgrade = grade.nextInt(); // the error is here apparently ? it highlights this line yellow and says ";" expected
System.out.println("enter your studentID here");
studentid = grade.nextInt();
System.out.println("type your student name here");
studentname = grade.next();
int answer = studentgrade + studentid;
System.out.println("answer = " + answer + "student name = " + studentname);
//+ student name
}
}
problem with this line
int studentgrade.next.int();
it is neither and assignment nor a statement. what are you trying to do with this?
it should be something like this:
int studentgrade = grade.nextInt();
And then
int studentid = next.int;
should be
int studentid = grade.nextInt();
And same problem is with
string studentname = next.string;
it should be
String studentname = grade.next();
Lots of other changes it requires in terms of being a compilable unit such as scanner should be Scanner, string should be String and system should be System. Please read java naming conventions and use standard class names as is at least.

I'm having trouble only inputting letters, not numbers

For my project I need to input a first and last name with no numbers but I simply can't find anything online. If you could help, that would be terrific.
Also if you have the time, I need to flip the first and last name with a comma when the user inputs them.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class PhoneListr {
public static void main (String[] args) throws IOException {
String firstName;
String lastName;
System.out.println ("Please enter your first name:");
firstName = PhoneList ("");
System.out.println ("Please enter your last name:");
lastName = PhoneList ("");
System.out.println ("Your full name is: " + lastName + "," + firstName);
}
public static String PhoneList (String input) throws IOException {
boolean continueInput = false;
while (continueInput == false) {
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (System.in));
input = bufferedReader.readLine();
continueInput = true;
if(input.matches("[a-zA-Z]+")) {
continueInput = true;
}
else {
System.out.println ("Error, you may only use the alphabet");
continueInput = false;
}
}
return input;
}
}
use String.matches(regex):
if(input.matches("[a-zA-Z]+")) {
System.out.println("your input contains no numerics");
}
else {
System.out.println("only alphabets allowed");
}
the above regex checks a through z, or A through Z, inclusive (range).
For this type of string matching you need to use Regular Expressions, or "RegEx"es. It is a very big topic to cover but here's an introduction. RegExes are tools used to test whether strings match certain criteria, and/or to pull certain patterns out of that string or replace certain parts that match those patterns with something else.
Here is an example using a RegEx to test whether your input contains a digit:
if(input.matches("\\d")) {
// matched a digit, do something
}
Based on OP problem and clarification here are few suggestions.
Chaitanya solution handles the check for only alphabets perfectly.
About the neglected areas of problem :
i would advice you to make two variable firstName and lastName inside the main()
String firstName;
String lastName;
Change retun type of method phoneList() to String
return the entered name input insted of number inside the method phoneList ( dont actually see why you are returning number) and store it inside the firstName and lastName
System.out.println ("Please enter your first name:");
firstName = PhoneList (0);
System.out.println ("Please input your last name:");
lastNamr =PhoneList (0);
now to print it in the "comma format" use
System.out.println("full name is: " +lastName+ "," +firstName);
As i read your program again , its a mess!!
About the method phoneList()
Use regex condition to set continueInput to true/flase and not exploit execptions.
P.s. I would appreciate "editing" to post , if any fellow member find any mistakes above, using a mobile, not sure about formatting etc. Thanks. :-) (y)
You can also use
if(input.matches("[^0-9]"))
{
System.out.println("Don't input numbers!");
continueInput = false;}
Can't understand what 2nd question asks. For answer what I get from your 2nd question is like this.
In main function change the code like this
String first_name = null;
String last_name = null;
System.out.println ("Please enter your first name:");
first_name = PhoneList();
System.out.println ("Please input your last name:");
second_name = PhoneList();
System.out.println (second_name+","+first_name);
then in PhoneList function last line should be changed to
return input;
Please check for a link! for more info
You can add a check by passing the argument to method StringUtils.isNumeric
This returns true if the String entered is numeric

Categories