Captain crunch - ROT13 encoder program - java

The Captain Crunch decoder ring works by taking each letter in a string and adding 13 to it. For example, 'a' becomes 'n' and 'b' becomes 'o'. The letters "wrap around" at the end, so 'z' becomes 'm'.
This is what I've got after editing it a bit from peoples comments, but now it keeps telling me that output may have not been initialized and I have no clue why... also is there anything else I need to fix in my program?
In this case, I am only concerned with encoding lowercase characters
import java.util.Scanner;
public class captainCrunch {
public static void main (String[] Args) {
Scanner sc= new Scanner(System.in);
String input;
System.out.print("getting input");
System.out.println("please enter word: ");
input= sc.next();
System.out.print(" ");
System.out.print("posting output");
System.out.print("encoding" + input + " results in: " + encode(input));
}//end of main
public static String encode(String input){
System.out.print(input.length());
int length= input.length();
int index;
String output;
char c;
String temp= " ";
for (index = 0; index < length; index++) {
c = input.charAt(index);
if (c >= 'a' && c <= 'm') c += 13;
else if (c >= 'n' && c <= 'z') c -= 13;
output= temp + (char)(c);
}
return output;
}
}

It's called ROT13 encoding.
http://en.wikipedia.org/wiki/ROT13
To fix your algorithm you just need:
public static String encodeString (String input) {
StringBuilder output = new StringBuilder();
for (int i=0;i<input.length;i++) {
char c = input.charAt(i)
output.append(c+13); // Note you will need your code to wrap the value around here
}
return output.toString();
}
I haven't implemented the "wrapping" since it depends on what case you need to support (upper or lower) etc. Essentially all you need to do though is look at the range of c and then either add or subtract 13 depending on where it is in the ASCII character set.

You don't have any loop iterating over the character of your string. You have to iterate other the string from 0 to string.length().

The output may have not been initialized:
String output = "";
If you don't put = "" then you have never initialized it (it's essentially random garbage, so the compiler won't let you do it).

Related

how to print count of each character in a string using java

Hey I am trying to figure out the logic in counting the each character in a string by comparing it to the first character in the string but I cannot seem to figure out the rest. If anyone can help complete this.
public class Main {
public static void main(String[] args) {
String word = "AaaaABBbccKLk";
countLetter(word);
}
public static void countLetter(String word){
int count = 0;
char firstChar = word.toLowerCase().charAt(0);
char ch;
for(int i = 0 ; i<word.length(); i++){
ch = word.toLowerCase().charAt(i);
if(ch == firstChar){
System.out.println(ch + "=" + count);
count++;
}
if(ch != firstChar && count > 0){
count=0;
System.out.println(ch + "=" + count);
count= count + 1;
}
}
}
}
I assume you may want something like this:
class Main {
public static void main(String[] args) {
String word = "AaaaABBbccKLk";
countLetter(word);
}
public static void countLetter(String word){
int[] charCount = new int[26];
word = word.toLowerCase();
for(int i = 0; i < word.length(); i++){
char letter = word.charAt(i);
int index = (int)letter - 97;
charCount[index]++;
}
for(int i = 0; i < charCount.length; i++){
System.out.println("Occurrences of " + (char)(i + 97) + " :" + charCount[i]);
}
}
}
Though this code only works for Strings with characters A-Z, you can easily make this work for a larger range of characters by expanding the size of charCount and using an ASCII table.
The way this code works is that it creates an integer array of size 26 (the number of English letters) and then lowercases the String because in programming, lowercase and uppercase letters are actually different.
Next, we iterate through the word and convert every letter into an index by converting it to its ASCII value and subtracting 97 so that we get characters in the range 0 to 25. This means that we can assign each letter to an index in our array, charCount.
From here, we just increment the element of our array that corresponds to the index of each letter.
Finally, we just print out every letter and its frequency.
Let me know if you have any questions! (Also in the future, try to give a bit more insight into your process so it is easier to guide you instead of just giving the answer).

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

Choosing a letter from the alphabet and putting quotation marks on it

I'm trying to make a program where it asks for a letter from the alphabet. Lets say I choose the letter "b". The "b" should be shown in quotation marks in the program. I'm trying to learn Java, I know HTML and CSS, but Java is new to me, so go easy.
So in practice:
Choose a letter:
d
abc"d"efghijklmnopqrstuvwxyz
I've figured out how to print the alphabet
import java.util.Scanner;
public class Characters {
public static void main(String[] args) {
char c;
for(c = 'a'; c <= 'z'; ++c)
System.out.print(c + " ");
}
}
(I have added scanner, because I'll ask the user for the letter)
A very concise example:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
char c = s.next().charAt(0);
for(char i = 'a'; i < 'z'; i++){
System.out.print(i == c ? "\""+c+"\"" : i);
}
}
}
Use java.util.Scanner's .next() to read the next word, then get the first character of the word.
Sample Run:
a
"a"bcdefghijklmnopqrstuvwxy
Since Java recognises quotation marks for text, you need to add a \ before each caracter to indicate to java that you wish for it to be part of the text. For example, if you want to show "b" with quotation mark, your final string is going to be a\"b\"cdefghijklmnopqrstuvwxyz
First, we would have to read the input char:
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0); // Get char
Then, I would make sure that our char is in the alphabet:
if(!('a' <= c && c <='z')) {
return; // NOT IN ALPHABET
}
If we got this far, we successfully read a character, which is in the alphabet.
Now, we can print out the modified alphabet.
for(char letter = 'a'; letter <= 'z'; letter++) {
if(letter == c) {
System.out.print("\"" + c + "\"");
}else {
System.out.print(letter);
}
}

How can I replace certain characters within a String in Java?

I have a program that reads an input (a String) and prints that String reversed. Now, I need to read through the reversed String and replace all of the "A"s with "T"s, the "T"s with "A"s, the "G"s with "C"s and the "C"s to "G"s. So basically, the "complement". I tried to use multiple lines with a replace function but once the "A"s are turned into "T"s, it will replace all of those into "A"s so there are no "T"s at all. How can I replace the characters so that they do not override each other?
Here is my code if it helps! I don't have any functions to get the "complement" yet, but here is what I'm working with.
import java.util.*;
public class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read;
read = new Scanner(System.in);
String input = read.next();
String reverse="";
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
}
}
You can convert your reverse string to a char array like this:
char[] charArr = reverse.toCharArray();
Then you can iterate through it and change the characters that you want:
for(int i = 0; i < charArr.length; i++){
if(charArr[i] == 'A'){
charArr[i] = 't';
}
}
At the end you can convert the char array back to a string like this:
String str = new String(charArr);
Here is a code sample that you can try:
import java.util.Scanner;
class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read = new Scanner(System.in);
String input = read.next();
String reverse="";
StringBuilder sb = new StringBuilder();
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
for (char c: input.toCharArray()) { // user 'reverse' to operate on reversed string
switch (c) {
case 'A' : sb.append('T'); break;
case 'T' : sb.append('A'); break;
case 'G' : sb.append('C'); break;
case 'C' : sb.append('G'); break;
default : sb.append(""); break; // handle you're exceptions here
}
}
System.out.println("x: " + sb);
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
read.close();
}}
Well, switch-case is a kind of mapping technique which will map your case (as key) with it's values. In this case:
I am replacing 'A' with 'T' where the string contains 'A' by appending into the StringBuilder (to create a new string) and then break; which is a mandatory statement for single time execution only.
And the default keyword is for default case, which means if all of the cases are unsatisfied to be executed then the default case is called, you can do whatever you want to do by default if no case, condition matched.
Well, for your last question, You can make it generic if the problem states some pattern; if not you, unfortunately have to do it manually.
Use the replace method, but change your values to a "temporary" character. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)
Replace T -> x
Replace A -> T
Replace x -> A
Repeat for all your pairs.

Java - Histogram program

I have a program which takes a string and gives a histogram. The problem is i need the histogram to be in order... like...
letter count
a 0
b 1
c 0
.... etc. My program will just give back the letters in the string, it will not display the letters which are not in the string. here is my main program.
import java.util.*;
public class CharacterHistogram {
//scanner and method decleration
Scanner keyboard = new Scanner (System.in);
public static void generateHistogram( String input) {
// make input lower case
input=input.toLowerCase();
int lengthOfInput= input.length();
char[] Array = input.toCharArray();
//Arrays.sort(Array);
int count = 0;
// colum creation
System.out.println();
System.out.println(" Character Count");
for (int i = 0; i < lengthOfInput; i++) {
// reset count every new letter
count = 1;
for (int x = i + 1; x < lengthOfInput; x++) {
if (Array[i] == ' ') {
break;
}
if (Array[i] == Array[x]) {
count++;
Array[x] = ' ';
}
}
// check for empty char
if (Array[i] != ' ') {
System.out.println();
//row creation
System.out.println(" "+Array[i]+" "+count);
System.out.println();
}
}
}
}
here is the tester:
public class CharacterHistogramTester{
public static void main(String [] args){
String input = "4axaaafgaa5";
System.out.println("Generate Histogram for: " + input);
CharacterHistogram.generateHistogram(input);
input = " OSU won 34-10 and now have 7 wins";
System.out.println("Generate Histogram for: " + input);
CharacterHistogram.generateHistogram(input);
}
}
i would like to know if there are any ways to show all letters (even ones not used in string) alphabetically. Thank you.
P.S. i have tried the sort(Array) method and it screws up the whole program...
Create an int array of length 26, contaning the number of occurrences of each letter (0, initially).
Loop through each char of your input, and increment the integer at the appropriate index (0 for a, 1 for b, etc.).
Then print every element of the int array.
Oh, and respect the Java naming conventios: variables start with a lowercase letter.
Use a single loop to traverse the string & count letter/character occurrences, not the unnecessary & inefficient "loop within a loop" structure which you have currently.
Initialization, counting & printing the output should be separate blocks of code -- not mangled into the same block.

Categories

Resources