Resetting character when end is reached java - java

Take following code as base:
for (int i = 0; i < 26; i++)
{
alphabet[i] = (char) ('A'+ i );
}
My question is: -
If 'A' Changes to 'X' how can we achieve the alphabet to reset from the start?
For example XYZABC

Whenever you have something that should "wrap around", have a look at the modulo operator. The basic idea is: you don't want to count from i=0 to 26, but e.g. from i=23 to 49, but only add the modulo-26 value to it.
Instead of starting to count at 23 (which would be kind of 'X' - 'A'), you can directly integrate this offset into your loop:
for (int i = 0; i < 26; i++)
{
alphabet[i] = (char) ('A' + ('X' - 'A' + i) % 26);
}
'A' is the base, 'X' - 'A' builds that offset where you add i to, and then take the modulo of 26 (as the alphabet has 26 characters), and then add that to your 'A' again.

You can just insert an if statement:
char startChar = 'X';
for (int i = 0; i < 26; i++) {
char ch = (char) (startChar + i);
if (ch > 'Z') {
ch -= 26;
}
alphabet[i] = ch;
}

Related

How to count the number of alphabetic literals in a String?

Currently I have a simple problem to solve:
Given a String str, what is the best way of counting the amount of alphabetic literals in the string?
Right now I am thinking something like this:
int letterCount = 0;
for(int i = 0 : str){
String check = "" + str.charAt(i);
if(check.isLetter())
letterCount++
}
Are there any more efficient or elegant ways?
I’m pretty fond of streams (since Java 8):
String str = "A string";
long letterCount = str.chars().filter(Character::isLetter).count();
System.out.println(letterCount);
7
Your for loop is another nice solution. Here’s a version that works:
for (int index = 0; index < str.length(); index++) {
if (Character.isLetter(str.charAt(index))) {
letterCount++;
}
}
String str = "#CodeWines65";
int upper = 0, lower = 0, number = 0, special = 0;
for(int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z')
upper++;
else if (ch >= 'a' && ch <= 'z')
lower++;
else if (ch >= '0' && ch <= '9')
number++;
else
special++;
}
System.out.println("Lower case letters : " + lower);
System.out.println("Upper case letters : " + upper);
System.out.println("Number : " + number);
System.out.println("Special characters : " + special);
// If you are not concerned about uppercase or lowercase you can add them both & get the total count

How to add 0 in front of every single digit string?

How can I add 0 in front of every single digit number? I mean 1 to 01 etc.
I have tried to add ifs like
if(c >='A' && c<= 'I')
str = "0"+str;
but it just adds 0 in front of everything like abcd converts to 00001234 not 01020304.
This is my code.
String A[] = new String[size];
for (int i = 0; i < size; i++) {
A[i] = jList1.getModel().getElementAt(i);
String[] Text = A[i].split("");
String s = jList1.getModel().getElementAt(i);
String str = ("");
for (int z = 0; z < Text.length; z++) {
for (int y = 0; y < Text[z].length(); y = y + 1) {
char c = s.charAt(z);
if (c >= 'A' && c <= 'Z') {
str += c - 'A' + 1;
} else if (c >= 'a' && c <= 'z') {
str += c - 'a' + 1;
} else {
str += c;
}
}
str = str + "";
}
}
This Worked for me
public String addZero(int number)
{
return number<=9?"0"+number:String.valueOf(number);
}``
One way to do this would be to use a StringJoiner with Java 8:
String s = "abcdABCD";
s = s.chars()
.mapToObj(i -> Integer.toString((i >= 'a' && i <= 'z' ? i - 'a' : i - 'A') + 1))
.collect(Collectors.joining("0", "0", "")));
System.out.println(s);
>> 0102030401020304
String str = "abcd-zzz-AAA";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.toLowerCase().charAt(i);
if (ch >= 'a' && ch <= 'z') {
sb.append('0');
sb.append(ch - 'a' + 1);
} else {
sb.append(ch);
}
}
Result: abcd-zzz-AAA -> 01020304-026026026-010101
Final fix :-)
use String#chars to get a stream of its characters, then for each one do the manipulation you want.
public class Example {
public static void main(String[] args) {
String s = "aBcd1xYz";
s.chars().forEach(c -> {
if (c >= 'a' && c <= 'z')
System.out.print("0" + (c - 'a' + 1));
else if (c >= 'A' && c <= 'Z')
System.out.print("0" + (c - 'A' + 1));
else
System.out.print(c);
});
}
}
Ouput:
0102030449024025026
You can add zero in front of single digit number using String.format.
System.out.println(String.format("%02d",1));
System.out.println(String.format("%02d",999));
The first line will print 01, second line prints 999 no zero padding on the left.
Padding zero with length of 2 and d represents integer.
I hope this helps.

JavaScript, Java, Php, or C++ cipher encryption - reworking algorithm

I am trying to implement a loop that encrypts a string to the given shift amount of int shift. The code below works great, however I'd like to change the code so that it encrypts in a descending order instead of ascending. Any clues as to what to change in the algorithm?
int shift = 3;
string line = "abc";
for (int i = 0; i < line.length(); i++) {
if (line[i] >= 'a' && line[i] <= 'z') {
int rotate = line[i] + shift;
if (rotate > 'z') line[i] = ((line[i] - 26) + shift);
else line[i] = rotate;
}
}
cout << line << endl;
With a shift of 3, the above code converts string line "abc" to "def", but I am trying to get the output of "dcb".
NOTE: The code is in C++ but I will accept JavaScript, Java, or Php suggestions just as C++, as long as it's raw code with no library resources. Thanks guys and gals.
you can just upgrade the variable shift and then instead of checking overflow of increasing check the decreasing
int shift = -3;
string line = "abc";
for (int i = 0; i < line.length(); i++) {
if (line[i] >= 'a' && line[i] <= 'z') {
int rotate = line[i] + shift;
if (rotate < 'a') line[i] = ((line[i] + 26) + shift);
else line[i] = rotate;
}
}
cout << line << endl;
you can also do the below if in your loop if you want to handle uppercases
if (line[i] >= 'A' && line[i] <= 'Z') {
int rotate = line[i] + shift;
if (rotate < 'A') line[i] = ((line[i] + 26) + shift);
else line[i] = rotate;
}

encode string passed to method & add 13

(EDITED)
My problem statement: write a method that will encode the String passed to the method by adding 13 letters to each character in the String. If the letter after adding 13 exceeds 'z' then "wrap around" the alphabet. Then return the encoded String.
encodeString("hello") → "uryyb"
encodeString("pie") → "cvr"
encodeString("book") → "obbx"
this is what I have so far :
public static String encodeString (String input) {
String output;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= 'a' && c <= 'm')
c += 13;
else if (c >= 'n' && c <= 'z')
c -= 13;
output= (" " + (c));
}
return output;
}
now I know that I have to create a counter so that the method will continue to loop until it reaches the length of the string passed...and I know that if the charAt(index) is less than the character 'n' that I add 13 and if it is greater then I subtract 13. when I put it all together though I just get so confused and just get a bunch of compiling errors like Type mismatch: cannot convert from int to String.
note straightforward explanations/answers would be much appreciated...
***so now my problem is that it keeps telling me my output variable may not have been initialized
This code is not the most performatic but works good with Upper and Lower characters.
hElLo → uRyYb
pIe → cVr
bOoK → oBbX
private static String encodeString(String string) {
char[] ret = new char[string.length()];
for (int i = 0; i < string.length(); i++) {
ret[i] = rot13(string.charAt(i));
}
return String.valueOf(ret);
}
public static char rot13(char c) {
if (Character.isLetter(c)) {
if (Character.compare(Character.toLowerCase(c), 'a') >= 0
&& Character.compare(Character.toLowerCase(c), 'm') <= 0)
return c += 13;
else
return c -= 13;
}
return c;
}
You have to initialize your output variable as an empty String. Furthermore you are always replacing the contents of the output variable with the last char you've just encoded. So you have to add every char to the output with += instead of =.
So here is the fixed solution:
public static String encodeString(String input) {
String output = ""; // initialize as empty String
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= 'a' && c <= 'm') {
c += 13;
} else if (c >= 'n' && c <= 'z') {
c -= 13;
}
output += " " + c; // add all chars to the String instead of replacing the whole String with "="!
}
return output;
}
I beautified your code a bit, so everybody can see what it really does.
Use an IDE!

Repeating Java Array

I'm new to java and still learning, so keep that in mind. I'm trying to write a program where a user can type in a keyword and it'll convert it to numbers and put it in an array. My problem is the array needs to keep repeating the int's.
My code is:
String keyword=inputdata.nextLine();
int[] key = new int[keyword.length()];
for (int k = 0; k < keyword.length(); ++k)
{
if (keyword.charAt(k) >= 'a' && keyword.charAt(k) <= 'z')
{
key[k]= (int)keyword.charAt(k) - (int)'a';
}
}
Right now if I try to get any key[i] higher than the keyword.length it throws an outofbounds error. I need it to to be infinte.
So basically, if keyword.length() were 3 I need to be able to see if key[2] is the same as key[5] and key[8] and so on.
Thanks for your help!
Well, it's easiest to fix your code with a bit of refactoring first. Extract all uses of keyword.charAt(k) to a local variable:
for (int k = 0; k < keyword.length(); ++k)
{
char c = keyword.charAt(k);
if (c >= 'a' && c <= 'z')
{
key[k] = c'a';
}
}
Then we can fix the issue with the % operator:
// I assume you actually want a different upper bound?
for (int k = 0; k < keyword.length(); ++k)
{
char c = keyword.charAt(k % keyword.length());
if (c >= 'a' && c <= 'z')
{
key[k] = c - 'a';
}
}
That's assuming you actually make key longer than keyword - and you probably want to change the upper bound of the loop too. For example:
int[] key = new int[1000]; // Or whatever
for (int k = 0; k < key.length; ++k)
{
char c = keyword.charAt(k % keyword.length());
if (c >= 'a' && c <= 'z')
{
key[k] = c - 'a';
}
}

Categories

Resources