Print 10 characters per line - java

hello i have some trouble doing my coding on this question;
Write a method that prints characters using the following header:
public static void printChars(char ch1, char ch2, int numberPerLine)
This method prints the characters between ch1 and ch2 with the specified numbers per line. Write test program that prints ten characters per line from ā€˜lā€™ and ā€˜Zā€™.
can somebody show me the coding sample to solve my problem? thanks

Here is some code that seems to wok on my end.
public static String alphabet = "abcdefghijklmnopqrstuvwxyz";
public static void printChars(char ch1, char ch2, int numberPerLine){
int currentNumber = numberPerLine;
int beginningIndex = alphabet.indexOf((ch1 + "").toLowerCase()) + 1;
int endingIndex = alphabet.indexOf((ch2 + "").toLowerCase());
for(int i = beginningIndex; i < endingIndex; i++){
System.out.print(alphabet.charAt(i));
if(currentNumber > 1){
currentNumber --;
}else{
System.out.println("");
currentNumber = numberPerLine;
}
}
}
public static void main(String[] args) {
printChars('c', 'z', 2);
}

Characters are encoded in ASCII. Each character has a unique decimal number representation. We can access these characters by their numbers, rather than the actual character.
For example, the character 'A' has an ASCII code of 65. We don't really need to know the integer codes to use their respective character representations though. We can just typecast the integers into chars.
We can also use characters in simple arithmetic. Since 'A' has ASCII code 65, then it makes sense for 65 + 1 = 66 to represent the character 'B'. Indeed it does.
public static void printChars(char ch1, char ch2, int numberPerLine) {
if(ch1 <= 'Z' && ch2 >= 'a')
return;
int count = 0; //count number of characters on a line.
char nextChar = ch1; //initialize our next character
while(nextChar <= ch2) { //test case
System.out.print(nextChar);
count++; //once we print a character, increment our count
if(count == numberPerLine) { //check if we reach our desired amount of characters
System.out.println();
count = 0; //once we print a new line, restart the count
}
nextChar = (char) (nextChar + 1); //get next character
}
}

Related

Adding two numbers stored as arrays of chars

I'm trying to write an algorithm which adds two numbers that are stored as chars in two arrays. Unfortunately, it doesn't work. When I try to debug it, I see that the variables a and b get the value -1 which makes no sense. Any idea what might be the problem?
public class rechner2 {
public static void main(String[] args) {
final char[] zahl1 = {1, 2, 3};
final char[] zahl2 = {7, 8, 9};
//Add arrays zahl1 and zahl2.
char [] zwischenarray = add(zahl1, zahl2);
for (int i = 0; i < zwischenarray.length; i++) {
System.out.println(zwischenarray[i]);
}
}
private static char[] add(char[] zahl1, char[] zahl2) {
int len;
if (zahl1.length < zahl2.length) {
len = zahl2.length;
} else {
len = zahl1.length;
}
char[] finalresult = new char [len + 1];
int carryover = 0;
for (int i = 0; i < len; i++) {
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
int c = a + b + carryover;
if (c > 9) {
carryover = 1;
c = c - 10;
} else {
carryover = 0;
}
finalresult[i] = (char)c;
}
if (carryover == 1) {
finalresult[len + 1] = 1;
}
return finalresult;
}
}
in this code I believe 2 bug
instead of char , i guess better to us int
length of the array
here is the code:
public class rechner2 {
public static void main(String[] args) {
int[] zahl1 = {1,2,3};
int[] zahl2 = {7,8,9};
//Add arrays zahl1 and zahl2.
int [] zwischenarray = add(zahl1, zahl2);
for (int i = 0; i < zwischenarray.length; i++) {
System.out.println(zwischenarray[i]);
}
}
private static int[] add(int[] zahl1, int[] zahl2) {
int len;
if (zahl1.length < zahl2.length) {
len = zahl2.length;
} else {
len = zahl1.length;
}
int[] finalresult = new int [len + 1];
int carryover = 0;
for (int i = 0; i <= len-1; i++) {
int a = (zahl1[i]);
int b = (zahl2[i]);
int c = a + b + carryover;
if (c > 9) {
carryover = 1;
c = c - 10;
} else {
carryover = 0;
}
finalresult[i] = c;
}
if (carryover == 1) {
finalresult[len] = 1;
}
return finalresult;
}
}
Your code is conflicted: The numbers / characters in your array are actually integers, not "printable" or "human readable" characters. But, parts of your code are treating them as if they are "printable".
Let's go back decades, and use ASCII for the beginning of this explanation. ASCII has "Printable" and "Nonprintable" characters. The "Nonprintable" characters are known as "Control codes."
Control codes include codes that move the cursor on a display terminal or print head on a printing terminal. They include thing like CR (Carriage Return), LF (Line Feed), HT (Horizontal tab), and BS (Backspace). Others are used by data communications hardware to control the flow of data, or to report status.
Printable characters correspond to what you see on a terminal screen or printout. They include uppercase alphabetic, lower case alphabetic, digits, punctuation, and the space character. They are "human readable."
Look at the list of printable characters in the Wikipedia article. Take 5 as an example. It's represented as '53' in base ten, which corresponds to '35' in base sixteen, or '011 0101' in binary. Note that it is not the same as the binary number five, which would be '0000 0101'.
Java uses 16 bit Unicode, not ASCII, for its char type. The Java compiler allows arithmetic to be done on char data, as if it was the same as short.
These lines in your code expect your char variables and constants are printable characters:
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
In addition, that you specified zwischenarray as char tells the compiler to handle the contents as printable characters in this line:
System.out.println(zwischenarray[i]);
But, the rest of your code treats your char data as integer data types.
You have a bug in this line: finalresult[len + 1] = 1;. After that bug is fixed, how do you fix the rest of your code? There are different ways, and which is best depends on your intention.
For demonstration purpose, try this: Replace the following
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
int c = a + b + carryover;
with
int c = zahl1[i] + zahl2 [i] + carryover;
Also, put a cast in your output line:
System.out.println((short)zwischenarray[i]);
And run it. That will demonstrate you can do arithmetic on Java char data.
Now, remove the (short) cast in output line, and change all occurrences of char to short (or int). Your program still works.
This is because of the way you entered the values for zahl1 and zahl2. Your source code consists of printable characters and white space. By omitting the single quotes, you told the compiler to convert the values to binary integers. For example, your source code 9 became binary 0000 1001 in the runtime code. If you wanted your 9 to remain as a printable character, you needed to enclose it in single quote marks: '9' .
By enclosing all the values in zahl1 and zahl2 in single quote marks, the use of Character.getNumericValue is appropriate. But, you would still need the (short) or (int) cast in your System.out. line to see your output.
Character.getNumericValue is returning -1 because the values passed are outside of the range it was designed to work with.
Here are two ways to convert a base 10 digit represented as a binary integer to the equivalent printable character:
finalresult[i] = (char) (c + '0');
But, my preference is for this:
final String digit = "0123456789";
finalresult[i] = digit.charAt (c);

Caesar Cipher Uppercase and Lowercase Wrap Around

I am having a problem regarding wrapping around the alphabet with my Caesar Cipher Program.
The program works fine with all lowercase letters. Wraps around perfectly and is able to apply positive and negative shifts. When i try to input an uppercase letter, the uppercase letter does not wrap around.
Here is my code:
public static StringBuilder encode(String str, int numShift)
{
numShift = numShift % 26;
//assign each character of the string to a position in the character array
char[] strChars = str.toCharArray();
for (int i = 0; i < strChars.length; i++)
{
//ignore and continue if the character is not within the alphabet
if((strChars[i] < 'a' || strChars[i] > 'z') && (strChars[i]<'A' || strChars[i] > 'Z'))
continue;
//apply the shift to each character
strChars[i] += numShift;
//wrap around if the shift is beyond Z
**if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}**
}
StringBuilder encodedStr = new StringBuilder();
encodedStr.append(strChars);
return encodedStr;
}
public static void init(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the string that you would like to encode:");
String str = scan.nextLine();
System.out.println("Please enter the number of letters you would like to shift:");
int strShift = scan.nextInt();
scan.close();
StringBuilder result = encode(str, strShift);
System.out.println(result);
}
public static void main(String[] args)
{
init();
}
}
Hints would be much appreciated! Of course, I am not asking anyone to do my work for me but some help would be appreciated! Thank you! :)
Edit: here's the if statement that does the wrap around for lowercase letters only:
if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}
Let's implement a wrap-around function for a single character. This will be used by the other method. When you separate your tasks and sub-tasks wisely, you will observe that your problem becomes easier to solve. Here I have based my solution on the fact that char variables are represented as numbers, we know the number of letters and we can use that number as a modulo class, to make sure that algebra is aiding us.
private static char wrapChar(char input, int amount) {
//assume for now that we have an upper-case letter
char start = 'A';
//if the assumption is mistaken...
if (('a' <= input) && (input <= 'z')) {
//then, if it is lower-case, then use lower-case
start = 'a';
} else if (!(('A' <= input) && (input <= 'Z'))) {
//target is not letter
return input;
}
//Calculate total offset compared to the first letter of the alphabet
//be it lower or upper
int offset = ((input - start) + amount) % 26;
//If offset happens to be negative, then shift a modulo period of 26
//To get the correct positive offset
if (offset < 0) {
offset += 26;
}
//Add the final offset to start and convert it to char
return ((char)(start + offset));
}
Now, instead of
//apply the shift to each character
strChars[i] += numShift;
//wrap around if the shift is beyond Z
**if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}**
You need just:
strChars[i] = wrapChar(strChars[i], numShift);

Adding two character arrays and storing the result as characters in another char array in Java

I want to add two character arrays and store the result as characters in another character array.
The addition involves addition of two english letters from the two arrays as operands.
The addition will wrap around z back to a .
eg.
Input:Array1 and Array 2 and output is Array 3
Array 1 :abcdeyz
Array 2 :aaaaaaa
Array 3 :bcdefza
Below is a part of my code which is not working.
Kindly suggest any changes
int c = 0;
char array3[] = new char[count] ;
for(int a=0;a<array1.length;a++)
{
for(int b=0;b<array2.length;b++)
{
int temp = (array1[a] + array2[b]) % 26 ;
array3[c] = (char) temp ;
c++ ;
}
}
Hint - value of 'a' is not 0
The issue is in the line -
int temp = (array1[a] + array2[b]) % 26 ;
Here is the modified code (assuming all characters are lower case)-
int c = 0;
char array3[] = new char[count] ;
for(int a=0;a<array1.length;a++)
{
for(int b=0;b<array2.length;b++)
{
int temp = ( (array1[a]-'a') + (array2[b]-'a')) % 26 ;
array3[c] = (char) (temp+'a') ;
c++ ;
}
}
Using the modulo of 26 is a good way of handling a-z to 1-26 conversion. This way your program can be agnostic about the actual ASCII character numbers.
Some other concerns:
Case Insensitivity. I would recommend converting your letters to lowercase before processing them.
Handling of exceptional cases. What if your arrays are different lengths? Or what if they have a character that isn't a
letter?
The below code is one way to handle these things.
public static int letterToInt(char letter) {
char letterToConvert = Character.toLowerCase(letter);
int codeForA = (int)'a';
int numberOfLetter = ((int)letterToConvert) - codeForA + 1;
if(numberOfLetter < 1 || numberOfLetter > 26) {
throw new IllegalArgumentException(
"The character argument can only be a-z or A-Z, but was '" + letter + "'");
}
return numberOfLetter;
}
public static char intToLetter(int number) {
if(number < 1 || number > 26) {
throw new IllegalArgumentException(
"The number can only be 1-26, but was " + number);
}
int codeForA = (int)'a';
return (char)(codeForA + number - 1);
}
public static char addLetters(char letter1, char letter2) {
int numberFromAddedLetters =
letterToInt(letter1) + letterToInt(letter2);
int modulo = numberFromAddedLetters % 26;
return intToLetter(modulo == 0 ? 26 : modulo);
}
public static char[] addLetterArrays(char[] array1, char[] array2) {
char[] longerArray;
char[] shorterArray;
if(array1.length >= array2.length) {
longerArray = array1;
shorterArray = array2;
} else {
longerArray = array2;
shorterArray = array1;
}
char[] addedLetters = new char[longerArray.length];
for(int index = 0; index < longerArray.length; index++) {
if(index < shorterArray.length) {
addedLetters[index] = addLetters(longerArray[index], shorterArray[index]);
} else {
addedLetters[index] = longerArray[index];
}
}
return addedLetters;
}
// Test it out
public static void main(String[] args) {
char[] letters1 = "abcdeyz".toCharArray();
char[] letters2 = "aaaaaaa".toCharArray();
// Prints [b, c, d, e, f, z, a]
System.out.println(Arrays.toString(addLetterArrays(letters1, letters2)));
}
This is a fixed and working example on how to do this:
public static void main(String[] args) {
char[] array1 = new char[] {'a', 'b', 'c', 'd', 'e', 'y', 'z'};
char[] array2 = new char[] {'a', 'a', 'a', 'a', 'a', 'a', 'a'};
char[] array3 = new char[array1.length];
for (int i = 0; i < array1.length; i++) {
array3[i] = toChar((toInt(array1[i]) + toInt(array2[i]) + 1) % 26);
}
System.out.println(Arrays.toString(array3));
}
private static int toInt(char chr) {
return chr - 'a';
}
private static char toChar(int value) {
return (char)(value + 'a');
}
There are some thinks to notice here (except the - 'a' part, the other answers mentioned that already):
you only need one loop for this task. If you use 2 nested loops, then you'll add each letter of array1 with every letter of array2. And you'll a larger array3. And since the result doesn't match the desired result ... :)
the + 1 in toInt(array2[i]) + 1 is necessary, because char - 'a' is "zero-based". Therefore 'a' + 'b' would result in 'b' and not 'c', because you'll calculate 0 + 1 (which will be 'b' if you "convert" it back to char by adding 'a') (I hope this is understandable expressed :D)
it is necessary that array2 has at least the same length as 'array1'. It is almost like padding in cryptography. (I've omitted the padding part to keep this code short)
Write this:
int temp = (((array1[a] - 'a') + (array2[b] - 'a')) % 26) + 'a';
what this does is convert both characters into their respective place in the alphabet, perform addition modulo the number of characters in the alphabet for the wraparound effect, and convert back to the correct ascii value.
Note that your code was having trouble because you were acting as though the alphabet's ascii values were their respective places in the alphabet itself, which is incorrect.

In a String, how can I separate & store the characters and integers?

My task is to create a Bubble Breaker type game, I broke my task into several smaller tasks, and I hit a wall.
I created a 2D Array Grid which will, whenever the program starts, be randomized with different coloured Bubbles. Each Line and Each Column is numbered, Lines range in Numbers, Columns range in Letters.
My goal is to have the user input choosing a String (Note I can only use String, as I'm programming in a pre-designed console), for example B10, B9 or 10B.
I'm able to check if the characters are numbers or letters via
command.charAt(i) >= '0' && command.charAt(i) <= '9' // i is a counter in a for
The above allows me to find if it's a digit or a number, the problem is that to select the Exact grid position, I need to, and can't:
Separate the String into Integrers AND character
Join the two Integrers
(note they can be B9, B10 or 10B)
This is an example of the duality B10 and 10B
You only need two lines:
int num = Integer.parseInt(str.replaceAll("\\D", ""));
String letter = str.replaceAll("\\d", "");
The order of letters and digits in the string is irrelevant - this will work either way.
Edited to cater for requirements as per comments below
To process a series of letter-digit pairs in larger string, parsing the letter to an int x (where A=1, B=2, etc) and assigning the digit(s) to int y, you can split the string up on whitespace and use code similar to above:
for (String pair : command.toUpperCase().split("\\s+")) {
int x = pair.replaceAll("\\d", "").charAt(0) - '#';
int y = Integer.parseInt(pair.replaceAll("\\D", ""));
}
Using split() means not having to sully yourself with the tedium of using a loop variable.
The reason for subtracting '#' is that is the character one before 'A', so subtracting that will convert A to 1, B to 2, etc.
Here's some test code:
String command = "A5 B10 11C 20D";
for (String pair : command.split("\\s+")) {
int x = pair.replaceAll("\\d", "").charAt(0) - '#';
int y = Integer.parseInt(pair.replaceAll("\\D", ""));
System.out.format("X = %d, Y = %d\n", x, y);
}
Output:
X = 1, Y = 5
X = 2, Y = 10
X = 3, Y = 11
X = 4, Y = 20
To answer the question, just use an if loop. (If the first char is a digit, parse all but the last as an integer, otherwise parse all starting from the second as an integer.) (use String.substring(start, end) to separate it if that's all you want to know)
Also, you can use Character.isDigit() instead of
command.charAt(i) >= '0' && command.charAt(i) <= '9'
(just for code legibility)
Loop through the String
Check if character is a letter
Save that letter to a variable (char letter)
Replace the original String such that the letter is replace with nothing (String numString)
Now you have them separated: letter and numString
This will work with B10 or 10B. And set that has only one letter and the rest numbers
See code
String code = "10B";
char letter;
for (char c : code.toCharArray()){
if (Character.isLetter(c)){ // if the character is a letter, save if the "letter"
letter = c;
break;
}
}
String numString = code.replace(letter, ""); // replace the original string, letter for ""
// Parse if you need to
int num = Integer.parseInt(numString);
// You have the letter by itself, and the number by itself
System.out.println("Letter: " + letter + ", Number: " + num);
Edit: Try the code below. I had a couple errors in one above
String code = "10B";
char letter = ' '; // <-- initialize
for (char c : code.toCharArray()) {
if (Character.isLetter(c)) { // if the character is a letter, save if the "letter"
letter = c;
break;
}
}
String numString = code.replace(String.valueOf(letter), ""); <-- String valueOf
int num = Integer.parseInt(numString);
System.out.println("Letter: " + letter + ", Number: " + num);
Result : Letter: B, Number: 10
public class StringSpliter {
public static void main(String[] args) {
ArrayList<Character> chars = new ArrayList<>();
ArrayList<Integer> ints = new ArrayList<>();
String str = "T23his i43s a Stin4g Whi12ch C1on3431tains Ch 5ara32cter2343s and Alphabets";
char[] mychars = str.toCharArray();
for (int i = 0; i < mychars.length; i++) {
if (mychars[i] >= 33 && !(mychars[i] <= '9' && mychars[i] >= '0')) {
chars.add(mychars[i]);
} else if (mychars[i] >= '0' && mychars[i] <= '9') {
ints.add((Integer.parseInt(""+mychars[i])));
}
}
for (int i = 0; i < chars.size() + ints.size(); i++) {
if (i < chars.size()) {
System.out.println(chars.get(i));
} else {
System.out.println(ints.get(i - chars.size()));
}
}
}
}
Try the above code

Convert a letter to the corresponding letter on the opposite counting direction in the alphabet

I am self-studying Java and I am very at the beginning learning the basics. With below code I am trying to convert a letter to the corresponding letter on the opposite counting direction in the alphabet(i.e A to Z or Z to A etc.). It works for a single letter but not for a series of letters. How can I make it work with more than one letter? If you can use the simplest way it would be good as I am quite new in Java. I don't(know how to) export any built in classes etc.
Thank you.
class Turner{
int find(int fin, int mi,int ma,char ch[]){
int mid = (ma+mi)/2;
int x;
if(ch[mid]==fin)
return mid;
else if(fin<ch[mid])
return(find(fin, mi,mid-1,ch));
else
return x = find(fin,(mid+1),ma,ch);
}
}
class Turn {
public static void main(String args[]) throws java.io.IOException
{
Turner try1 = new Turner();
char arra[] = new char[26];
char arrb[] = new char[26];
int min = 0;
int max = arra.length;
char a = 'A';
char b = 'Z';
int i;
char letter;
for(i=0;i<26;i++)
{
arra[i]=a;
a++;
arrb[i]=b;
b--;
}
System.out.println("Enter a letter: ");
letter = (char)System.in.read();
System.out.print(arrb[try1.find(letter,min,max,arra)]);
}
}
Have you considered just doing some math?
letter = Character.toUpperCase((char)System.in.read());
System.out.print((char)('Z' - (letter - 'A'));
And it works for only one letter because you are not repeating the conversion procedure. The program reads one char, prints its opposite and then terminates.
All you have to do is to put the read and print code inside some sort of loop, so every time it runs it will promptly wait for the next letter.
while (true) {
letter = Character.toUpperCase((char)System.in.read());
if ((letter > 'Z') || (letter < 'A'))
break; // user inputted an invalid symbol, terminating the program
System.out.print((char)('Z' - (letter - 'A')));
}
If your function (they are called methods in java) works, good. Just put it in a while loop or otherwise call it when you need it.
boolean done = false;
while(!done){
System.out.println("Enter a letter (space to quit): ");
letter = (char)System.in.read();
if(letter == ' ') done = true;
else System.out.print(arrb[try1.find(letter,min,max,arra)]);
}
And Havenard is right, this can be written considerably more simply, with arithmetic on chars. For instance ch -'a' == 1 evaluates to true when ch is 'b'.
One other note: find and Turner aren't very descriptive names for what these things do. Before long it could get messy without simple and to the point naming.
A character has an equivalent numerical value. For "basic characters", this mapping is called ASCII table: http://www.asciitable.com/
Now, in java, you can convert a char into an int by casting. Example: int nValue=(int) 'a'.
Since there is a numerical value associated to 'a' and another one associated with 'z', you could use some simple math to solve your problem.
See:
int aNumericalValue = (int) 'a';
int zNumericalValue = (int) 'z';
char characterToConvert = ...;
int characterToConvertAsNumericalValue = (int) characterToConvert;
int resultCharacterAsNumericalValue = zNumericalValue - (characterToConvertAsNumericalValue - aNumericalValue);
char resultCharacter = (char) resultCharacterAsNumericalValue;
Or, you could write all of this as a single line of code:
char resultCharacter = (char) ((int) 'z' - ((int) characterToConvert - (int) 'a'));
And finally, if you are willing to hardcode some ASCII values:
char resultCharacter = (char) (122 - ((int) characterToConvert - 97));
Note that this is for lowercase letters. For caps, use 'A' (ascii 65), 'Z' (ascii 90).

Categories

Resources