Stuck on how to make string character input only - java

for the last few hours i've been trying to get this code to only allow character input, as its for accepting names..
I have been following the same type of method i used to allow only integers, but with no luck.
any advice would be great,
Here is my code
String name;
System.out.println("Enter student's name: ");
name = in.nextLine();
while (!in.nextLine().matches("[a-zA-Z]"));
{
System.out.println("Please enter a valid name!: ");
in.next();
}
name = in.nextLine();

Your regex checks if the line matches exactly one [a-zA-Z] character. You probably want to check at least one: [a-zA-Z]+
Bear in mind that the way you are checking, you won't get what you have checked in the variable name, as you are consuming it in your checking. Can I propose an alternative:
System.out.println("Enter student's name: ");
String name = in.nextLine();
while(!name.matches("[a-zA-Z]+")){
System.out.println("Please enter a valid name!");
name = in.nextLine();
}

I'm not too familiar with regex, personally, so I would just go with a method that takes a string and determines whether it is only comprised of the alphabets.
[EDIT] Shame on me, the method for testing if a character is a letter is static. Thanks to dansalmo for reminding me.
public static boolean isAlphabetic(String s) {
for(int i = 0; i < s.length(); i++) {
if (!Character.isLetter(s.charAt(i))) return false;
}
return true;
}

Did you check the value of the variable name?
While you assign the input to name , you seem to read the next line for regex check.
Remove the in.next too and it should work fine

Similar to Bucco's solution but iterating over a char array:
public static boolean isAlphabetic(String s) {
for(char c : s.toCharArray())
if (!Character.isLetter(c)) return false;
return true;
}

Related

how to check if a user's input follows the correct format

I want to write a program to ask the user's age, gender, name. Are there any simpler methods which I can use to check if the input is following the correct format?
The correct format is: name -- age -- gender
For example, Bob -- 22 -- M
public static void main (String[] args){
Scanner scan = null;
String info = null;
while (true){
scanner = new Scanner (System.in);
info = scanner.nextLine();
if (!info.contains("--") || !info.contains(" ")){
System.err.println("invalid format");
continue;
}
String infoList = info.split("--");
// I need to check if the input contains any other sign such as ~,! and if there are
// exactly 3 inputs
// so the list should be {X,Y,Z}, I also need to check if the age is a number rather
//than a letter or a sign.
}
If I write my program like that (use if condition to check every possible invalid condition), which will make my program long-winded.
Best way to do it would be using regular expressions rather than splitting the string into and array and checking each item indidually.
This regex should work:
[A-Za-z]+ -- [0-9]{1,2} -- [MF]
You can then check if any string matches this expression
String regex = "[A-Za-z]+ -- [0-9]{1,2} -- [MF]";
String testString = "Bob -- 22 -- M";
if(testString.matches(regex)) {
// testString matches the regex
} else {
// testString doesnt match the regex
}
After checking that the expression matches you could split the string and be able to manipualte each of the elements individually. Remeber to split by " -- " rather than "--" else you will get spaces in the string which can give problems later when manipulating the data.
If you want to understand better how regex works I would recommend you to search a bit about it as it can be very useful.
You can use Regex
String info = "Bob--22--M";
if (info.matches("[a-zA-z]+--[0-9]{2}--[MFmf]")){
System.out.println("invalid format");
}
See regex here
You can do a simple method for each verification and then only call that method.
String[] infoList = info.split("--");
// infoList[0]should be the name, infoList[1] should be the age and infoList[2] should be the gender
if(!checkFormat(infoList[1],infoList[2])){
System.out.println("invalid format");
return;
}
method for verification:
private boolean checkFormat(String age, String gender){
try
{
int aux =Integer.parseInt("age");
}
catch(Exception)
{
return false;
}
if(!(gender.Equals("M") || gender.Equals("F")))
{
return false;
}
return true;
}
About the name, unless you have some especification, I can't do nothing about it.

how do you use a string in a while loop and then number the string?

in my intro to programming class. I am supposed to make a program that asks the user to enter his/her name and then use a while loop to print the name in the following manner:
(user entered Caroline)
C
a
r
o
l
i
n
e
Caroline, there are 8 letters in your first name.
--I've tried a bunch of things but still can't figure it out.--This is what I have so far
Assuming you are correctly getting the user entered string from the STDIN.
You may look to do something like this in your language of choice:
Find the length of your string
Use the while loop, with the condition relating to the length of your string, to move through the string character by character
Print out to a newline each individual character in your string
Feel free to ask questions and I would be happy to elaborate. Adding some examples of your code so far and the problems your facing would be useful.
In C++, this would be:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i=0;
string s;
cin>>s;
while(i<s.length())
{ cout<<i+1<<"."<<cout<<s[i]<<endl;
i++;
}
cout<<s<<", "<<"There are "<<s.length()<<" letters in your first name.";
return 0;
}
This is also very similar in Java, you should be able to derive it looking at this if you expected it in a programming language of your choice.
inside your main method try this:
//Asks user name.
System.out.println("What's your name?");
//Instantiates scanner
Scanner sc = new Scanner(System.in);
//With the scanner it reads user input and save it in the variable name
String name = sc.nextLine();
//It is a good programming practice to close the scanner
sc.close();
/*The loop that for each letter of the name also prints the position
number plus 1*/
int i = 0;
while (i < name.length()) {
System.out.println(i+1 + ". " + name.charAt(i));
i++;
}
As per snap shot shared by OP:
Here, you need to modify this lines:
System.out.println(name.charAt(i));
to
System.out.printf("%d. %c%n",(1+i),name.charAt(i));
Also, change this line:
i++;
}}}
to
i++;
}
System.out.printf("%s, there are %d letters in your first name%n",name,i));
}}

Comparing a Scanner to a String

I'm trying to ask the user to enter a character ("y"/"n") and check whether or not that was the right answer. I'm getting the following error: "incomparable types: java.util.Scanner and java.lang.String"
Scanner userInput = new Scanner(System.in);
System.out.printf("Is this word spelled correctly?: %s", wordToCheck);
rightCheck(userInput);
public boolean rightCheck(Scanner usersAnswer)
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
Yes, because a scanner is a way of getting input rather than the value itself. You want to fetch the next value from the input, and then compare it. Something like this:
String answer = scanner.next();
if (answer.equals("y")) {
...
} else if (answer.equals("n")) {
...
}
Note that you should usually (including this case) not compare strings with ==, as that compares whether the two operands refer to the exact same string object - you're only interested in whether they refer to equal objects. (See this question for more details.)
I have modified your code, haven't tested it but it should work:
Scanner userInput = new Scanner(System.in);
System.out.println("Is this word spelled correctly?:" + wordToCheck);
rightCheck(userInput.next());//send the string rather than the scanner
public boolean rightCheck(String usersAnswer)//convert the parameter type to String
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
I believe you should first get the String from Scanner (through next() maybe?). Then in your method, do not use "==" as a string comparator.

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

Restrict string input from user to alphabetic and numerical values [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
Basically, my situation requires me to check to see if the String that is defined by user input from the keyboard is only alphabetical characters in one case and only digits in another case. This is written in Java.
my current code:
switch (studentMenu) {
case 1: // Change all four fields
System.out.println("Please enter in a first name: ");
String firstNameIntermediate = scan.next();
firstName = firstNameIntermediate.substring(0,1).toUpperCase() + firstNameIntermediate.substring(1);
System.out.println("Please enter in a middle name");
middleName = scan.next();
System.out.println("Please enter in a last name");
lastName = scan.next();
System.out.println("Please enter in an eight digit student ID number");
changeID();
break;
case 2: // Change first name
System.out.println("Please enter in a first name: ");
firstName = scan.next();
break;
case 3: // Change middle name
System.out.println("Please enter in a middle name");
middleName = scan.next();
break;
case 4: // Change last name
System.out.println("Please enter in a last name");
lastName = scan.next();
case 5: // Change student ID:
changeID();
break;
case 6: // Exit to main menu
menuExit = true;
default:
System.out.println("Please enter a number from 1 to 6");
break;
}
}
}
public void changeID() {
studentID = scan.next();
}
I need to make sure the StudentID is only numerical and each of the name segments are alphabetical.
java.util.Scanner can already check if the next token is of a given pattern/type with the hasNextXXX methods.
Here's an example of using boolean hasNext(String pattern) to validate that the next token consists of only letters, using the regular expression [A-Za-z]+:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter letters:");
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Nope, that's not it!");
sc.next();
}
String word = sc.next();
System.out.println("Thank you! Got " + word);
Here's an example session:
Please enter letters:
&###$
Nope, that's not it!
123
Nope, that's not it!
james bond
Thank you! Got james
To validate that the next token is a number that you can convert to int, use hasNextInt() and then nextInt().
Related questions
Validating input using java.util.Scanner - has many examples!
It's probably easiest to do this with a regular expression. Here's some sample code:
import java.util.regex.*;
public class Test
{
public static void main(String[] args) throws Exception
{
System.out.println(isNumeric("123"));
System.out.println(isNumeric("abc"));
System.out.println(isNumeric("abc123"));
System.out.println(isAlpha("123"));
System.out.println(isAlpha("abc"));
System.out.println(isAlpha("abc123"));
}
private static final Pattern NUMBERS = Pattern.compile("\\d+");
private static final Pattern LETTERS = Pattern.compile("\\p{Alpha}+");
public static final boolean isNumeric(String text)
{
return NUMBERS.matcher(text).matches();
}
public static final boolean isAlpha(String text)
{
return LETTERS.matcher(text).matches();
}
}
You should probably write methods of "getAlphaInput" and "getNumericInput" which perform the appropriate loop of prompt/fetch/check until the input is correct. Or possibly just getInput(Pattern) to avoid writing similar code for different patterns.
You should also work out requirements around what counts as a "letter" - the above only does a-z and A-Z... if you need to cope with accents etc as well, you should look more closely at the Pattern docs and adapt appropriately.
Note that you can use a regex to validate things like the length of the string as well. They're very flexible.
Im not sure this is the best way to do, but you could use Character.isDigit() and Character.IsLiteral() mabybe like this:
for( char c : myString.toCharArray() ) {
if( !Character.isLiteral(c) ) {
//
}
}
try regexp: \d+ -- numerical, [A-Za-z]+ -- alphabetical
I don't think you can prevent the users from entering invalid values, but you have the option of validating the data you receive. I'm a fan of regular expressions. Real quick, something like this maybe (all values initialized to empty Strings):
while (!firstName.matches("^[a-zA-Z]+$")) {
System.out.println("Please enter in a first name");
firstName = scan.next();
}
...
while (!studentID.matches("^\\d{8}$")) {
System.out.println("Please enter in an eight digit student ID number");
changeID();
}
If you go this route, you might as well categorize the different cases you need to validate and create a few helper methods to deal with each.
"Regex" tends to seem overwhelming in the beginning, but learning it has great value and there's no shortage of tutorials for it.
That is the code
public class InputLetters {
String InputWords;
Scanner reader;
boolean [] TF;
boolean FT;
public InputLetters() {
FT=false;
while(!FT){
System.out.println("Enter that you want to: ");
reader = new Scanner(System.in);
InputWords = reader.nextLine();
Control(InputWords);
}
}
public void Control(String s){
String [] b = s.split(" ");
TF = new boolean[b.length];
for(int i =0;i<b.length;i++){
if(b[i].matches("^[a-zA-Z]+$")){
TF[i]=true;
}else
{
TF[i]=false;
}
}
for(int j=0;j<TF.length;j++){
if(!TF[j]){
FT=false;
System.out.println("Enter only English Characters!");
break;
}else{
FT=true;
}
}
}

Categories