string length, number of capitals, and number of numbers in a string - java

I want to check if a string has 8 or more characters, and if it has 1 capital letter and 1 number.
This is my code:
import java.util.Scanner;
public class PasswordTest
{
public static void main(String[] args)
{
Scanner keyb = new Scanner(System.in);
System.out.printf("Enter a password to be checked: \n");
String passwordInput = keyb.next();
int numberCharaters = passwordInput.length();
int numberCount = 1;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
int numberNumbers = numberCount - 1;
int captialCount = 1;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = 'A'; c <= 'Z'; c++)
{
if (passwordInput.charAt(i) == c)
{
captialCount++;
}
}
}
int numberCaptials = captialCount - 1;
if (numberCharaters >= 8 && numberNumbers >= 1 && numberCaptials >= 1)
{
String strongEnough = "Password is strong enough.";
System.out.println(strongEnough);
}
else
{
String strongEnough = "Password is not strong enough.";
System.out.println(strongEnough);
}
}
}
and this is the error message I'm getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:658)
at passwordtest.main(passwordtest.java:23)
My input was: Test1
What am I doing wrong? I've been trying to figure out where the java.lang.StringIndexOutOfBoundsException: comes from.

Your program has some mistakes.
You should have initialized numberCount to 0 to avoid having to subtract later, and avoid having to create another variable. Also the error you're getting is because of the <=, since there is no string element = to the length of the string, i.e index is from 0 to length - 1.
int numberCount = 0;
for (int i = 0; i < numberCharaters; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
Then, for the capital count you made the same mistake, I would also take into account the advice in the comments to improve the loops.

You are making a minor mistake.
Length = Actual number of elements(characters).
Index = starts from 0 and ends at length-1.
Your code should be look like this:
import java.util.Scanner;
public class PasswordTest
{
public static void main(String[] args)
{
Scanner keyb = new Scanner(System.in);
System.out.printf("Enter a password to be checked: \n");
String passwordInput = keyb.next();
int numberCharaters = passwordInput.length();
int numberCount = 0;
for (int i = 0; i <= numberCharaters-1; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
int numberNumbers = numberCount - 0;
int captialCount = 0;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = 'A'; c <= 'Z'; c++)
{
if (passwordInput.charAt(i) == c)
{
captialCount++;
}
}
}
int numberCaptials = captialCount - 0;
if (numberCharaters >= 8 && numberNumbers >= 1 &&
numberCaptials >= 1)
{
String strongEnough = "Password is strong enough.";
System.out.println(strongEnough);
}
else
{
String strongEnough = "Password is not strong enough.";
System.out.println(strongEnough);
}
}
}

import java.util.*;
public class password
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.print("enter the password : ");
String s=sc.nextLine();
int l=s.length();
int k=0,k1=0;
if(l>=8)
{
for(int i=0;i<l;i++)
{
if(Character.isLetter(s.charAt(i)))
{
if(Character.isUpperCase(s.charAt(i)))
{
k++;
}
}
else
{
if(Character.isDigit(s.charAt(i)))
{
k1++;
}
}
}
if(k>0&&k1>0)
{
System.out.println("Password is strong enough");
}
else
{
System.out.println("Password shoud contain atleast capital letter and one number");
}
}
else
{
System.out.println("Password shoud contain atleast capital letter,one number and shoud have length of 8 or more");
}
}
}

Related

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index out of bounds

I was getting this error while running the following code. I couldn't find out what was wrong with the code.
As far as I can see, there's some issue with my second character array. But couldn't find out what was wrong. First tried running the last loop before temp_count. Then also tried temp_count±1. Yet, I failed. I have also tried taking different array size. still no luck
import java.util.Scanner;
public class oop2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str=sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[temp_count];
//Converting uppercase to lower case for convenience
for(int i=0; i<str.length(); i++)
{
if (Character.isUpperCase(c[i]))
{
c[i]=(char) (c[i]+32);
}
}
//verifying whether the alphabet exists
for(char x = 'a'; x<='z'; x++)
{
int count=0;
for(int i=0; c[i]!='\0'; i++)
{
if (c[i]==x)
{
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count==0)
{
temp[temp_count]=x;
temp_count++;
}
}
//Verifying whether it's a pangram or not
if (temp_count==0)
{
System.out.println("Pangram");
}
else
{
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for(int i=0; i<temp_count-1; i++)
{
System.out.print(temp[i]+", ");
}
}
sc.close();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str = sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[0];
//Converting uppercase to lower case for convenience
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(c[i])) {
c[i] = (char)(c[i] + 32);
}
}
//verifying whether the alphabet exists
for (char x = 'a'; x <= 'z'; x++) {
int count = 0;
for (int i = 0; c[i] != '\0'; i++) {
if (c[i] == x) {
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count == 0) {
char [] copy = new char[temp.length+1];
for (int i = 0; i < temp.length; i++) {
copy[i]=temp[i];
}
copy[copy.length-1] = x;
temp=copy;
}
}
//Verifying whether it's a pangram or not
if (temp_count == 0) {
System.out.println("Pangram");
} else {
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for (int i = 0; i < temp_count - 1; i++) {
System.out.print(temp[i] + ", ");
}
}
sc.close();
}
}
Blockquote

How to make program re-run without pressing the run button

I am trying to make a program that tests whether or not a password is valid or invalid. After the password is submitted, I would like to give the user a choice to re-run the program(by responding 'y'). Everything works in my code, except when y is pressed at the end, the program stops instead of starting over.
Any help would be greatly appreciated.
import java.util.Scanner;
import java.lang.*;
public class PasswordTest1
{
//Program main method
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String again = "y";
//Promt user to enter input
System.out.print("Enter a password: ");
String password = scan.nextLine();
//If-else to print whether the password is valid
if (checkPassword(password))
{
System.out.println("Valid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
} else {
System.out.println("Invalid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
}
//Program new method
public static boolean checkPassword(String password) {
String again = "y";
while((again == "Y") || (again == "y")){
boolean checkPassword = true;
{
//Make sure password is at least 7 digits
if (password.length() < 8) {
checkPassword = false;
}
else {
//A password has at least 1 digit
int numberOfDigit = 0;
for (int i = 0; i < password.length(); i++) {
if (isDigit(password.charAt(i))) {
if(isDigit(password.charAt(i))){
numberOfDigit++;
}
}
}
if (numberOfDigit < 1) {
checkPassword = false;
}
//Check for lower case
int numberOfLowerCase = 0;
for (int i = 0; i < password.length(); i++) {
if (isLowerCase(password.charAt(i))) {
if(isLowerCase(password.charAt(i))){
numberOfLowerCase++;
}
}
}
if (numberOfLowerCase < 1) {
checkPassword = false;
}
//Check for upper case
int numberOfUpperCase = 0;
for (int i = 0; i < password.length(); i++) {
if (isUpperCase(password.charAt(i))) {
if(isUpperCase(password.charAt(i))){
numberOfUpperCase++;
}
}
}
if (numberOfUpperCase < 1) {
checkPassword = false;
}
//Check for Special Characters
int numberOfSpecialCharacters = 0;
String specialCharactersString = "!##$%^&*()'+,-./:;<=>?[]_{}|";
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if(specialCharactersString.contains(Character.toString(ch))){
numberOfSpecialCharacters++;
}
}
if (numberOfSpecialCharacters < 1) {
checkPassword = false;
}
}
}
return checkPassword;
}
return true;
}
public static boolean isDigit(char ch) {
return (ch <= '9' && ch >= '0');
}
public static boolean isLowerCase (char ch) {
return (ch <= 'z' && ch >= 'a');
}
public static boolean isUpperCase (char ch) {
return (ch <= 'Z' && ch >= 'A');
}
}
I was able to get your code repeat as long as the 'n' key is not pressed. Right now if any key is pressed other than 'n', it will continue.
One problem was that your while loop needs to be inside of your main. The way it is setup, as soon as the checkPassword returns, there is no way for the program to repeat. Asking for y/n had no way to recall the function. You also had an issue with your string comparison, as #PM 77-1 mentioned in the comments. I would recommend keeping the curly brackets spaced out so it is easier to read, you had a pair of brackets that served no purpose.
import java.util.Scanner;
import java.lang.*;
public class PasswordTest1
{
//Program main method
public static void main(String[] args)
{
String again;
String n = "n";
while(true)
{
//Prompt user to enter input
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter a password: ");
String password = scan.nextLine();
//If-else to print whether the password is valid
if (checkPassword(password))
{
System.out.println("\nValid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
else
{
System.out.println("\nInvalid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
if(again.equals(n))
{
break;
}
}
}
//Program new method
public static boolean checkPassword(String password)
{
boolean checkPassword = true;
//Make sure password is at least 7 digits
if (password.length() < 8)
{
checkPassword = false;
}
else
{
//A password has at least 1 digit
int numberOfDigit = 0;
for (int i = 0; i < password.length(); i++)
{
if (isDigit(password.charAt(i)))
{
if(isDigit(password.charAt(i)))
{
numberOfDigit++;
}
}
}
if (numberOfDigit < 1)
{
checkPassword = false;
}
//Check for lower case
int numberOfLowerCase = 0;
for (int i = 0; i < password.length(); i++)
{
if (isLowerCase(password.charAt(i)))
{
if(isLowerCase(password.charAt(i)))
{
numberOfLowerCase++;
}
}
}
if (numberOfLowerCase < 1)
{
checkPassword = false;
}
//Check for upper case
int numberOfUpperCase = 0;
for (int i = 0; i < password.length(); i++)
{
if (isUpperCase(password.charAt(i)))
{
if(isUpperCase(password.charAt(i)))
{
numberOfUpperCase++;
}
}
}
if (numberOfUpperCase < 1)
{
checkPassword = false;
}
//Check for Special Characters
int numberOfSpecialCharacters = 0;
String specialCharactersString = "!##$%^&*()'+,-./:;<=>?[]_{}|";
for (int i = 0; i < password.length(); i++)
{
char ch = password.charAt(i);
if(specialCharactersString.contains(Character.toString(ch)))
{
numberOfSpecialCharacters++;
}
}
if (numberOfSpecialCharacters < 1)
{
checkPassword = false;
}
}
return checkPassword;
}
public static boolean isDigit(char ch)
{
return (ch <= '9' && ch >= '0');
}
public static boolean isLowerCase (char ch)
{
return (ch <= 'z' && ch >= 'a');
}
public static boolean isUpperCase (char ch)
{
return (ch <= 'Z' && ch >= 'A');
}
}

How do I put all those indexes to a char Array?

I can't find a way to be to able to put the encryptedChar to a char Array so that I can out put the message on one line. If anyone could give me a simple solution to the problem or help me in any way that would be great!
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// can get the index without key. DONE
// encrypt message. finish equation.
int encryptKey, encryptedIndex;
int plainLetterIndex = 0;
int loadingBar = 3;
char encryptedChar;
char[] alphaArray = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
String redo, message;
System.out.println("Welcome to the encrypter and decrypter program. The program will take the message");
System.out.println("and either encrypt it or decrypt it. Depending on what you choose to do.");
System.out.println("");
do {
System.out.println("Please enter your message!");
message = sc.nextLine();
message = message.toUpperCase();
System.out.print("Would you like to re-enter your message? (Y/N)");
redo = sc.nextLine();
} while (redo.equals("Y") || redo.equals("y"));
// declaring arrays
char[] messageArray = message.toCharArray();
char[] encryptedMessageArray = new char[messageArray.length];
// asking for key
System.out.println("Please input the 'key' you would like to use to encrypt your message.");
while(true){
try{
encryptKey = Integer.parseInt(sc.nextLine());
break;
} catch (NumberFormatException ignore){
System.out.println("You have entered an incorrect number, please try again!");
}
}
System.out.println(" ");
for (int i = 0; i < messageArray.length; i++) {
//System.out.println(messageArray[i]);
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
//encryptedMessageArray = encryptedChar;
System.out.print(encryptedChar);
}
}
}
sc.close();
}
}
Use an index variable for encryptedMessageArray, increase it everytime you put a character into encryptedMessageArray
int index = 0;
for (int i = 0; i < messageArray.length; i++) {
//System.out.println(messageArray[i]);
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[index] = encryptedChar;
index++;
}
}
}
System.out.println();
System.out.println(encryptedMessageArray);
Add either the encrypted char or the original char to your encryptedMessageArray so you can decrypt the array end get the original message
for (int i = 0; i < messageArray.length; i++) {
boolean isCharEncrypted = false;
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[i] = encryptedChar;
isCharEncrypted = true;
}
}
if (!isCharEncrypted) {
encryptedMessageArray[i] = messageArray[i];
}
}
Here is an alternative solution to avoid the inner for-loop
for (int i = 0; i < messageArray.length; i++) {
char c = messageArray[i];
if (c >= 'A' && c <= 'Z') {
plainLetterIndex = c - 65; //A is ASCII 65
encryptedIndex = (char) (plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[i] = encryptedChar;
} else {
encryptedMessageArray[i] = messageArray[i];
}
}

can someone help me clear these errors

I am trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}
A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.

Numbers to letters in java (like old mobile phones' keyboard)

Just like older mobile phones' keypads work. I should input a string of numbers and the program should print out a text based on those numbers.
e.g: Input: 4448 9666777557777 should output to: ITWORKS.
Here's my code so far but it's not printing out anything. Could you please tell me what's wrong with it and what could've I done better?
Scanner sc = new Scanner(System.in);
String[] letters = {
"0",
"1",
"ABC",
"DEF",
"GHI",
"JKL",
"MNO",
"PQRS",
"TUV",
"WXYZ"
};
System.out.println("Write something.");
String numbers = sc.nextLine();
char[] toChar = numbers.toCharArray();
int count = 0;
for (int index = 0; index < toChar.length; index++) {
if (toChar[index] >= '2' && toChar[index] <= '9') {
if (index > 0 && toChar[index] == toChar[index - 1]) {
count++;
}
else if (count > 0) {
System.out.print(letters[toChar[index - 1] - '0'].charAt(count - 1));
count = 0;
}
}
}
How about this?
import java.util.Scanner;
public class Test {
private static final String[] letters = {
"0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
};
private static char getChar(int digit, int count) {
while (count > letters[digit].length()) {
count -= letters[digit].length();
}
return letters[digit].charAt(count - 1);
}
private static String getString(String input) {
int lastDigit = 0, count = 1;
String result = "";
for (int i = 0; i < input.length(); i++) {
int currentDigit = input.charAt(i) - '0';
if (currentDigit >= 2 && currentDigit <= 9) {
if (lastDigit == 0) {
lastDigit = currentDigit;
} else if (currentDigit == lastDigit) {
count++;
} else {
result += getChar(lastDigit, count);
lastDigit = currentDigit;
count = 1;
}
}
}
return result + getChar(lastDigit, count);
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Write something");
System.out.println(getString(scanner.nextLine()));
}
}
}
I enhanced the problem decomposition. It works for all examples OP has shown so far.
If I understand your intention correctly, count should increment only if current digit is the same as previous:
for (int pos = 1, char c = toChar[0], int count = 1; pos <= toChar.length; pos++, count = 1) {
int n = letters[c - '0'].length;
while (pos < toChar.length && c == toChar[pos] && count < n) {
pos++;
count++;
}
System.out.println(letters[c - '0'].charAt(count - 1));
if (pos < toChar.length - 1) {
c = toChar[++pos];
}
}
This code will help you!
Check this one
public class Denene {
public static String getChar(String cha)
{
String [] chars= {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
String[] strSplit = cha.split(" "); //7777 88 7777 2 66 8
int len=strSplit.length;
char r;
char []ar =new char[len];
for(int i=0;i<len;i++){
String str=strSplit[i];
ar[i]= chars[Integer.parseInt(String.valueOf(str.charAt(0)))].charAt(str.length()-1);
}
return new String(ar);
}
public static void main(String[] args) {
System.out.println("Enter any number .....");
System.out.println(getChar(new Scanner(System.in).nextLine())); //Output : susant
}
}

Categories