I have following problem:
The user has to put his name correctly in my program:
the name only contain letters, hyphens "-" and blanks " "
the first letter should be a capital letter.
after a blank or hyphens should be followed by a capital letter.
For example only this form should be accepted by the program:
"Name" or "Firstname-Secondname" or "Firstname Secondname".
The 3rd point doesn't work in my code:(
My Java code:
public class Test {
private static Scanner scanner = new Scanner(System.in);
private static String name;
public static void main(String[] args) {
boolean check = false;
check = checkName();
System.out.println("Check= "+check);
output(check);
}
public static void output(boolean check) {
if (check == false) {
System.out.println("Fehler");
}
if(check == true) {
System.out.println("Dein Name ist: "+name);
}
}//End output()
public static boolean checkName() {
System.out.print("Name: ");
name = scanner.nextLine();
boolean check = false;
if(name.charAt(0) >= 'A' && name.charAt(0) <= 'Z') {
for(int i=1; i < name.length(); i++) {
if (name.charAt(i) >= 'a' && name.charAt(i) <= 'z') {
check = true;
} else if (name.charAt(i) == '-') {
i++;
if(name.charAt(i) >= 'A' && name.charAt(i) <= 'Z') {
check = true;
} else {
check = false;
}
} else if (name.charAt(i) == ' ') {
i++;
if(name.charAt(i) >= 'A' && name.charAt(i) <= 'Z') {
check = true;
} else { check = false;
}} else {
check = false;
break;
}
}
} return check;
}//End checkName()
Can someone help please?
This looks like a good place to use a regular expression. What about the following example:
String name = scanner.nextLine();
if (Pattern.compile("^[A-Z][a-z]*(?:(?: |-)[A-Z][a-z]*)?$").matcher(name).find()) {
// Valid Name
}
This checks the variable name against a regular expression to see if it matches. To explain the regular expression:
^ This means start of string.
[A-Z][a-z]* This means an uppercase letter followed by zero or more lowercase letters.
((?: |-)[A-Z][a-z]*)? This means followed by a space or hyphen with an uppercase followed by an optional lowercase character - this section is optional as the group is followed by a ?.
$ This means end of string.
You can also use String.matches() which is simpler, instead of Pattern.compile().matcher().
Related
import java.awt.Component;
import javax.swing.JOptionPane;
public class DoSomething {
public static void main(String[] args) {
String password = JOptionPane.showInputDialog(null,
"Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
Component frame = null;
int counter = 0;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
if (password.matches("a-zA-Z")) {
counter++;
character= true;
}
}
if(Character.isLetterOrDigit(c)) {
counter++;
symbol = false;
}
if(Character.isDigit(c)) {
counter++;
if (counter >=2) {
number = true;
}
if (password.length()>=8) {
length = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog("Your Password " +password +" is valid")
}
}
}
Edited -- it still hates length (even if it is 8 or more)
Why not just use regular expressions ?
public static boolean isValid(String password) {
return password.matches("([a-zA-Z]{8,})([0-9]{2,})");
}
This expression (if I'm not mistaken) checks if there are 8 or more characters(lowercase and uppercase) and if there are more than two numbers in the password. Symbols such as $, #, [space] will trigger the expression as false. EDIT: This regular expression only allows a password with 8 (or more) grouped characters and 2 (or more) numbers. Numbers cannot be separated (1MyPassword3) as this will flag the password as invalid. Further investigation will be required.
See the java API for regular expressions:
java 7 Pattern class
java 8 Pattern class
Also check out String.matches(String regex)
Reaction on comment
This code should suit you better then:
int letterCount = 0;
int numberCount = 0;
/*
* Loop through the password and count all the letters and characters
*/
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (Character.toString(c).matches("[a-zA-Z]")) {
letterCount++;
}
if (Character.toString(c).matches("[0-9]")) {
numberCount++;
}
}
if (letterCount > 8) {
// password has 8 or more characters
}
if (numberCount > 2) {
// password has more than 2 numbers
}
Then if you really want to check length as well, you can add this piece of code (outside the for-loop)
if (password.length() >= 10) {
/* Since we need 2 numbers and 8 characters, the password
* can never be valid if it's smaller than 10 characters
*/
else {
/*
* Invalid password
*/
}
Assuming that your conditions for a valid password were:
At least 8 letters
At least 2 numbers
No symbols
At least 10 characters long
String password = JOptionPane.showInputDialog(null, "Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
int letterCounter = 0;
int numCounter = 0;
Component frame = null;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
letterCounter++;
}
else if(Character.isDigit(c)) {
numCounter++;
}
else {
symbol = true;
}
}
//Checking booleans
if (password.length()>=10) {
length = true;
}
if (letterCounter>=8) {
character = true;
}
if (numCounter>=2) {
number = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog(frame, "Your Password " + password + " is valid");
System.out.println("Success");
}
else {
System.out.println("Invalid");
}
I am trying to find if a phone number fits the format (xxx)xxx-xxxx where x is a digit. First, I have the program for the length and the '(',')', and '-'. When I type in something that doesn't work, I get the logical output. However, when I type in a properly formatted number, my program doesn't return anything.
import java.util.Scanner;
public class Program04 {
public static void main(String args[])
{
Scanner stdIn = new Scanner(System.in);
String pN;
System.out.print("Please enter a phone number (ddd)ddd-dddd :");
pN = stdIn.nextLine();
char a = pN.charAt(1);
char b = pN.charAt(2);
char c = pN.charAt(3);
char d = pN.charAt(5);
char e = pN.charAt(6);
char f = pN.charAt(7);
char g = pN.charAt(9);
char h = pN.charAt(10);
char i = pN.charAt(11);
char j = pN.charAt(12);
if (pN.length() == 13 && pN.charAt(0)=='(' && pN.charAt(4)== ')' && pN.charAt(8)=='-')
{
if (a>=0 && a<=9)
{
if (b>=0 && b<=9)
{
if (c>=0 && c<=9)
{
if (d>=0 && d<=9)
{
if (e>=0 && e<=9)
{
if (f>=0 && f<=9)
{
if (g>=0 && g<=9)
{
if (h>=0 && h<=9)
{
if (i>=0 && i<=9)
{
if (j>=0 && j<=9)
{
System.out.print("This is a valid phone number!");
}
}
}
}
}
}
}
}
}
}
}
else System.out.println("Not a vaid phone number.");
}
}
It's easier to use pattern-matching (regex) for validation:
...
pN = stdIn.nextLine();
System.out.println(pN.matches("\\(\\d{3}\\)\\d{3}-\\d{4}"));
Even if you want to have it check if each character is a digit, using so many nested if's is not the way to go. Instead, define a simple method that applies the check, say:
private static boolean isDigit(char x) {
return x>=0 && x<=9;
}
and then do:
if ( isDigit(a) && isDigit(b) && ...) {
return true;
}
else {
return false;
}
If you're not allowed to use RegEx or if it is too difficult to understand, try simplifying your nested if's by a simple switch inside a loop, it is much more readable and maintenance is the easiest :
public static void main(String[] args) {
String pn = scan.nextLine();
boolean valid = true;
if (pn.length() == 13){
for (int i = 0 ; i < 13 ; i++){
switch(i){
case 0 : valid = pn.charAt(0) == '(';break;
case 4 : valid = pn.charAt(4) == ')';break;
case 8 : valid = pn.charAt(8) == '-';break;
default : valid = Character.getNumericValue(pn.charAt(i)) >= 0 && Character.getNumericValue(pn.charAt(i))<= 9 ; break;
}
if (!valid) break;
}
if (!valid) System.out.println("Invalid number");
}else{
valid = false;
System.out.println("Invalid length");
}
if (valid){
System.out.println(pn + " is a valid telephone number");
}
}
Also, to avoid working with the ASCII value of a char, try using the Character.getNumericValue(Char c) method. It returns a numeric that you can use for your tests, like above.
It is better to use regex in this case:
You can use following :
String pattern = "(\\(\\d{3}\\)\\d{3}-\\d{4})";
Pattern r = Pattern.compile(pattern);
pN = stdIn.nextLine();
Matcher m = r.matcher(pN);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}
It keeps skipping the else part of my statement. I just want it to print out of the invalid line if all the other restrictions are not met.
import java.util.Scanner;
public class Program_3
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: ");
String str = input.nextLine();
boolean lowerCase = false;
boolean upperCase = false;
boolean number = false;
char y;
for (int i = 0; i < str.length(); i++)
{
y = str.charAt(i);
if(Character.isUpperCase(y))
{
upperCase = true;
}
else if(Character.isDigit(y))
{
number = true;
}
else if(Character.isLowerCase(y))
{
lowerCase = true;
}
}
if (lowerCase == true)
{
if (upperCase == true)
{
if (number == true)
{
if (str.length() >= 8)
{
System.out.println("Verdict:\t Valid");
}
}
}
}
else
System.out.println("Verdict:\t Invalid");
}
}
why does it skip and not print the invalid line when all ifs are not met?
The else in your code relates only to the outermost if.
So it will only be executed if lowerCase == false.
To fix this logic, combine all three conditions in a single if, i.e.:
if (lowerCase == true && upperCase == true && number == true && str.length() >= 8)
{
System.out.println("Verdict:\t Valid");
}
else
System.out.println("Verdict:\t Invalid");
Side note, booleans don't require explicit comparison to true, so you can write it shorter:
if (lowerCase && upperCase && number && str.length() >= 8)
The else condition is placed in the wrong place, it'll only be reached if the lowerCase condition is false. And anyway, we can simplify and combine all the ifs in a single condition, what you meant to say was this:
if (lowerCase && upperCase && number && str.length() >= 8) {
System.out.println("Verdict:\t Valid");
} else {
System.out.println("Verdict:\t Invalid");
}
This code can b be simplified to show control-flow:
if(lowerCase == true)
{
//lowerCase == true -> execute this code
if( upperCase == true)...
}else
//lowerCase == false -> execute this code
...
The inner if-statements (which are exclusive btw.) don't execute the outer else-statements, if the condition is false. The logical correct version of your code would be:
if(lowerCase && upperCase && isNumber && str.length() > 8)
System.out.println("Verdict:\t Valid");
else
...
Your test password contains at least one lowercase character. As long as it does, the else statement will never execute. To test "if all conditions are true ... else ..." try the follwing:
if (lowerCase && upperCase && number && str.length >= 8) {
// password ok
} else {
// password not ok
}
By the way, as you can see I don't use lowerCase == true since it's not needed, lowerCase already is a boolean.
I am trying to finish a homework assignment and keep getting two errors and cannot figure out how to fix them. Here is the code:
import java.util.Scanner;
public class GoughAndreaProg5
{
public static void main (String[] args)
{
Scanner stdIn = new Scanner(System.in);
System.out.println("Enter a password that meets the following rules: ");
System.out.println("");
System.out.println("Is atleast 8 characters long");
System.out.println("Contains atleast 1 lower letter character");
System.out.println("Contains atleast 1 upper letter character");
System.out.println("Contains atleast 1 numeric digit");
System.out.println("Contains atleast 1 special character from the set: !##$%^&*");
System.out.println("Does not contain the word \"and\" or the word \"end\"");
System.out.println("");
String myInput = stdIn.nextLine();
boolean digit = false;
boolean upperCase = false;
boolean lowerCase = false;
for(int x=0; x<myInput.length(); x++)
{
if (Character.isDigit(myInput.charAt(x)))
digit = true;
if(Character.isUpperCase(myInput.charAt(x)))
upperCase = true;
if(Character.isLowerCase(myInput.charA(x)))
lowerCase = true;
}
boolean validLength = true;
if (myInput.length() < 8)
{
System.out.println("Must be at least 8 characters long");
validLength = false;
}
boolean special = false;
if(myInput.indexOf('!') != -1 | myInput.indexOf('#') != -1 || myInput.indexOf('#') != -1 || myInput.indexOf('$') != -1 || myInput.indexOf('%') != -1 || myInput.indexOf('^') != -1 || myInput.indexOf('&') != -1 || myInput.indexOf('*') != -1)
special = true;
else //no special character
{
System.out.println("Must contain a special character");
}
boolean word = false;
if (myInput.indexOf("and") != -1 || myInput.indexOf("end"));
{
word = true;
System.out.println("Contains the string \"and\" or the word \"end\"");
}
if(!digit)
System.out.println("Must have a numeric digit");
if(!upperCase)
System.out.println("Must have an upper case");
if(!lowerCase)
System.out.println("Must hava a lower case");
//output valid or not
if (validLength && special && !word && upperCase && lowerCase && digit)
System.out.println("valid");
else
System.out.println("not valid");
} //end main method
public static void System.out.println(String inStr)
{
System.out.println(inStr);
} //end of alt string print method
} //end of class
The errors are:
C:\Users\gougha\Documents\Park\Java Class\myJavaPgms\GoughAndreaProg5.java:76: error: '(' expected
public static void System.out.println(String inStr)
^
C:\Users\gougha\Documents\Park\Java Class\myJavaPgms\GoughAndreaProg5.java:76: error: <identifier> expected
public static void System.out.println(String inStr)
^
I have tried every thing I can think of. I'm sure it's an easy fix, but this is all so new to me and I can't see it. Thank you!
There are several compile errors with your code
To start
public static void System.out.println(String inStr)
should be (though you don't use it so I suggest just remove this method)
public static void println(String inStr)
Then
if (myInput.indexOf("and") != -1 || myInput.indexOf("end"));
should be
if (myInput.indexOf("and") != -1 || myInput.indexOf("end") != -1);
Finally
if(Character.isLowerCase(myInput.charA(x)))
should be
if(Character.isLowerCase(myInput.charAt(x)))
You do not need to create this method public static void System.out.println(inStr). Infact the syntax is also wrong. You just need to provide a method name when you create it. Not the class name along with it.
// Not required at all
public static void System.out.println(String inStr)
{
System.out.println(inStr);
}
System.out.println() is the inbuilt method to print values to the console. So just use System.out.println(inStr) in your main method, whenever you need to print something on the System's output console.
I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
System.out.println("Please enter a single character: ");
String character = in.next();
System.out.println(character);
if (character.isLetter()){
System.out.println("The character entered is a letter.");
}
else (character.isDigit()){
Syste.out.println("The character entered is a digit.");
You could use:
if (Character.isLetter(character.charAt(0))){
....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
...
} else if (Character.isLetter(c)) {
...
}
...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
Ummm, you guys are forgetting the Character.isLetterOrDigit method:
boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{
x = true;
}
This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0)
now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.
here is a code for your program:
import java.util.Scanner;
class Practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Input a letter");
String line = in.nextLine();
char c = line.charAt(0);
if( Character.isDigit(c))
System.out.println(c +" Is a digit");
else if (Character.isLetter(c))
System.out.println(c +" Is a Letter");
}
}
By using regular expressions:
boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}");
char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
System.out.println("not character");
}
else
System.out.println("Character");
Look for ASCII table to see how the int value are hardcoded .
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
char temp = yourString.charAt(0);
if(Character.isDigit(temp))
{
..........
}else if (Character.isLetter(temp))
{
......
}else
{
....
}
import java.util.*;
public class String_char
{
public static void main(String arg[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String data;
data = in.next();
int len = data.length();
for (int i = 0 ; i < len ; i++){
char ch = data.charAt(i);
if ((ch >= '0' && ch <= '9')){
System.out.println("Number ");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("Character");
}
else{
System.out.println("Symbol");
}
}
}
}
You need to convert your string into character..
String character = in.next();
char myChar = character.charAt(0);
if (Character.isDigit(myChar)) {
// print true
}
Check Character for other methods..
You could do this by Regular Expression as follows
you could use this code
EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();
if (Number.matches(NumberPattern) && s.length() > 0)
{
//code for number
}
else
{
//code for incorrect number pattern
}
I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
public static void main(String[] args) {
String c;
boolean b;
System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
c = s.next();
b = containsNumber(c);
try {
if (b == true) {
throw new CharacterFormatException();
} else {
System.out.println("Valid String \t" + c);
}
} catch (CharacterFormatException ex) {
System.out.println("Exception Raised-Contains Number");
}
}
static boolean containsNumber(String c) {
char[] ch = new char[10];
ch = c.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 48) && (ch[i] <= 57)) {
return true;
}
}
return false;
}
}
CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.