Validating String While Loop java No Regex - java

Basically I'm trying to have a few while loops check specific indices within a string. The first loop that validates the length of the refNum works fine. When it gets to the bigger set of while loops it just skips it and I'm not sure why, any feed back would be greatly appreciated.
package testing_code;
import java.util.Scanner;
/**
*
* #author A.Con
*/
public class Testing_Code
{
public static void main(String[] args)
{
Scanner userInput = new Scanner (System.in);
String refNum;
System.out.println("Enter refNum: example - WE123A");
refNum = userInput.next();
int rnLength = refNum.length();
while(rnLength < 6 || rnLength > 6)
{
System.out.println("Invalid reference number. Try again.\n ");
System.out.println("Please enter reference No.: ");
refNum = userInput.next();
rnLength = refNum.length();
}
while(!(refNum.charAt(0) >= 'A') && !(refNum.charAt(0) <= 'Z') && !(refNum.charAt(1) >= 'A') && !(refNum.charAt(1) <= 'Z'))
{
while(!(refNum.charAt(2) >= '0') && !(refNum.charAt(2) <= '9') && !(refNum.charAt(3) >= '0') && !(refNum.charAt(3) <= '9'))
{
while(!(refNum.charAt(4) >= '0') && !(refNum.charAt(4) <= '9') && !(refNum.charAt(5) >= 'A') && !(refNum.charAt(5) <= 'Z'))
{
System.out.println("Invalid reference number. Try again.\n ");
System.out.println("Please enter reference No.: ");
refNum = userInput.next();
}
}
}

Your while conditions are all wrong. !(refNum.charAt(0) >= 'A') && !(refNum.charAt(0) <= 'Z') for instance checks if a character is lower than A and higher than Z, which is impossible; you should be using or instead.
As a matter of fact, there are a lot of ways you can improve this. Here's my version
public class Testing_Code
{
static boolean inRange(char c, char first, char last) {
return (c >= first) && (c <= last);
}
public static void main(String[] args)
{
Scanner userInput = new Scanner (System.in);
String refNum;
System.out.println("Enter refNum: example - WE123A");
refNum = userInput.next();
while(refnum.length() != 6
|| !inRange(refnum.charAt(0), 'A', 'Z')
|| !inRange(refnum.charAt(1), 'A', 'Z')
|| !inRange(refnum.charAt(2), '0', '9')
|| !inRange(refnum.charAt(3), '0', '9')
|| !inRange(refnum.charAt(4), '0', '9')
|| !inRange(refnum.charAt(5), 'A', 'Z'))
{
System.out.println("Invalid reference number. Try again.\n ");
System.out.println("Please enter reference No.: ");
refNum = userInput.next();
rnLength = refNum.length();
}
}
}

First !(A >= B) is equivalent to (A < B). So !(refNum.charAt(0) >= 'A') && !(refNum.charAt(0) <= 'Z') is equivalent to (refNum.charAt(0) < 'A') && (refNum.charAt(0) > 'Z').
If you look at the ASCII table, you will see that "less than A and greater than Z" are mutually exclusive conditions. They will never both be true at the same time, so the while loop ends up simplifying to while(false)

Your condition while(!refNum.charAt(0) >= 'A') && !(refNum.charAt(0) <= 'Z')) is always false, as a char can't be less than 'A' and greater than 'Z' at same time. Use a || instead of && and you are good to go.
I will recommend using
Character.isLetter(refNum.charAt(0)) // returns true if the passed character is a letter
Character.isDigit(refNum.charAt(0)) // returns true, if the passed character is a digit.
Much simpler & easy to read.

Related

How to use a switch...case loop in java inside a nested if...else if...else loop?

import java.util.Scanner;
import javax.lang.model.util.ElementScanner14;
class mudit {
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
System.out.print("Enter!!!");
final char n = input.next().charAt(0);
art :
if ((n >= 'a' && n <= 'z' ) || (n >= 'A' && n <= 'z'))
System.out.println(n + " is an alphabet.");
dart :
if ( n == 'a' || n == 'e' || n == 'i' || n == 'o' || n == 'u' || n == 'A' || n == 'E' || n == 'I' || n == 'O' || n == 'U')
System.out.println("VOWEL");
break dart;
else
System.out.println("CONSONANT");
break dart;
else if ( n * 1 == n)
System.out.println(n + " is a numerical value.");
else
System.out.println("Something else");
input.close();
}
}
When ever i run this code i run into an error.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "else", delete this token
at mudit.main(mudd.java:28)
I want it to tell whether the entered charachter is an alphabet(vowel or consonant) or numerical
I am using vs code editor.
The problem is that the if statement block is more than one line. You can only use an if statement, else statement, or else if statement without curly braces if the block is only a single line. To fix this problem, simply wrap your conditions in curly braces.
On another note, breaking in this context doesn't do anything. You can only break out of a for-loop, advanced for-loop, while loop, do-while loop, and switch statement. I may have forgotten 1 or 2 scenarios so feel free to remind me!
If there is more then one line inside a "if" or "else" you need to enclose those statements with { }. This should work now.
import java.util.Scanner;
import javax.lang.model.util.ElementScanner14;
class mudit {
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
System.out.print("Enter!!!");
final char n = input.next().charAt(0);
art :
if ((n >= 'a' && n <= 'z' ) || (n >= 'A' && n <= 'z')) {
System.out.println(n + " is an alphabet.");
dart :
if ( n == 'a' || n == 'e' || n == 'i' || n == 'o' || n == 'u' || n == 'A' || n == 'E' || n == 'I' || n == 'O' || n == 'U') {
System.out.println("VOWEL");
break dart;
} else {
System.out.println("CONSONANT");
break dart;
}
}
else if ( n * 1 == n)
System.out.println(n + " is a numerical value.");
else
System.out.println("Something else");
input.close();
}
}

Automaton DFA implementation not working using Java

I'm studying right now, at my university, DFA and NFA automatons and how to implement some of them using Java code.
I am having some trouble with this exercise: we have 4 different laboratory turns (T1, T2, T3 and T4) and we need to write code in order to recognize if a particular string (composed of the university badge number of a student and his name, e.g., 123321Johnson) corresponds to T2 or T3.
We know that:
T1 is the turn of the ones who have an odd badge number and surname between "A" and "K"
T2 is the turn of even badge numbers and surnames between "A" and "K"
T3 is the turn of odd badge numbers and surnames between "L" and "Z"
T4 is the turn of even badge numbers and surnames between "L" and "Z"
We also know that the string has to be composed of at least one number and at least one letter.
E.g., the automaton has to accept "1232324Gac" or "1232323Lum" but not "121234Lum" or "121233Gac".
Here's the code I wrote:
import java.util.Scanner;
public class Es3 {
static Scanner sc = new Scanner(System.in);
String s = sc.next();
public static boolean scan(String s)
{
int state = 0;
int i = 0;
while (state >= 0 && i < s.length()) {
final char ch = s.charAt(i++);
switch (state) {
case 0:
if (ch >= 0 && ch <= 9)
state = 1;
else
state = -1;
break;
case 1:
if (ch >=0 && ch <=9)
state = 1;
else if (ch >='a' && ch <='k')
if ((s.charAt(i--))%2==0)
state = 2;
else
state = -1;
else if (ch >='l' && ch <='z')
if ((s.charAt(i--))%2==1)
state = 3;
else
state = -1;
else
state = -1;
break;
case 2:
if (ch >='a' && ch <='z')
state = 2;
else
state = -1;
break;
case 3:
if (ch >='a' && ch <='z')
state = 3;
else
state = -1;
break;
}
}
return (state == 2 || state == 3);
}
public static void main(String[] args)
{
System.out.println(scan(args[0]) ? "OK" : "NO");
}
}
Obviously, the code is not working, but this is important to show the general purpose of the exercise.
Could someone help me?
The reason your algorithm wasn't working is because you were trying to compare char values to int values, which wouldn't give the anticipated result. Also, when you were checking if a char value was in a certain letter range, you didn't take capital letters into account.
import java.util.Scanner;
public class Es3
{
static Scanner sc = new Scanner(System.in);
String s = sc.next();
public static boolean scan(String s)
{
int state = 0;
int i = 0;
while (state >= 0 && i < s.length()) {
final char ch = s.charAt(i++);
switch (state) {
case 0:
// Compare the char to the char values of the numbers
if (ch >= '0' && ch <= '9')
state = 1;
else
state = -1;
break;
case 1:
// Same here, compare the char to the char values of the numbers
if (ch >= '0' && ch <= '9')
state = 1;
// Check if the char is capital, as well as lowercase
else if ((ch >= 'a' && ch <= 'k') || (ch >= 'A' && ch <= 'K'))
// Convert the char to an int before performing the calculations
if ((Character.getNumericValue(s.charAt(i-1)))%2 == 0)
state = 2;
else
state = -1;
// Check if the char is capital as well
else if ((ch >= 'l' && ch <= 'z') || (ch >= 'L' && ch <= 'Z'))
// Convert from char to int before calculating
if ((Character.getNumericValue(s.charAt(i-1)))%2 == 1)
state = 3;
else
state = -1;
else
state = -1;
break;
case 2:
// Check if the char is capital as well
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
state = 2;
else
state = -1;
break;
case 3:
// Check if the char is capital as well
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
state = 3;
else
state = -1;
break;
}
}
System.out.println("State "+state);
return (state == 2 || state == 3);
}
public static void main(String[] args)
{
System.out.println(scan(args[0]) ? "OK" : "NO");
}
}
I think the code above should do what you’re trying to do.

I'm facing an issue with control structures

My problem is with output of my code. When I enter 20, the output must be weird, but I am getting not weird. Same with the value 18.
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 2 && n >= 5){
ans="Not weird";
} else if(n <= 6 && n >= 20){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}
the output must be weird,but i am getting not weird
Because, if(n%2 == 1) return false and fall to else block where
if(n <= 2 && n >= 5) is `false`
and
else if(n <= 6 && n >= 20) is also `false`
So, again falls to else block. You probably change
if(n <= 2 && n >= 5)
to
if(n >= 2 && n <= 5)
and
else if(n <= 6 && n >= 20)
to
else if(n >= 6 && n <= 20)
Otherwise, they will never be true and always falls to else.
In your program last else is being executed. Change && (logical AND) to || (logical OR) which will check if number is less than something OR higher than something, instead of checking if something is less or equal 5 AND higher or equal to 20 in the same time as it doesn't have a possibility to evaluate in any case.
I have come up with two solutions and also i see a flaw:
1. if(n%2 == 1) this code can be altered to if(n%2 == 0)
2. The flaw is **(n <= 2 && n >= 5)** . No number can be <2 and >5 at the same time. Try changing that to (n <= 2 || n >= 5) and same goes for (n <= 6 && n >= 20)
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 6 || n >= 20){
ans="Not weird";
} else if(n <= 2 || n >= 5){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}

Read input from user and ignore the spaces between words, converting letters to telephone numbers

I've been trying to figure out how to ignore the blank space/digits/letters by using the character.isDigit & character.isLetter method when the users enters a String.. Can you guys please advise me?
When I tried the input with GETLOAN (Without the space) it works well...
But when I enter a space between e..g. Get Loan, the program shows an error..
public static void main(String[] args) {
String letters;
char phoneDigit;
Scanner kb = new Scanner(System.in);
System.out.println("Enter letters : ");
letters = kb.next();
for (int i = 0; i < 7; i++) {
phoneDigit = letters.charAt(i);
// Using character.isDigit...
if (Character.isDigit(phoneDigit) == true || Character.isLetter(phoneDigit) == true);
{
if (i == 3) {
System.out.println("-");
} //If
if (phoneDigit >= 'A' && phoneDigit <= 'C'
|| phoneDigit >= 'a' && phoneDigit <= 'c') {
System.out.println("2");
} else if (phoneDigit >= 'D' && phoneDigit <= 'F'
|| phoneDigit >= 'd' && phoneDigit <= 'f') {
System.out.println("3");
} else if (phoneDigit >= 'G' && phoneDigit <= 'I'
|| phoneDigit >= 'g' && phoneDigit <= 'i') {
System.out.println("4");
} else if (phoneDigit >= 'J' && phoneDigit <= 'L'
|| phoneDigit >= 'j' && phoneDigit <= 'l') {
System.out.println("5");
} else if (phoneDigit >= 'M' && phoneDigit <= 'O'
|| phoneDigit >= 'm' && phoneDigit <= 'o') {
System.out.println("6");
} else if (phoneDigit >= 'P' && phoneDigit <= 'S'
|| phoneDigit >= 'p' && phoneDigit <= 's') {
System.out.println("7");
} else if (phoneDigit >= 'T' && phoneDigit <= 'V'
|| phoneDigit >= 't' && phoneDigit <= 'v') {
System.out.println("8");
} else if (phoneDigit >= 'W' && phoneDigit <= 'Z'
|| phoneDigit >= 'W' && phoneDigit <= 'z') {
System.out.println("9");
} // If
} // If
} // For loop
} //PSVM
remove the semicolon(;) from here
if (Character.isDigit(phoneDigit) == true || Character.isLetter(phoneDigit) == true);//semicolon
; means end of statement.This means if conditions ended there.The statements under if will always be executed irrespective of what if returns(true or false) so the rest of statements under {} will simply behave as non static blocks
When I tried the input with GETLOAN (Without the space) it works well... But when I enter a space between e..g. Get Loan, the program shows an error..
You are getting error when you enter space because of the reason I specified above as the statements under if will always be executed
If you enter two words separated by a space, e.g. "get loan", the Scanner produces two output elements, i.e. the invocation of kb.next() just returns "get". A second invocation would return "loan". The Scanner class is not the right class to use for your purpose.
Use something like
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
to read from the console.

Converting charAt check 'containing A-Z' to 'not containing A-Z'

I would like to check if a String input contains characters other than alphabets. Below is my current code:
if ((name.charAt(i) >= 'a' && name.charAt(i) <= 'z') ||
((name.charAt(i) >= 'A' && name.charAt(i) <= 'Z')))
How can I change the code such that it functions as check if name.charAt(i) "is not equals to A to Z OR a to z?
Just negate your condition :
if (!((name.charAt(i) >= 'a' && name.charAt(i) <= 'z') || ((name.charAt(i) >= 'A' && name.charAt(i) <= 'Z'))))
String str = "1234";
if(!str.matches("[a-zA-Z]+")){
System.out.println("not contains alphabets");
}else{
System.out.println("contains alphabets");
}
I'll demonstrate a systematic approach to this which can help you in other similar situations. First, to improve readability, extract the char to a local var.
char ch = name.charAt(i);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') ...
Now you can work with this in terms of DeMorgan's laws. To make things easier, I'll declare some helper boolean vars for each part:
boolean a = ch >= 'a',
z = ch <= 'z',
A = ch >= 'A',
Z = ch <= 'Z';
So, we have your original expression as
(a && z) || (A && Z)
We want the negative of that expression:
!(a && z || A && Z)
Let's clean it up. Apply
to get
!(a && z) && !(A && Z)
Then apply
to the inner expressions:
(!a || !z) && (!A || !Z)
Now substitute the original expresions back in, negating <= into >, >= into <:
(ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z')
this is the negated expression you are looking for, cleaned up of any explicit negations.
Instead of comparing characters for upper & lowercase, use Character.isLetter(char c) method as it checks for both the cases.
char[] chars = name.toCharArray();
boolean isAlphabet = true;
for (char c : chars) {
if (!Character.isLetter(c)) {
//if character is not A-Z or a-z
isAlphabet = false;
}
}

Categories