Print a string backwards and shifted once ex: cat = ubd - java

I have successfully printed my String backwards, but I'm having a hard time getting it to shift forward a letter. My outputs have been numbers instead of letters, so I have tried to convert those numbers back to letters unsuccessfully. There is other code in this as well, but I only need help with this one bit.
package inlämningsuppgift4;
import java.util.Scanner;
public class Inlämningsuppgift4 {
public static void word(String w1){
//char a[]= w1.toCharArray();
for (int i=w1.length()-1; i>=0; i--)
//char c = 'a';
//c = (char) (((c - 'a' - 1) % 26) + 'a');
{System.out.print(w1.charAt(i));
}
System.out.println();
}
public static void word2(String w2){
for (int j=0;j<w2.length(); j++)
{System.out.print("*"+w2.charAt(j));
}
System.out.println("*");
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Ange ett ord: ");
String ord = input.nextLine();
word2(ord);
word(ord);
}
}
It seems like I was on the right path trying to set up "//char c" but I couldn't get it to function as written. I got that code from a questions search, but can't wrap my head around it. How do I make it fit with my code already written? Or should I find a different way?

You have two different problems:
reversing a string. There are a lot of ways to do it.
String s1 = "cat";
String s2 = "";
for (int i =0 ; i < s1.length(); i++) {
s2 = s1.charAt(i) + s2;
}
System.out.println(s2);
So just create a new string by adding strings backwards.
"Shifting" a character, which presumably means taking the code-point and modifying it, and possibly wrapping it (eg: Z wraps to A, instead of moving forward to [)
String s1 = "cat";
String s2 = "";
for (int i =0 ; i < s1.length(); i++) {
char c = s1.charAt(i);
c += 1;
// reverse string implementation omitted
}
System.out.println(s2);
Java seems to let you add directly to char so whatever works. Note that this does not care about wrapping, so z would not wrap to a. That's up to you to figure out.
Now you just need to combine that with the string building.

Related

What is the best way to replace a letter with the letter following it in the alphabet in Java?

I'm a programming newbie and I am doing a coderbyte exercise that says "
Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a)"
i'm thinking of the following methods:
declare a string called "abcdefghijklmnopqrstuvxyz" and compare each string's char index position with the alphabet's index position, and then just bring the alphabet char that is located at the i+1 index location. But I don't know how it would work from z to a.
I've seen some techniques using ASCII values for every char but I've never done that before and not sure how it works
convert the given string into a char[] array, but then I'm not sure how I would tell the system to get me the next alphabet char
What would be the easiest way to do this?
EDIT
this is my code so far, but it doesn't work.
import java.util.*;
import java.io.*;
class Main {
public static String LetterChanges(String str) {
// code goes here
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String newWord = "";
for (int i = 0; i < str.length(); i++){
for (int j = 0; j < alphabet.length(); i++){
if (str[i] == alphabet[i]){
if (alphabet[i+1].isVowel()){
newWord = newWord + toUpperCase(alphabet[i+1]);
}
else{
newWord = newWord + alphabet[i+1];
}
}
}
}
return str;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterChanges(s.nextLine()));
}
}
Can't I ask for the index position of a Char that is a part of a String? in C I could do that.
Other than that not sure why it doesn't work.
I would definitely go with method 1.
I believe what you're looking for is the indexOf method on a String.
First of, I would create a method that given a character finds the next letter in the alphabet and return that. This could be done by finding the letter in your alphabet string and then fetch the letter at index+1. As you also pointed out you would need to take care of the edge case to turn 'z' into 'a', could by done with an if-statement or by having an extra letter 'a' at the end of your alphabet string.
Now all that remains to do is create a loop that runs over all characters in the message and calls the previously made method on that character and constuct a new string with the output.
Hope this helps you figure out a solution.
Assuming that there would be only lower case English letters in the given String the most performant way would be to add +1 to every character, and use either if-statement checking whethe the initial character was z or use the modulo operator % as #sp00m has pointed out in the comment.
Performing a search in the alphabetic string (option 1 in your list) is redundant, as well extracting array char[] from the given string (option 3).
Checking the edge case:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = str.charAt(i);
if (next == 'z') result.append('a'); // checking the edge case
else result.append((char) (next + 1));
}
return result.toString();
}
Applying modulo operator:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = (char) ((str.charAt(i) - 'a' + 1) % 26 + 'a');
result.append(next);
}
return result.toString();
}
main()
public static void main(String[] args) {
System.out.println(shiftLetters("abc"));
System.out.println(shiftLetters("wxyz"));
}
Output:
bcd // "abc"
xyza // "wxyz"

Counting the number of specific occurrences in a java String

I am attempting to solve a problem where I create a method that counts the number of occurrences of capital and lowercase ("A" or "a") in a certain string. I have been working on this problem for a week now, and the main error that I am receiving is that "char cannot be dereferenced". Can anyone point me in the correct direction on this Java problem? Thank you.
class Main{
public static int countA (String s)
{
String s1 = "a";
String s2 = "A";
int count = 0;
for (int i = 0; i < s.length; i++){
String s3 = s.charAt(i);
if (s3.equals(s1) || s3.equals(s2)){
count += 1;
}
else{
System.out.print("");
}
}
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(countA("aaA")); //3
System.out.println(countA("aaBBdf8k3AAadnklA")); //6
}
}
try a simpler solution
String in = "aaBBdf8k3AAadnklA";
String out = in.replace ("A", "").replace ("a", "");
int lenDiff = in.length () - out.length ();
Also as #chris mentions in his answer, the String could be converted to lowercase first and then only do a single check
the main error that I am receiving is that "char cannot be
dereferenced"
change this:
s.length // this syntax is incorrect
to this:
s.length() // this is how you invoke the length method on a string
also, change this:
String s3 = s.charAt(i); // you cannot assign a char type to string type
to this:
String s3 = Character.toString(s.charAt(i)); // convert the char to string
another solution to accomplishing your task in a simpler manner is by using the Stream#filter method. Then convert each String within the Stream to lowercase prior to comparison, if any Strings match "a" we keep it, if not we ignore it and at the end, we simply return the count.
public static int countA(String input)
{
return (int)Arrays.stream(input.split("")).filter(s -> s.toLowerCase().equals("a")).count();
}
For counting the number of time 'a' or 'A' appears in a String:
public int numberOfA(String s) {
s = s.toLowerCase();
int sum = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == 'a')
sum++;
}
return sum;
}
Or just replace everything else and see how long your string is:
int numberOfA = string.replaceAll("[^aA]", "").length();
To find the number of times character a and A appear in string.
int numA = string.replaceAll("[^aA]","").length();

String Output Alignment in Java

practice question part 1
practice question part 2
This is a practice question which is rather hard for me. Below is my code for the static method(the main method is fixed -unchangeable, and signature of static method is given), and my intention is to get the matches between the characters and print them out.
But there are some concerns:
1) How do i ensure it doesn't print when all the strings are aligned but there are extra characters which makes the boolean false and the result to be not aligned instead? (e.g amgk as second string & first string is Java Programming Course)
2) How do i make it print right? currently the spaces are off and the letters aren't what is wanted.
3) If there is more than one character a in str1, which do i choose to put, and how do i omit the rest when there is already a match?
Would really appreciate a pseudocode to help guide a beginner like me in solving this problem.
public class Q3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first string:");
String input1 = sc.nextLine();
System.out.print("Enter the second string:");
String input2 = sc.nextLine();
System.out.println();
if (matchStrings(input1, input2)) {
System.out.println();
System.out.println("There is an alignment as shown above.");
} else {
System.out.println("No alignment can be found.");
}
}
public static boolean matchStrings(String str1, String str2) {
// Modify the code below to return the correct value.
boolean isMatch = false;
//int firstChar = str2.charAt(0);
//int lastChar = str2.charAt(str2.length()-1);
int prevIndex = 0;
System.out.println(str1);
for (int j = 0; j< str2.length(); j++) {
for (int i = 0; i<str1.length();i++) {
char charToSearch = str1.charAt(i);
int newIndex = i;
if (str2.charAt(j)== charToSearch) {
for (int k = prevIndex; k < newIndex-1; k++) {
System.out.print(" ");
}
System.out.print(charToSearch);
//prevIndex=newIndex+1;
isMatch = true;
}
}
}
return isMatch;
}
}
I think two of the first few structures you learn in a Data Structures course is the stack and queue. Thus, I will provide an implementation using a Stack. You can use a Stack to store the test String and pop each char element off the stack when it is matched up with a character in the first string. Otherwise you would output an empty space " " in the matched String object:
Stack s2 = new Stack();
String str1 = "Java Programming";
String str2 = "amg";
for(int i = str2.length()-1; i >= 0; i--){ //Need to populate the stack backwards...LIFO
s2.push(str2.charAt(i));
}
String match = ""; //Used to store the matching line
for(int i = 0; i < str1.length(); i++){
if(str1.charAt(i) == (char)s2.peek()){
match += s2.pop().toString();
}
else
{
match += " ";
}
}
System.out.println(str1);
System.out.println(match);
You can also use a Queue for this, but I will leave that for you to learn on your own. Also practice on creating your own Stack object using arrays and integer pointers to handle overflow/underflow.
The above code would print out:

How to reverse integers using while or for loop

Sorry, I am new to java. I want to create a program that displays reversed integers using any kind of loop. For example I would ask user to enter a positive integer and then I would return reversed input to the user. So far this is the closest I got, but I get the count of the string in reverse and not the values that were captured.
String number;
for (int c = number.length(); c >= 0; c--) {
System.out.print(c);
}
String number;
for (int c = number.length() - 1; c >= 0; c--){
System.out.print(number.charAt(c));
}
This should do the trick. c is the position in your string, use it to print the char at that position.
(Also, remember it's String, not string. Same for System)
Edit: Oops, forgot to add the "-1" in number.length()
You can try something likewise(either of way),
public static void main(String[] args) {
String number = "hello";
for (int c = number.length()-1; c >= 0; c--)
{
System.out.print(number.charAt(c));
}
// At the end output is : olleh
System.out.println();
// Or another way is, using StringBuffer
StringBuffer sb = new StringBuffer("Hello String");
System.out.println(sb.reverse()); //Output :- gnirtS olleH
}

Help testing two words, then printing the cross of where the same chars are

i'm trying to make a program that reads two English words from the command line, then outputs all possible ways the words can cross eachother. and print an error message if they do not cross. i want to use the charAt and length methods.. not sure where to even start..
here's what i got so far:
public class Cross2
{
public static void main(String[] args)
{
// create two dimentional array that stores input
private String[][] cross = new String[w1pos][w2pos];
// get input from user
Scanner input = new Scanner(System.in);
System.out.println("Enter two words: ");
String word1 = input.next();
String word2 = input.next();
// loop through length of words
for(int w1pos = 0; w1pos < word1.length(); w1pos++) {
for(int w2pos = 0; w2pos < word2.length(); w2pos++) {
// if characters are equal, print the array
if (word1.charAt(w1pos) == word2.charAt(w2pos))
System.out.println(cross[w1pos][w2pos]);
}
}
i think so. i would need to loop through the length of the string, then use charAt(i) to print each character.
That's a good start.
and yes crossing as in letter matching.. so i need to compare each character using charAt for each position in each of the two words
That's good. Hint: So how many loops?
and print an error message if they do not cross
Hint: ... and how will you do that?
Don't answer my questions. They are hints. Write some code based one them.
So for the words "abra" and "cadabra", would the output look like this?
c
abra
d
a
b
r
a
c
a
d
abra
b
r
a
c
a
d
a
b
r
abra
c
a
d
a
abra
r
a
c
a
d
a
b
abra
a
c
abra
d
a
b
r
a
c
a
d
abra
b
r
a
c
a
d
a
b
r
abra
If so, I would recommend that you use a two-dimensional array of characters filled with spaces that you write the words into before displaying. Printing each character one at a time might be significantly more difficult.
[edit:]
I don't know Java so I couldn't use functions and I couldn't write much more than what you had, but I hope this helps.
// This is a comment explaining what the code does.
.
/* This is a comment explaining what you need to add to make the code work. */
.
public class Cross2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter two words: ");
String word1 = input.next();
String word2 = input.next();
String[][] cross = new String[word1.length()][word2.length()];
/* Fill 'cross' with spaces */
for(int w1pos = 0; w1pos < word1.length(); w1pos++) {
for(int w2pos = 0; w2pos < word2.length(); w2pos++) {
if (word1.charAt(w1pos) == word2.charAt(w2pos)) {
// Store 'word1' horizontally into 'cross'.
for(int w1posAgain = 0; w1posAgain < word1.length(); w1posAgain++) {
/* Store 'word1.charAt(w1posAgain)' horizontally into 'cross'
at row 'w2pos' and column 'w1posAgain'. */
}
// Store 'word2' vertically into 'cross'.
for(int w2posAgain = 0; w2posAgain < word2.length(); w2posAgain++) {
/* Store 'word2.charAt(w2posAgain)' vertically into 'cross'
at row 'w2posAgain' and column 'w1pos'. */
}
for(int w1posAgain = 0; w1posAgain < word1.length(); w1posAgain++) {
for(int w2posAgain = 0; w2posAgain < word2.length(); w2posAgain++) {
System.out.print(cross[w1posAgain][w2posAgain]);
}
System.out.println();
}
/* Fill 'cross' with spaces.
Yes, really.*/
}
}
}
}
}

Categories

Resources