I am trying to make a program where a input an email from the user. I have to create a username from the email by deleting the part that comes after ‘@’ and I will display that username to the user. I will ignore the numbers and after a '.' and I will uppercase the next char.
Example :
email = “something.someone.98@gmail.com” ; username = “SomethingSomeone”
email = “something.someone@icloud.com”; username = “SomethingSomeone”
package core_java.JavaExercise.Two;
import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
public class Java_String_Exercise_03 {
public static void main(String[] args) {
Scanner sc = new Scanner(in);
out.print("Enter your email address: ");
String email = sc.next();
String userName = "";
for (int i = 1 ; i < email.length() ; i++) {
Boolean digitCheck = Character.isDigit(email.charAt(i));
if(digitCheck) {
userName += "";
} else if (email.charAt(i) == '@') {
break;
} else if (email.charAt(i) == '.') {
if (Character.isDigit(email.charAt(i+1))) {
userName += "";
} else {
userName += "" + String.valueOf(email.charAt(++i)).toUpperCase();
}
} else {
userName += email.charAt(i);
}
}
out.printf("Your username is %s.", userName);
}
}
I have solved the problem however is there any efficient way of doing this code?
The following condition means that the last value isn't the value you loop for, that isn't a reason to stop looking for you value. As it isn't the first, and not the last, your stop, but haven't search in the middle
else if (arr[arr.length - 1] != target) {
out.printf("Your target = %d has not been found.", target);
break;
}
You need to have search through the whole array before being able to say "not found"
boolean found = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
out.printf("Target = %d has found at the index of %d\n", target, i);
found = true;
break;
}
}
if (!found) {
out.printf("Your target = %d has not been found.\n", target);
}