index increment showing dead code why so ?? before adding special character condition it was working fine no dead code was showing and i want to validate special character condition as well.
public class ValidatePhoneNumber {
void validatePhoneNumber(String pNumber) {
// 1st Case - +91 9765463742 have to check for + sign
boolean flag = false;
String specialCharacter = "!##$%^&*()-/`~:<>/?|=.,";
if (pNumber.startsWith("+") && pNumber.length() == 14) {
for (int index = 1; index < pNumber.length(); index++) {
if ((Character.isDigit((pNumber.charAt(index))) || Character.isSpaceChar((pNumber.charAt(index))))
&& (!(specialCharacter.contains(Character.toString(pNumber.charAt(index)))))
&& (!(Character.isLetter(pNumber.charAt(index))))) {
flag = true;
}
else
System.out.println(pNumber.charAt(index) + " " + pNumber + " Number is Invalid");
flag = false;
break;
}
if (flag == true) {
System.out.println("Number " + pNumber + " is Valid");
}
}
public static void main(String[] args) {
ValidatePhoneNumber phoneNumber = new ValidatePhoneNumber();
phoneNumber.validatePhoneNumber("+91 975644#742");
phoneNumber.validatePhoneNumber("09765463742");
The problem is because of the following break statement which will break the for loop right after the first iteration and therefore index++ will never get an opportunity to run:
else
System.out.println(pNumber.charAt(index) + " " + pNumber + " Number is Invalid");
flag = false;
break;
You should write it as:
void validatePhoneNumber(String pNumber) {
// 1st Case - +91 9765463742 have to check for + sign
boolean flag = false;
int index;
String specialCharacter = "!##$%^&*()-/`~:<>/?|=.,";
if (pNumber.startsWith("+") && pNumber.length() == 14) {
for (index = 1; index < pNumber.length(); index++) {
if (!(Character.isDigit(pNumber.charAt(index)) || Character.isSpaceChar(pNumber.charAt(index)))
&& (specialCharacter.contains(Character.toString(pNumber.charAt(index)))
|| Character.isLetter(pNumber.charAt(index)))) {
flag = true;
break;
}
}
} else {
flag = true;
}
if (!flag) {
System.out.println("Number " + pNumber + " is Valid");
} else {
System.out.println(pNumber + " Number is Invalid");
}
}
Note that I've moved System.out.println(pNumber.charAt(index) + " " + pNumber + " Number is Invalid"); out of the loop so that this message gets printed only once.
Test code:
ValidatePhoneNumber phoneNumber = new ValidatePhoneNumber();
phoneNumber.validatePhoneNumber("+91 975644#742");
phoneNumber.validatePhoneNumber("+91 9765463742");
Output:
+91 975644#742 Number is Invalid
Number +91 9765463742 is Valid
Related
Have a task to get N numbers from console, find the longest and the shortest ones and their length. The task is not difficult and works correctly, but I decided to make a check, if the console input corresponds the conditions of the task:
Are there only Integer numbers.
Are the exactly N numbers, not more/less.
I decided to write a boolean method isInputCorrect(), which would take the Scanner and check if the input is correct, but it doesn't work correctly.
public static void main(String[] args) {
int n = 5;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Hello, please enter " + n + " integer numbers:");
while (!isInputCorrect(sc,n)){
System.out.println("Wrong! Try again:");
sc.next();
}
} while (!isInputCorrect(sc, 5));
String scLine = sc.nextLine();
String[] arr = scLine.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isInputCorrect(Scanner sc, int n){
boolean flag = true;
for (int i = 0; i < n; i++){
if (sc.hasNextInt()){
sc.next();
}else {
flag = false;
break;
}
}
return flag;
}
EDIT
This code still doesn't work. I realize, that the problem is in isDigit(). And exactly in regular conditions in last if statement. It is something like this:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
This method takes the console input as a string, then it checks, how many numbers(strings) does it contain, are there any negative numbers and so on. But it can be applied only for substrings(words without whitespace). In my case it can be applied to arr[i].
So I modified it to split String into array[] and tried to check every single element. I've got:
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
but it returnes true even when input is:
1 3213 w 15 3
I can't understand, what is the problem? The full code is:
public static void main(String[] args) {
int n = 5;
boolean validInput = false;
String input;
do {
System.out.println("Please enter " + n + " integer numbers:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
if (isDigit(input, n)) {
validInput = true;
} else {
System.out.println("Wrong input! Try again: ");
}
}
while (!validInput);
String[] arr = input.split("\\s+");
String maxLengthNum = arr[0];
String minLengthNum = arr[0];
for (int i = 1; i < arr.length; i++){
if (maxLengthNum.length() < arr[i].length()){
maxLengthNum = arr[i];
}
if (minLengthNum.length() > arr[i].length()){
minLengthNum = arr[i];
}
}
String equalMaxNum = "";
String equalMinNum = "";
int countMax = 0;
int countMin = 0;
for (String s : arr){
if (maxLengthNum.length() == s.length()){
countMax += 1;
equalMaxNum += s + " ";
}
if (minLengthNum.length() == s.length()){
countMin += 1;
equalMinNum += s + " ";
}
}
if (countMax > 1){
System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
}
else {
System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
}
if (countMin > 1){
System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
}
else {
System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
}
}
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else {
for (String s : arr) {
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")) {
flag = true;
}
} else if (s.matches("[0-9]*")) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
SOLVED
Thanks to everybody, your help was really usefull. I finally found the problem
It was in isDigit() method. It was checking out every element of array, and switched a flag according to the last result. I wrote "break" to stop the further checking if there was at least one false flag in loop.
public static boolean isDigit (String input, int n){
String[] arr = input.split("\\s+");
boolean flag = false;
if (arr.length != n){
flag = false;
}
else{
for (String s: arr){
if (s.startsWith("-")) {
if (s.substring(1).matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
else {
if (s.matches("[0-9]*")){
flag = true;
}
else {
flag = false;
break;
}
}
}
}
return flag;
}
You may use regular expressions to verify that the input contains only integer numbers:
int n = 5;
// ... your current code
String scLine = sc.nextLine();
if (!scLine.matches("\\d+(?:\\s+\\d+)*")) {
throw new IllegalArgumentException("input contained non-integers");
}
String[] arr = scLine.split("\\s+");
if (arr.length != n) {
throw new IllegalArgumentException("found " + arr.length + " number inputs but expected " + n + ".");
}
you can check if input string has only numbers as below
public boolean isDigit(String input) {
if (input == null || input.length() < 0)
return false;
input = input.trim();
if ("".equals(input))
return false;
if (input.startsWith("-")) {
return input.substring(1).matches("[0-9]*");
} else {
return input.matches("[0-9]*");
}
}
EDIT:
allowing user to re-enter untill valid number is entered
boolean validInput = false;
do
{
System.out.println("Enter the number ");
// get user input
String input sc.nextLine();
if(isDigit(input))
validInput = true;
else
System.out.println("Enter valid Number");
}
while (!validInput );
In this code, the user gets 3 guesses of letters in the name and then the user can guess the actual name. Does anybody know how to fix this code so that if the user enters "m" they'll still be told where its position is even though the name starts with a capital M?
//import java scanner
import java.util.Scanner;
//declare variables
class Main
{
Scanner scan = new Scanner(System.in);
String name = "Matt";
String guessedName;
int nameLength, position, guesses;
char guess;
//method for guessLetter
public void guessLetter()
{
nameLength = name.length();
System.out.println("The name I am thinking of is " + nameLength + " letters long.\nYou will be able to pick three letters and I'll let you know the location letter occurs in the name. Then you can guess the name.");
guesses = 3;
while(guesses >= 1)
{
System.out.println("Guess one letter?");
guess = scan.nextLine().charAt(0);
letters();
guesses -= 1;
}
}
//method for guess Name
public void guessedName()
{
System.out.println("Guess what you think the name is?");
guessedName = scan.nextLine();
if(guessedName.equalsIgnoreCase(name)){
System.out.println("Correct, that is the name!");
}
else{
System.out.println("Wrong, that is not the correct name.");
System.out.println("The name is " + name + ".");
}
}
//method for letters
public void letters()
{
if(name.indexOf(guess)>-1)
{
position = name.indexOf(guess);
System.out.println(guess + " is at position " + position + ".");
}
else
{
System.out.println(guess + " is not in the name!");
}
}
public static void main(String[] args)
{
Main prog = new Main ();
prog.guessLetter();
prog.guessedName();
}
}
Just check for the character in a loop. That's what indexOf does. Something like this.
public void letters() {
String[] chars = name.split("");
for (int i = 0; i < chars.length; i++) {
if(chars[i].equalsIgnoreCase(guess)) {
System.out.println(guess + " is at position " + i + ".");
return;
}
}
System.out.println(guess + " is not in the name!");
}
If you want a comparison that ignores case, but you don't want to convert the name, then you need to test twice - once for each case.
if (name.indexOf(guess) > -1) {
position = name.indexOf(guess);
System.out.println(guess + " is at position " + position + ".");
}
else {
if (Character.isUpperCase(guess)) {
guess = Character.toLowerCase(guess);
}
else {
guess = Character.toUpperCase(guess);
}
if (name.indexOf(guess) > -1) {
position = name.indexOf(guess);
System.out.println(guess + " is at position " + position + ".");
}
else {
System.out.println(guess + " is not in the name!");
}
}
Basically the above code does the following:
If guess matches a letter in name then we are done.
If not, then check the case of guess.
If guess is upper case, convert it to lower case.
If guess is lower case, convert it to upper case.
Recheck to see whether the converted guess matches a letter in name.
Refer to class java.lang.Character
Alternatively, you can use regular expressions.
Pattern pattern = Pattern.compile(String.valueOf(guess), Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(name);
if (matcher.find()) {
position = matcher.start();
System.out.println(guess + " is at position " + position + ".");
}
else {
System.out.println(guess + " is not in the name!");
}
I need help in designing a for loop that returns the name if found and if it is not found it returns the requested name as not found. I need to do this without repeating the not found loop multiple times.
I have tried various if, else if, and else statements. I have also tried a do while loop inside of the for loop and also tried to do the not found statement outside of the loop
String[] values = new String[12];
int name = 1;
// Initialize Scanner
java.util.Scanner input = new java.util.Scanner(System.in);
// Create loop for name input
for (int i = 0; i < values.length; i++)
{
System.out.print("Enter in " + " the name of friend " + name++ + ": ");
values[i] = new String(input.next());
if (values[i].equalsIgnoreCase("zzzz"))
{
break;
}
}
// Create loop for name output
System.out.println("\n" + "The names of your friends are: ");
for (int i = 0; i < values.length; i++)
{
if (values[i].equalsIgnoreCase("zzzz"))
{
break;
}
else
{
System.out.println(values[i]);
}
}
// Search for the name
boolean found = false;
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
for(int i = 0;i < values.length && !found;++i)
{
if (find.equalsIgnoreCase(values[i]))
{
System.out.println("\n" + "Your friend " + find + " was found");
found = true;
break;
}
else if (find != values[i] && (found = false))
{
System.out.println("\n" + "Your friend " + find + " was not found" );
break;
}
}
}
}
I expect the not found statement to not be reiterated multiple times through the loop until the actual name is found. If the name does not exist in the array, it should search through the whole array and return that it was not found.
See my attempt. I have cast all elements to lower case whilst we iterate through the array to ensure we don't miss a match. For example if we searched for
"tom" and in the array we had "Tom" the match would be missed.
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
boolean foundFlag = false;
String[] values = new String[12];
//Populate array
for(int i = 0, x = 1; i < values.length; i ++, x ++)
{
System.out.print("Enter name of friend " + x + ": " );
String name = input.next();
values[i] = name;
}
//Output all elements of the array
System.out.println("\n" + "The names of your friends are: ");
for(String x : values)
{
System.out.println(x);
}
//Find a friend
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
//Iterate through array and check if Friend inside.
for(int i = 0; i < values.length; i ++)
{
if(values[i].toLowerCase().equals(find.toLowerCase()))
{
foundFlag = true;
break;
}
}
//If friend in the array flag will be True, else flag will remain false.
if (foundFlag)
{
System.out.println("Friend " + find + " found");
}
else
{
System.out.println("Friend " + find + " not found");
}
}
}
just create a function to do your searching:
public boolean findName(String[] items, String name) {
if (items == null || items.length == 0 || name == null || name.trim().isEmpty()) return false;
for(int i = 0; i < items.length; i++) {
if (items[i].equalsIgnoreCase(name.trim())) {
return true;
}
}
return false;
}
Then where ever you need to find a friend:
boolean exists = findName(values, "Foo Bar");
if (exists) {
System.out.println("Friend exists");
} else {
System.out.println("Friend does not exists");
}
You can use also java 8 streams :
boolean found = Stream.of(values)
.anyMatch(value -> value.equalsIgnoreCase(name));
try to use this code :
// Search for the name
boolean found = false;
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
for(int i = 0;i < values.length && !found;++i)
{
if (find.toLowerCase().equals(values[i].toLowerCase()))
{
System.out.println("\n" + "Your friend " + find + " was found");
found = true;
break;
}
}
if(!found){
System.out.println("\n" + "Your friend " + find + " was not found" );
}
}
Here is the code for a guessing game I have made. My counter in not increasing past 1. I am passing the parameters choice and generatedNumber from a seperate controller class. Should the do while loop be in the controller class?
public String startGuessingGame(int choice, int generatedNumber) {
int count = 0;
final int attempts = 4;
String result = null;
do {
count++;
if (choice == generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed the correct number!";
}
else if (choice > 50 || choice < 0) {
result = "Out of range. "
+ "\nPlease choose a number between 1 and 50.";
}
else if (choice > generatedNumber) {
result = "Attempt " + count + " "
+ " - You have guessed too high!";
}
else if (choice < generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed too low!";
}
if (count == attempts) {
result = "You are out of guesses! The number was " + generatedNumber;
}
}
while(count < attempts);
return result;
}
}
There is no loop here.
You're looking for something like while(count < attempts).
Try this:
Incrementing the counter at the end before the while condition:
do{
...
if (count == attempts) {
result = "You are out of guesses! The number was " + generatedNumber;
}
count++;
}while(count < attempts);
return result;
...
You need to make count a class variable (member) of your controller class and have your do/while loop in that class so that the startGuessingGame only handles the validation of the user choice. Something like this but the code is far from complete
public class SomeControllerClass() {
final int attempts = 4;
int count = 0;
public void someMethod() {
int choice = 0;
do {
choice = getChoice();
count++;
String text = otherClass.startGuessingGame(choice, generatedNumber);
while (count < attempts);
}
and the method only does validation
public String startGuessingGame(int choice, int generatedNumber) {
String result = null;
if (choice == generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed the correct number!";
} else if (choice > 50 || choice < 0) {
//and so on
return result;
}
Hi i was trying to create a mock database search and, though it works, whenever i enter an input that is not part of the database, it creates an Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 on line 23. I dont know what else to do as i see no error in the code.
import java.util.*;
public class Database {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
String[] names = new String[4];
boolean found = false;
int i = 0;
names[0] = "Thor";
names[1] = "Ben";
names[2] = "Zoe";
names[3] = "Kate";
System.out.println("Enter Player Name");
String input = scan.nextLine();
while(found != true){
if(input.equals(names[i])){
System.out.println(input + " has been found");
found = true;
} else {
i = i+1;
}
if(i == 3 && found == false){
System.out.println(input + " was not found");
}
}
}
}
You are not leaving the loop after you print that input + " was not found".
Therefore the next iteration of the loop throws ArrayIndexOutOfBoundsException.
You should leave the loop after you finish testing the entire array.
change
while(found != true){
to
while(!found && i < names.length){
Actually you can move the if statement that tests whether the input wasn't found to be after the loop :
while(!found && i < names.length) {
if(input.equals(names[i])){
System.out.println(input + " has been found");
found = true;
} else {
i = i+1;
}
}
if(!found){
System.out.println(input + " was not found");
}
An even better alternative would be to use a for loop :
for (int i = 0; i < names.length && !found; i++) {
if(input.equals(names[i])){
System.out.println(input + " has been found");
found = true;
}
}
if(!found){
System.out.println(input + " was not found");
}
if your input doesn't matches the value of i will keep on incrementing and your length of an array is 4. Obviously ArrayindexoutofException.
To avoid you need to consider the array length also.
Change your while loop to
while (found != true) {
if (input.equals(names[i])) {
System.out.println(input + " has been found");
found = true;
} else {
i = i + 1;
}
if (i == 4 && found == false) { //changed here
System.out.println(input + " was not found");
//or found == true;
break; //and here
}
}
You need to quit the loop if THIS condition is true
i == 4 && found == false
and to actually quit, you must "break" the while condition
found != true
You can do this by setting found=true (but that's not semantically correct) or add the break instruction.
Here is an alternative solution to your while loop:
while (!found && i<4)
if (input.equals(names[i++]))found = true;
System.out.println(input+(found?" has been":" was not")+" found");
You can simply change to
while(i < names.length)
and forget the additional boolean variable. Since you want to keep iterating i until you find the solution, the stop condition will be the max i. When you do find your solution, you can simply breakthe while statement:
if (input.equals(names[i])) {
System.out.println(input + " has been found");
break;
}