Rules for valid Indian mobile number:
The number should contain 10 or 11 or 12 digits.
If it contains 10 digits, then the first digit should be 7 or 8 or 9.
If it contains 11 digits, then the first digit should be 0 and the second rule followed.
If it contains 12 digits, then the first two digits should be 91 and the second rule followed.
For test case:
1
881906355596
this code should produce Invalid but it is showing Valid.
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int t=scan.nextInt();
while((t--)!=0){
String s = scan.next();
int length = s.length();
if((length==10) &&((s.charAt(0)=='7')||(s.charAt(0)=='9')||(s.charAt(0)=='8')))
System.out.println("Valid");
else if((length==11) &&(s.charAt(0)=='0')&&(s.charAt(0)=='7')||(s.charAt(0)=='9')||(s.charAt(0)=='8'))
System.out.println("Valid");//code
else if((length==12) &&(s.charAt(0)=='9')&&(s.charAt(1)=='1'))
System.out.println("Valid");//code
else System.out.println("Invalid");
}
}
}
Your second and third conditions are wrong.
The second condition incorrectly returns true for your 881906355596 input.
You'll see why if you arrange it as follows:
else if (
(length==11) && // false &&
(s.charAt(0)=='0') && // false &&
(s.charAt(0)=='7') || // false ||
(s.charAt(0)=='9') || // false ||
(s.charAt(0)=='8') // true
) // equals true
It should be:
else if (length == 11 && s.charAt(0) == '0' && (s.charAt(1) == '7' || s.charAt(1) == '9' || s.charAt(1) == '8'))
The third condition should be:
else if (length == 12 && s.charAt(0) == '9' && s.charAt(1) == '1' && (s.charAt(2) == '7' || s.charAt(2) == '9' || s.charAt(2) == '8'))
You missed one whole ()
else if((length==12) &&((s.charAt(0)=='9')&&(s.charAt(1)=='1')))
Related
Why is the first if statement always true?
private String setDepartment (){
int code = Integer.parseInt(JOptionPane.showInputDialog("Enter The Department Code:\n" +
"1:Sales\n" +
"2:Development\n" +
"3:Accounting\n" +
"4:None"));
/*Why this if statement is always true? How do i solve it? */
if (code !=1 || code !=2 || code !=3 || code !=4)
{
JOptionPane.showMessageDialog(null, "Invalid Number.Enter a number between 1-4");
setDepartment();
}
if (code==1){
return "Sales";
}
else if (code==2){
return "Development";
}
else if (code==3){
return "Accounting";
}
else
return "";
}
Replace || with &&:
if (code !=1 && code !=2 && code !=3 && code !=4)
You need to use AND instead of OR.
If the user enters 1 then it's automatically different than 2,3 and 4.
You can therefore use :
if (code !=1 && code !=2 && code !=3 && code !=4)
OR
if (code ==1 || code ==2 || code ==3 || code ==4)
From first principles, picking code = 1:
code !=1 || code !=2 || code !=3 || code !=4
= 1 !=1 || 1 !=2 || 1 !=3 || 1 !=4
= false || true || true || true
= true
You probably meant && rather than ||.
Because at any point of time code value would be any of 1-4. And 3 of 4 conditions would always be true. Change your if condition to
If( !( code ==1 || code == 2 || code == 3 || code == 4))
I need to compare char values with set char values 'g' 'c' 'a' 't'(lower and upper case), for i want only those values to be entered. I can not seem to get certain cases of my input validation working.
f in the below strings can stand for any length of string that is not characters g,c,a,t.
The string "fffffff" keeps in the loop.
The string "fgf" keeps in the loop.
However, i want the strings, "fffffg" or "gfg" to exit the loop, and they are not doing so.
The actual purpose of the exercise, to take a user input of nucleotides like g,c,a,t like the one's in DNA, and convert them into the complementary string of RNA. G is complement to C and vice versa. A is complement to U(the T is replaced with U) and vice versa.
So if the string is "gcat", the response for RNA should be "cgua".
import java.text.DecimalFormat;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import java.util.Random;
//getting my feet wet, 1/13/2015, program is to take a strand of nucleotides, G C A T, for DNA and give
//the complementary RNA strand, C G U A.
public class practiceSixty {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String input = null;
boolean loopControl = true;
char nucleotide;
while(loopControl == true)
{
input = JOptionPane.showInputDialog(null, " Enter the sequence of nucleotides(G,C,A and T) for DNA, no spaces ");
for(int i = 0; i < input.length(); i++)
{
nucleotide = input.charAt(i);
if(!(nucleotide == 'G' || nucleotide == 'g' || nucleotide == 'C' || nucleotide == 'c' || nucleotide == 'A' || nucleotide == 'a' || nucleotide == 'T' || nucleotide == 't' ))
{
loopControl = true;
}
else if(nucleotide == 'G' || nucleotide == 'g' || nucleotide == 'C' || nucleotide == 'c' || nucleotide == 'A' || nucleotide == 'a' || nucleotide == 'T' || nucleotide == 't' )
{
loopControl = false;
System.out.println(nucleotide);
}
}
}
JOptionPane.showMessageDialog(null, "the data you entered is " + input);
StringBuilder dna = new StringBuilder(input);
for(int i = 0; i < input.length(); i++)
{
nucleotide = input.charAt(i);
if(nucleotide == 'G' || nucleotide == 'g' )
{
dna.setCharAt(i, 'c');
}
else if( nucleotide == 'C' || nucleotide == 'c')
{
dna.setCharAt(i, 'g');
}
if(nucleotide == 'A' || nucleotide == 'a')
{
dna.setCharAt(i, 'u');
}
else if(nucleotide == 'T' || nucleotide == 't')
{
dna.setCharAt(i, 'a');
}
}
JOptionPane.showMessageDialog(null, "the DNA is , " + input + " the RNA is " + dna);
}
});
}
}
You could do your check with a single regular expression, and then just use a do/while loop to keep prompting for input until the user enters something valid.
do {
input = JOptionPane.showInputDialog(
null, " Enter the sequence of nucleotides(G,C,A and T) for DNA, no spaces ");
} while (!input.matches("[GCATgcat]+"));
The regular expression will match any input that consists of one or more letters of the 8 shown. When you don't get a match, the loop repeats.
I'm super new to programming so I would love to keep this simple. The compiler accepts my code, but when I run the program and type in for example the letter A I just get a ton of errors. I tried earlier using String letter instead of int letter, but I just got compiler errors stating I couldn't convert Strings to characters or something. I'm really confused and could use a quick explanation and fix so I can get a number back. Here's my code:
import java.util.Scanner;
import java.lang.String;
public class PhoneAlgorithm {
public static void main(String[] args){
int digit = -1;
Scanner in;
in = new Scanner(System.in);
System.out.print("Enter an uppercase letter to find out the corresponding digit on a telephone: ");
int letter;
letter = Integer.parseInt(in.next());
if (letter == 'A' || letter == 'B' || letter == 'C') {
digit = 2; }
else if (letter == 'D' || letter == 'E' || letter == 'F') {
digit = 3; }
else if (letter == 'G' || letter == 'H' || letter == 'I') {
digit = 4; }
else if (letter == 'J' || letter == 'K' || letter == 'L') {
digit = 5; }
else if (letter == 'M' || letter == 'N' || letter == 'O') {
digit = 6; }
else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S') {
digit = 7; }
else if (letter == 'T' || letter == 'U' || letter == 'V') {
digit = 8; }
else if (letter == 'W' || letter == 'X' || letter == 'Y' || letter == 'Z') {
digit = 9; }
else if (letter >= 'a' && letter >= '3') {
System.out.print("You did not enter a valid uppercase letter. Try again!");
}
if (digit != -1) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}
}
}
When you use parseInt(str), you will get an Exception if the parameter str cannot be converted to an integer.
You must use char, since you are comparing the input with single characters:
char letter;
letter = in.nextLine().charAt(0);
str.charAt(index) Returns the char value at the specified index.
I have modified your code, I guess this is what you are looking for..
import java.util.Scanner;
public class Try {
public static void main(String[] args) {
//declarations
char letter;
int digit=0;
// Asking the user to enterstring
System.out.println("Enter the string");
String enterString;
//creating a scanner object and reading the string
Scanner input = new Scanner(System.in);
enterString= input.next();
System.out.println("Entered string is "+enterString);
int temp=0;
for(int i=0;i<enterString.length();i++){
letter=(char)enterString.codePointAt(i);
if (letter == 'A' || letter == 'B' || letter == 'C') {
digit = digit*10+2; }
else if (letter == 'D' || letter == 'E' || letter == 'F') {
digit = digit*10+3; }
else if (letter == 'G' || letter == 'H' || letter == 'I') {
digit = digit*10+4; }
else if (letter == 'J' || letter == 'K' || letter == 'L') {
digit = digit*10+5; }
else if (letter == 'M' || letter == 'N' || letter == 'O') {
digit = digit*10+6; }
else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S') {
digit = digit*10+7; }
else if (letter == 'T' || letter == 'U' || letter == 'V') {
digit = digit*10+8; }
else if (letter == 'W' || letter == 'X' || letter == 'Y' || letter == 'Z') {
digit = digit*10+9; }
else if (letter >= 'a' && letter >= '3') {
System.out.print("You did not enter a valid uppercase letter. Try again!");
}
/*if (digit != 0) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}*/
}
if (digit != 0) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}
}
}
I have a hangman game created in java. I want to create a simple function that will check if the word input has white space and/or special characters.
I've found the functions String.replaceAll(), but I haven't been able to dig up a premade function that returns a boolean value for if there are special charactors and/or white space.
Is there a function out there already? Or at least a simpler way of specifying no white space or special characters other than doing the following?
public void checkWord()
{
boolean flag = false;
for(int i=0;i<wordArray.length;i++)
{
if(wordArray[i] == '1' || wordArray[i] == '2' || wordArray[i] == '3' || wordArray[i] == '4' || wordArray[i] == '5' || wordArray[i] == '6' || wordArray[i] == '7' || wordArray[i] == '8' || wordArray[i] == '9' )
{
flag = true;
}
}
if(flag == true)
{
System.out.println("Invalid characters used in the word");
System.exit(0);
}
}
The function is getting dense, and I've only covered digits. Thoughts?
You can use a simple regular expression:
public boolean isValidWord(String w) {
return w.matches("[A-Za-z]*");
}
Explanation of the regex:
[A-Za-z] - capital or lowercase letter
* - zero or more
More info on regexes: http://www.regular-expressions.info/
I am trying to calculate an arithmetic expression, which is entered as a string (for example, ( 5+4*5-1/8 ), which will give the result 3). I enter an expression and convert it into an array. First; the result will start with the first element and it will change in the loop. But the problem is operator precedence. How can I use the operator presedence in a loop? Here is my code:
import java.util.Scanner;
public class HesapMakinesi {
private char value[];
private int count;
private Scanner str = new Scanner(System.in);
private String process;
HesapMakinesi() {
System.out.print("Enter the process ");
process = str.next();
//System.out.println(islem);
Initializer(process);
}
private void Initializer(String process) {
count = process.toCharArray().length;
value = new char [count];
int i;
System.arraycopy(process.toCharArray(), 0, value, 0, count);
//System.out.println(value);
if(value[0]=='-' || value[0]=='+' || value[0]=='/' || value[0]=='*' || // A process cannot start with an operator
value[count-1]=='-' || value[count-1]=='+' || value[count-1]=='/' || value[count-1]=='*') {
System.out.println("You have entered a wrong process.Please enter again!!!");
System.out.print("Enter the process: ");
process = str.next();
Initializer(process);
}
for(i=0; i<count; i++) { // A process cannot include a character except operators
if( value[i]!='+' && value[i]!='-' && value[i]!='*' && value[i]!='/' && value[i]!='(' && value[i]!=')' && !Character.isDigit(value[i]) ) {
System.out.println("You have entered a wrong process.Please enter again!!!");
System.out.print("Enter the process: ");
process = str.next();
Initializer(process);
}
}
for(i=0; i<count-1; i++) { // A process cannot have operators sequantially
if( !Character.isDigit(value[i]) && !Character.isDigit(value[i+1]) ) {
if( (value[i] == '+' && value[i+1] == '+' ) || (value[i] == '+' && value[i+1] == '-' ) || (value[i] == '+' && value[i+1] == '*' ) ||
(value[i] == '+' && value[i+1] == '/' ) ) {
System.out.println("You have entered a wrong process.Please enter again!!!");
System.out.print("Enter the process: ");
process = str.next();
Initializer(process);
}
else if( (value[i] == '-' && value[i+1] == '+' ) || (value[i] == '-' && value[i+1] == '-' ) || (value[i] == '-' && value[i+1] == '*' ) ||
(value[i] == '-' && value[i+1] == '/' ) ) {
System.out.println("You have entered a wrong process.Please enter again!!!");
System.out.print("Enter the process: ");
process = str.next();
Initializer(process);
}
else if( (value[i] == '*' && value[i+1] == '+' ) || (value[i] == '*' && value[i+1] == '-' ) || (value[i] == '*' && value[i+1] == '*' ) ||
(value[i] == '*' && value[i+1] == '/' ) ) {
System.out.println("You have entered a wrong process.Please enter again!!!");
System.out.print("Enter the process: ");
process = str.next();
Initializer(process);
}
else if( (value[i] == '/' && value[i+1] == '+' ) || (value[i] == '/' && value[i+1] == '-' ) || (value[i] == '/' && value[i+1] == '*' ) ||
(value[i] == '/' && value[i+1] == '/' ) ) {
System.out.println("You have entered a wrong process.Please enter again!!!");
System.out.print("Enter the process: ");
process = str.next();
Initializer(process);
}
}
}
//sCount();
}
/*private void Count(){
double result,temp;
int i;
for(i=0; i<count; i++) {
if( value[i]!= )
}
}*/
}
That's not how you do it. You need to parse the expression before evaluating it. I suggest you to read the Shunting-yard algorithm.
Following on from my comment... If you're dealing with a simple expression where you can only have numbers and signs +-/* then you can have a simple approach:
split your expression by lowest precedence operators first (+-) remembering the signs.
Compute each piece - as now the precedence isn't important, since everything is of the same level
sum those computed pieces taking into account the sign of the piece from step 1.
In your example, you'll end up with something like this:
(Split by +-) three pieces: (1) 5; (2) 4*5 with sign +; (3) 1/8 with sign -
Compute each of the three pieces: (1) 5; (2) 20; (3) 0.125
Sum the three pieces with their respective signs: 5+20-0.125 = 24.875