I have been working on this for hours and now Im kinda stuck....please help me.
Im a complete programming handicap. All the methods work fine except the alphabet one.
It will receive two characters (either upper or lower case) and return a string composed of the range of char values given. Maintain the same case (upper or lower) that was passed in to the method. If an upper case and a lower case char (one of each) was passed to the method, convert the upper case char into lower case and use the lower case range. Note, the range will be inclusive of the starting char and exclusive of the ending char. Also, observe that if the starting (first) char given is greater than the ending (second) char, for example 'm' and 'h', then the method will return an empty string since there are no chars in this range.
Can you give me some help on how I can do the above on the alphabet method?
import java.util.*;
class CharacterOperations
{
public static void run()
{
int number=1;
Scanner scanner = new Scanner(System.in);
while(number > 0)
{
System.out.println("(1) Insert 1 to change a letter from its lower case value to its upper case value");
System.out.println("(2) Insert 2 to change a letter from its upper case value to its lower case value ");
System.out.println("(3) Insert 3 for the alphabet method (range of two letters) ");
System.out.println("Enter a number (or negative to quit): ");
number = scanner.nextInt();
if (number == 1)
{
System.out.print("Enter a lower case letter: ");
String a= scanner.next();
char letter = (char) a.charAt(0);
toUpper(letter);
}
else if (number == 2)
{
System.out.print("Enter an upper case letter: ");
String a= scanner.next();
char letter = (char) a.charAt(0);
toLower(letter);
}
else if (number == 3)
{
System.out.print("Enter an upper case or lower case letter: ");
System.out.print("Enter an upper case or lower case letter: ");
String a= scanner.next();
char letter1 = (char) a.charAt(0);
String b= scanner.next();
char letter2 = (char) b.charAt(0);
alphabet(letter1, letter2);
}
}
}
public static char toUpper(char letter)
{
int rep = ((int)letter - 32);
char ltr = (char)rep;
System.out.println("The letter "+ ltr + " integer representation is: " + rep);
return (char) ((int) letter -32);
}
public static char toLower(char letter)
{
int rep = (int)(letter + 32);
char ltr = (char)rep;
System.out.println("The letter " + ltr + " integer representation is: " + rep);
return (char) ((int) letter + 32);
}
public static String alphabet( char letter1, char letter2){
int rep1 = (int)letter1;
int rep2 = (int)letter2;
char ltr1 = (char)rep1;
char ltr2 = (char)rep2;
System.out.println("The letter " + ltr1 + " integer representation is: " + rep1);
System.out.println("The letter " + ltr2 + " integer representation is: " + rep2);
}
}
Thanks!
for (char c = 'a'; c <= 'z'; c++) {
System.out.println(c);
}
it's very simple ^_^
With a char you can just ++ it to get the next char and so on.
char a = 'a';
a++; // now you have b
a++; // now you have c
Just do a while loop to go from start to end char.
Use this to first to generate a random letter. You first have to generate a random number within a certain range. Then when you get the number back and store it in a char variable, it shows it as a letter.
char letter = 0;
letter = (char) (65 + (char)(Math.random() * (90 - 65) + 1));
This answaer assumes you are just talking about standard keyboard characters from the ASCII set.
Take the ascii codes for the 2 charaters and create a loop:
StringBuilder buf = new StringBuilder();
for (int i = rep1; i <= rep2; ++i)
buf.append((char)i);
return buf.toString();
This will work as they both need to be same case...
public static String alphabet(char letter1, char letter2) {
StringBuffer out = new StringBuffer();
for (char c = letter1; c < letter2; c++) {
out.append(c);
}
return out.toString();
}
Obviously you should add some error checking and handling
Simple solution:
String str = "A"
char cr = str.charAt(0);
System.out.println((cr += 1)); //got B
public static String alphabet( char letter1, char letter2){
expects to return a String because you said public static "String"
take out the String and this should work, replace it by void if you just want to print with System.out.print. or return the string that your making
beside that my advise for going to uppercase and lowercase would have been to convert the char to a String and just use the java built in method.
Related
This is what I have so far. I'm unsure how to print the individual value of each char in ascii without the values repeating on every line. Any help would be appreciated.
Create a for loop to print out all of the ASCII values associated with EACH
character of the town name or pet name (e.g., R = 125, a = 97 etc.)
import java.util.Arrays;
public class Lab1Part2{
public static void main (String[] args){
char B = 'B';
char l = 'l';
char a = 'a';
char n ='n';
char h = 'h';
int ascii = B;
//create array
char[] JavaCharArray = new char[6];
JavaCharArray[0] = 'B';
JavaCharArray[1] = 'l';
JavaCharArray[2] = 'a';
JavaCharArray[3] = 'n';
JavaCharArray[4] = 'c';
JavaCharArray[5] = 'h';
//print array
for(int i=0;i<JavaCharArray.length;i++){
System.out.println(JavaCharArray[i] + " = " + ascii);
}
}
}
The char type in Java is legacy, essentially broken. As a 16-bit value, it is incapable of representing most characters.
Code points
Instead, learn to use code point integer numbers to work with individual characters.
int[] codePoints = "Blanch😷".codePoints().toArray() ;
for( int codePoint : codePoints )
{
System.out.println( "character: " + Character.toString( codePoint ) + " = code point: " + codePoint ) ;
}
See this code run live at IdeOne.com.
character: B = code point: 66
character: l = code point: 108
character: a = code point: 97
character: n = code point: 110
character: c = code point: 99
character: h = code point: 104
character: 😷 = code point: 128567
You will find "codePoint" related methods around various classes such as String, Character, StringBuilder. See also: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
You need to calculate "ascii" every time you enter the loop (iteration). char can be casted to int automatically
//print array
for(int i=0; i<JavaCharArray.length; i++){
ascii = JavaCharArray[i];
System.out.println( JavaCharArray[i] + " = " + ascii);
}
btw: you declare a few char variables at the start but never use them. For example, you probably wanted to do JavaCharArray[0] = B; rather than JavaCharArray[0] = 'B';
You need to cast the characters to int:
public static void main(String[] args) {
//create array
char[] JavaCharArray = new char[6];
JavaCharArray[0] = 'B';
JavaCharArray[1] = 'l';
JavaCharArray[2] = 'a';
JavaCharArray[3] = 'n';
JavaCharArray[4] = 'c';
JavaCharArray[5] = 'h';
//print array
System.out.print("(");
for (int i = 0; i < JavaCharArray.length; i++) {
System.out.print(JavaCharArray[i] + " = " + (int) JavaCharArray[i]+ ", ");
}
System.out.print(")");
}
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).
I'm trying to write a program that will input a sentence, and then two letters, and then switch all instances of those letters and then print out the switched sentence. For instance, they could input
I like to eat bananas
and then “e” and “a,” and my program would print
I lika to aet benenes
Here is my code, but at the end it prints out String Index out of line.
Any ideas how to fix this?
System.out.println("Write something awesome.");
String input1 = Keyboard.readString();
System.out.println("Pick a letter from that awesome sentence.");
char letter1 = Keyboard.readChar();
System.out.println("Pick another letter from that awesome sentence.");
char letter2 = Keyboard.readChar();
double let1 = (input1.length());
int let1Next = (int) let1;
double let2 = (input1.length());
int let2Next = (int) let2;
String newUserImput = input1.replace(input1.charAt(let1Next),
input1.charAt(let2Next));
System.out.println(newUserImput);
Without a stack trace, I have to guess the exception is on this line.
String newUserImput = input1.replace(input1.charAt(let1Next),
input1.charAt(let2Next));
What does input1.charAt(let1Next) resolve to?
double let1 = (input1.length());
int let1Next = (int) let1;
double let2 = (input1.length());
int let2Next = (int) let2;
This can't really be what you mean.
let1Next will represent the end of the array + 1 as will let2Next.
Therefore, there are 2 major bugs here:
You are replacing all occurrences of a given character with itself.
The letter you are picking is beyond the end of the string. Remember, string indexes (such as the input to String.charAt) are 0-based, so the they range from 0 through (length - 1). By specifying input1.length, you are asking for the character after the last character of the string, hence the StringIndexOutOfBoundsException.
You can iterate over array that contains all characters of user sentence (you can get such array using toCharArray method invoked on input1) and if you find letter1 replace it with letter2 and vice-versa.
After that you can create new string based on updated array with new String(arrayOfCharacters).
The method replace will replace all chars in the string
So what you want is
String new1 = input1.replace (letter1, letter2);
String new2 = input1.replace (letter2, letter1);
Then iterate over the original string to see what is different in new1 and new2.
Try using char array-
char letter1 = 'a';
char letter2 = 'e';
String s = "I like to eat bananas";
char[] chrs = s.toCharArray();
int n = chrs.length;
for (int i = 0; i < n; i++) {
if (chrs[i] == letter1) {//if array contains letter1 at intdex i
chrs[i] = letter2; //replace with letter 2
} else if (chrs[i] == letter2) { //if array contains letter2 at intdex i
chrs[i] = letter1;//replace with letter 1
}
}
String swapedString = new String(chrs);
System.out.println(swapedString );
try with this.
char[] cs = input1.toCharArray();
for (int i = 0; i < cs.length; i++) {
char c = cs[i];
if (letter1 == c) {
cs[i] = letter2;
} else if (letter2 == c) {
cs[i] = letter1;
}
}
String newUserImput = new String(cs);
You are getting String index out of line because you tried to access characters outside of the string (valid range is from 0 to length-1). And even if you used length-1, your code will not do what you want. What you really need is to have two dummy placeholders (I assume your string will never contain '#' or '$') replacing 'a' and 'e' and then swap 'a' and 'e' with the dummy placeholders. The code follows:
System.out.println("Write something awesome.");
String input1 = "I like to eat bananas";//Keyboard.readString();
System.out.println("Pick a letter from that awesome sentence.");
char letter1 = 'e';
System.out.println("Pick another letter from that awesome sentence.");
char letter2 = 'a';
// dummy placeholders
char letter3 = '#';
char letter4 = '$';
String newUserImput = input1.replace (letter1, letter3);
newUserImput = newUserImput.replace (letter2, letter4);
newUserImput = newUserImput.replace (letter3, letter2);
newUserImput = newUserImput.replace (letter4, letter1);
System.out.println(newUserImput);
I've been trying and trying and there is no way.
I want to spend a lowercase letter to uppercase equivalent.
I know and know how to use the method toUpperCase () but I want to do without it.
This is my failing code:
import java.util.Scanner;
public class ConvertLetters {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.print("enter a lower case letter");
char letter = stdin.nextLine();
int letter2 = 'A' + (letter - 'a');
System.out.println("and we will refund your letter capitalized");
System.out.print("Your letter: " + letter);
System.out.print("upper case equates to:");
System.out.print(letter2);
}
}
You want to finish with a char
char letter = stdin.nextLine().charAt(0);
char letter2 = (char) ('A' + (letter - 'a'));
or
char letter2 = (char) (letter - 32);
I see two problems with this code. First, you assign nextLine(), which is a string. You may want something like
char letter = stdin.nextLine().charAt(0);
instead. Second, you print int, try
System.out.print((char)letter2);
With these changes, I think your code will give you better results.
Naturally, that won't work for non-ascii characters, anyway.
What is the method for converting strings in Java between upper and lower case?
String#toLowerCase and String#toUpperCase are the methods you need.
There are methods in the String class; toUppercase() and toLowerCase().
i.e.
String input = "Cricket!";
String upper = input.toUpperCase(); //stores "CRICKET!"
String lower = input.toLowerCase(); //stores "cricket!"
This will clarify your doubt
Yes. There are methods on the String itself for this.
Note that the result depends on the Locale the JVM is using. Beware, locales is an art in itself.
String#toLowerCase
Assuming that all characters are alphabetic, you can do this:
From lowercase to uppercase:
// Uppercase letters.
class UpperCase {
public static void main(String args[]) {
char ch;
for(int i=0; i < 10; i++) {
ch = (char) ('a' + i);
System.out.print(ch);
// This statement turns off the 6th bit.
ch = (char) ((int) ch & 65503); // ch is now uppercase
System.out.print(ch + " ");
}
}
}
From uppercase to lowercase:
// Lowercase letters.
class LowerCase {
public static void main(String args[]) {
char ch;
for(int i=0; i < 10; i++) {
ch = (char) ('A' + i);
System.out.print(ch);
ch = (char) ((int) ch | 32); // ch is now uppercase
System.out.print(ch + " ");
}
}
}
Coverting the first letter of word capital
input:
hello
world
String A = hello;
String B = world;
System.out.println(A.toUpperCase().charAt(0)+A.substring(1) + " " + B.toUpperCase().charAt(0)+B.substring(1));
Output:
Hello World