Being fairly new to Java, I have an exercise where the user will be asked to enter a word. Next, they will be asked to enter a number. Then the program will modify the word by taking the number and implementing it to change the string. For example, if the word "Hello" was entered, and the integer entered was the number "3", it will take each character in the string (Hello) and move them each 3 letters down in the alphabet, which would then make the output word "Khoor". I recently learned about method replacing (.replace) in the same chapter as this question but it seems like having to clarify every single letter with a replace would be too lengthy. This is what I have so far.
public class Lab03Exercise7 {
public static void main(String [] args)
{
// Prompt user to enter a string
System.out.print("Enter a word");
// Import Java scanner
Scanner input = new Scanner( System.in );
int numberinput;
String wordinput = input.nextLine();
// Prompt user to enter an integer
System.out.print( "Enter a number");
numberinput = input.nextInt();
}
}
You can do it as follows:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
String wordInput = input.nextLine();
System.out.print("Enter a number: ");
int numberInput = input.nextInt();
StringBuilder updatedStr = new StringBuilder();
for (char c : wordInput.toCharArray()) {
updatedStr.append((char) (c + numberInput));
}
System.out.println("Updated string: " + updatedStr);
}
}
Explanation: Break the word into an array of characters and iterate through the array. During iteration, add the number to the character and append the updated character to a StringBuilder object. Note that you can add an integer to a char value but you need to cast it before appending to the StringBuilder object.
You can use something like this:
final StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < wordinput.length(); i++) {
final char currentChar = wordinput.charAt(i);
sb.append((char)(currentChar + numberinput));
}
System.out.println(sb.toString());
So basically, we're going character by character and adding the shift that you've got from the user. here I don't handle the edge cases - where we need to rotate after z / Z
In general, this algorithm called Caesar Cipher and you can get some more info about it here: https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/
As highlighted by #maio290' comment you have to use the ascii table to solve your problem, differentiating between lowercase characters and uppercase characters. Starting from the assumption we have a 26 chars alphabet (a-z and A-Z) in the example we are translating the chars of three positions so we will have for example:
"Hello" will be translated to "Khoor"
"zed" will be translated to "chg"
In the case of z char it will be translated to c, I'm posting an example explaining the situation:
public class Caesar {
public static String encode(String original, int k) {
char[] arr = original.toCharArray();
StringBuilder encoded = new StringBuilder();
for (char ch : arr) {
char initialCharacter = Character.isLowerCase(ch) ? 'a' : 'A';
int dec = ((int)(ch - initialCharacter) + k) % 26;
encoded.append((char)(dec + initialCharacter));
}
return encoded.toString();
}
public static void main(String[] args) {
System.out.println(encode("Hello", 3)); //<-- will print Khoor
System.out.println(encode("zed", 3)); //<-- will print chg
}
}
You have to transform your char to int and after retransform it to char , differentiating between lowercase chars and uppercase chars and assuming an alphabet of 26 chars , for further details see the ascii table.
I believe this is gonna help to solve your problem. Just do not forget to handle it after 122(letter z). You can check the ASCII table here (https://theasciicode.com.ar/)
public static void main(String[] args) throws Exception {
String word = "word";
char[] arr = word.toCharArray();
int count=0;
for (char c : arr) {
//!!Handle if the sum is bigger than 122 (letter z), you need to do some easy math.
arr[count] = (char) (((int)c) + 3);
count++;
}
String newWord = new String(arr);
}
Related
For example lets say you have the string "greg". The program prompts you to enter which character to remove and you say "g", the program then prompts "Enter the g you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.)" and you enter "2". The program then outputs the new sentence which is "gre". This is a piece of my program for my CSCI class and I know how to do it using replace(), but my professors says we can only use loops and these string methods length, concat, +, charAt, substring, and equals (or equalsIgnoreCase). I can't seem to figure it out any help would be appreciated. Thank you!
As pointed out in comments, you need to maintain count for number of occurrences and build a new string skipping nth occurence(Strings are immutable in Java):
public static String removeNthCharacter(String input, char ch, int occurence) {
StringBuilder sb = new StringBuilder();
int totalOccurences = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ch) {
totalOccurences++;
if (totalOccurences == occurence) {
// Skip This character
continue;
}
}
sb.append(input.charAt(i));
}
return sb.toString();
}
I tested this and it seems to generate expected output:
public static void main(String[] args) {
System.out.println(removeNthCharacter("greg", 'g', 2));
System.out.println(removeNthCharacter("greggggeegeegggg", 'g', 6));
}
This produces this output:
src : $ java RemoveChar
gre
greggggeeeegggg
public static void main(String[] args) {
System.out.print("Enter a String : ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.print("Enter character to be removed : ");
scanner = new Scanner(System.in);
char character = scanner.next().charAt(0);
System.out.println("Possible positions of "+character+" : ");
// find all occurrences forward
for (int i = -1; (i = input.indexOf(character, i + 1)) != -1; i++) {
System.out.println(i);
}
System.out.print("Select any above index to remove : ");
scanner = new Scanner(System.in);
int index = scanner.nextInt();
System.out.println("Result : "+input.substring(0, index)+input.substring(index+1, input.length()));
}
output
Enter a String : greg
Enter character to be removed : g
Possible positions of g :
0
3
Select any above index to remove : 0
Result : reg
output
Enter a String : greg
Enter character to be removed : g
Possible positions of g :
0
3
Select any above index to remove : 3
Result : gre
Say that I need to input a series of letters for the value: letter.
And I have multiple strings such as String.s1 that contains the characters: ABC
And String.s2 is DEF and so on and so on until the end of the alphabet.
I need to write an If statement so that if I input any character from s1 it will return with the digit 1 and s2 will return the digit 2 and so on and so on. I need to be able to input all the characters I need at once.
My current messy code is:
import java.util.Scanner;
public class Assign2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
char letters;
int numbers;
String.s1 = "ABC";
String.s2 = "DEF";
String.s3 = "GHI";
String.s4 = "JKL";
String.s5 = "MNO";
System.out.print("Enter the chosen letter: ");
letters = input.letters();
if (letters.contains(s1))
numbers = 1;
else if (letters.contains(s2))
numbers = 2;
}
}
You can create a string array such as yourArray below that holds s1,s2,s3 so on. Then you can handle this in a simple loop
for(int i = 0; i< yourArray.size ; i++){
if(letters.contains(yourArray[i])){
numbers = i+1;
break;
}
}
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.
Hi guys i made this
import java.util.Scanner;
//Creates a class
public class codeString {
public static void main(String[] arg) { //creates scanne/giving name
Scanner ImBack = new Scanner(System.in);
//print out "enter any String" and asks to put in data
System.out.print("Enter any String :");
String Word = ImBack.nextLine();
int ascii = (int) Word.charAt(0);
System.out.println(ascii);
System.out.println((char) Word.charAt(0));
}
}
But when i run it it converts only 1 letter, I know that i have to make a loop..
so then i went on google and made this
for (Word.charAt(0); Word = int; Word = Word) {
System.out.println("" + Word);
}
printing lots of errors, one of them was asking for toString, but it worked with out the toString for the one letter, so i know i did loop wrong 100%, could anyone help? and will i need a
length
in there?
You need something like this :
for (int i = 0; i < Word.length(); i++) {
System.out.println(Word.charAt(i));
}
Word.length() return to you the length of your word or text
Word.charAt(i) to get character by character
You can learn also the Oracle tutorials about Arrays and do...while Loop
I am new in programming and I am trying to write a program that moves the characters in a text string a specified number of positions.
The program must include a method whose inputs will be a text string (type String) and the number of positions (type int). The output will be a string with characters shifted.
For example, moving 4 positions:
rabbit eats a carrot
it eats a carrotrabb
Now I have this partial code. I can erase first characters but I don't know how to put them to the end of this text. How can i make it?
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
char firstLetter = a.charAt(0);
b--;
a = a.substring(b);
String m = a + firstLetter ;
System.out.println("now it is "+ m);
}
If you use regex, it's just one line:
return str.replaceAll("^(.{" + n + "})(.*)", "$2$1");
import java.util.*;
public class JavaApplication5 {
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
String firstPart = a.substring(0,b); // line 1
b--;
a = a.substring(b);
String m = a + firstPart ; // line 2
System.out.println("now it is "+ m);
}
}
See the changes above in statement marked with comment line 1 and line 2.
In line 1, we are getting the first part of string and in line 2, adding at the end of second string part.
public String foo(String s, int n) {
String s2 = s.substring(0, n);
s = s.substring(n) + s2;
return s;
}
you can put a few validations on this, like null string or n is less than s.length() etc.
It is better to use modulus operator to calculate number of shifts. When initial number of shift is more than string length. Check this :
public String shift(String string,int n){
int nshift = string.length() < n ? n%string.length() : n ;
String a = string.substring(0,nshift);
return string.substring(nshift) + a ;
}
One more version. All the work is essentially done in 1 line here:
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
Anyway, the full code is:
import java.util.*;
public class ShiftLetters {
public static void main(String[] args) {
System.out.print("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.print("Enter number of positions: ");
int b = cti.nextInt();
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
System.out.println(result);
}
}
Also, you might want to be more accurate with your indentation style to improve readability.