Java

12 respostas
latifey

bom dia
estou tentado resolver trabalho mais nao consigo. alguem me ajuda please

Exercise III
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?. Write a method that takes a String and that returns a new String containing the
encoded version. You should assume that the String contains upper and lower case letters, and
spaces, but no other punctuation. Lower case letters should be transformed into other lower case
letters; upper into upper.
You should not encode the spaces

12 Respostas

AlexandreGama

Fala latifey !

Você chegou a tentar algo? Teria algum código onde você está com algum problema?
Aí o pessoal consegue ajudar melhor! :slight_smile:

Até mais!

Jonatas_Emidio_de_So

>Para o Caso da Substituição de caracter.
Se o que você está procurando é criar um aplicativo que substitui caracteres[a vira b], a classe String possui um método que faz isso.
String.replaceAll: Onde você entra com os caracteres que você quer substituir
Ex String.replaceAll(?a?,?b?) ? Aqui o a vira b
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)

>No caso da troca do maiúsculo para minúsculo você pode fazer uma validação utilizando a classe Character que possui os métodos:
isUpperCase: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Character.html#isUpperCase(char)
e o isLowerCase
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Character.html#toLowerCase(char)
Espero ter ajudado!

:arrow: http://varandageek.blogspot.com/

latifey

sim eu tentei algo sim

import java.util.Scanner;
public class string {

public static void main(String[] args) {
	Scanner Scr = new Scanner(System.in);
	
	System.out.println("Type your word");
	String alf = Scr.next();
    // TODO code application logic here
    String alphabet = "abcdehghijklmnopqrstuvwyz";
    alphabet = alphabet.toUpperCase();
    
   
   

if(alf('abcdehghijklmnopqrstuvwyz'){
	char letter = alphabet.charAt(13);
	System.out.println(letter);
}
else {
	System.out.println("unkown");
}
}
	
}
L

Pelo que entendi é para pegar cada caracter da String e adicionar 13 nele.

String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String str = "Texto que sera modificado";
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
    char currentChar = chars[i];
    if (Character.isLetter(currentChar)) {
        boolean isUpperCase = Character.isUpperCase(currentChar);
        currentChar = Character.toUpperCase(currentChar);
        int newIndex = letters.indexOf(currentChar) + 13;
        char newChar = '[code]String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String str = "Texto que sera modificado";
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
    char currentChar = chars[i];
    if (Character.isLetter(currentChar)) {
        boolean isUpperCase = Character.isUpperCase(currentChar);
        currentChar = Character.toUpperCase(currentChar);
        int newIndex = letters.indexOf(currentChar) + 13;
        char newChar = '\0';
        if (newIndex >= letters.length()) {
            newIndex -= letters.length();
        }
        newChar = letters.charAt(newIndex);
        if (!isUpperCase) {
            newChar = Character.toLowerCase(newChar);
        }
        chars[i] = newChar;
    }
}
String newStr = new String(chars);
System.out.println("Original: " + str);
System.out.println("Novo    : " + newStr);
'; if (newIndex >= letters.length()) { newIndex -= letters.length(); } newChar = letters.charAt(newIndex); if (!isUpperCase) { newChar = Character.toLowerCase(newChar); } chars[i] = newChar; } } String newStr = new String(chars); System.out.println("Original: " + str); System.out.println("Novo : " + newStr);[/code]
AlexandreGama

Fala latifey!

Só uma dica, tenta colocar seus códigos com a formatação de código do Fórum.
Se tiver dúvida de como fazer isso é só dar um toque!

Quanto ao seu problema, batendo o olho vi que você da um alphabet.toUpperCase
e imagino que você esteja digitando uma letra LowerCase (minúsculo normal), logo
ele não acharia o caracter.

Seria este o problema?

Até mais!

AlexandreGama

Tenta o código desta forma:

public static void main(String[] args) { 
	Scanner Scr = new Scanner(System.in); 

	System.out.println("Type your word"); 
	String alf = Scr.next();
	
	String alphabet = "abcdehghijklmnopqrstuvwyz"; 
//		alphabet = alphabet.toUpperCase(); 

	if(alphabet.contains(alf)){ 
		char letter = alphabet.charAt(13); 
		System.out.println(letter);
	} 
	else { 
		System.out.println("unkown"); 
	} 
}

Lembrando que estou usando alphabet.contains(alf) que verifica se o caracter que você digitou
existe na sua variável alphabet

Até mais!

latifey

exactamente isJunior
só os valores do String tem de ser inserido pelo usuário cuja a mesma letra inserida tem adicionar mais 13, ou seja não sei se notaste o string é o alfabeto completo.
obrigado

L

Editei o post anterior com a resolução completa. Agora tratando apenas as letras e reiniciando a contagem depois do 'z'.

String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String str = "Texto que sera modificado";
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
	char currentChar = chars[i];
	if (Character.isLetter(currentChar)) {
		boolean isUpperCase = Character.isUpperCase(currentChar);
		currentChar = Character.toUpperCase(currentChar);
		int newIndex = letters.indexOf(currentChar) + 13;
		char newChar = '[code]String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String str = "Texto que sera modificado";
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
	char currentChar = chars[i];
	if (Character.isLetter(currentChar)) {
		boolean isUpperCase = Character.isUpperCase(currentChar);
		currentChar = Character.toUpperCase(currentChar);
		int newIndex = letters.indexOf(currentChar) + 13;
		char newChar = '\0';
		if (newIndex >= letters.length()) {
			newIndex -= letters.length();
		}
		newChar = letters.charAt(newIndex);
		if (!isUpperCase) {
			newChar = Character.toLowerCase(newChar);
		}
		chars[i] = newChar;
	}
}
String newStr = new String(chars);
System.out.println("Original: " + str);
System.out.println("Novo    : " + newStr);
'; if (newIndex >= letters.length()) { newIndex -= letters.length(); } newChar = letters.charAt(newIndex); if (!isUpperCase) { newChar = Character.toLowerCase(newChar); } chars[i] = newChar; } } String newStr = new String(chars); System.out.println("Original: " + str); System.out.println("Novo : " + newStr);[/code]
AlexandreGama

Como o lsjunior indicou, se não tiver problema pra você já deixar o seu alfabeto em
Upper será melhor, mas não sei se no seu contexto é possível.

Creio que com os dois códigos você já consiga resolver o seu problema! :slight_smile:
Posta aí se tiver alguma coisa.

Ate mais!

AlexandreGama

Só lembrando,
A minha abordagem resolve apenas o seu problema em relação ao seu código que você postou,
já do nosso amigo lsjunior percorre o alfabeto para trocar os caracteres.
:wink:

Até mais!

latifey

o string tem de ser inserido pelo pelo user,
ou seja o systema pedirá para inserir um letra:
por exemplo se eu insiro o a ele automaticamente soma o a mais 13 que deve sair N mais em letras Uppercase.

gelera agradeço imenso o vosso apoio.

brigadao

L

Sim, o algoritmo que fiz é a partir da entrada dos dados, a variável str no seu caso será o retorno da leitura da String. Para ler a String vc pode usar o Scanner, BufferedReader, JOptionPane, etc.

Criado 18 de outubro de 2010
Ultima resposta 18 de out. de 2010
Respostas 12
Participantes 4