why my code is not turn out the result that I want? - java

I want to define a method that input a string then return a string which character in it has been convert
public static String encode(String s){
char[] newArray = {'a','b','c','d','e','f','g','h','i','g','k','l','m'};
char[] newArray2 = {'n','o','p','q','r','s','t','u','v','w','s','y','z'};
for(int i=0; i<s.length();i++){
if(s.charAt(i) == newArray[i]){
s.replace(newArray[i], newArray2[i]);
}
}
return s;
}
public static void main(String[] args){
System.out.println(encode("firefly"));
}
but compiler just return firefly, I know there is a problem in s.charAt(i) == newArray[i] but how to define a method , for example, 'f' this single char to search through out the newArray, instead of if f correspond the first char at newArray? also how to define it when I want uppercase letter switch only with uppercase . then if I input a String like FireFly it will return SverSyl?

Because replace doesn't change the original String. It returns a new String. You need to write
s = s.replace(newArray[i], newArray2[i]);
to assign the modified String back to the variable s.

First, strings in Java are immutable. This mean you can't change them. What you can is create a new one. Second, you compare your string with the translation array to find a match at the same index. It's very difficult to find a match at the same positions and it's not what you want.
You could use the following method:
public static String encode(String s) {
StringBuffer b = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M')) {
b.append((char) ((int) c + 13));
continue;
}
if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z')) {
b.append((char) ((int) c - 13));
continue;
}
b.append(c);
}
return b.toString();
}
The idea is that you translate each character independently and add it to a string buffer. Then you return the resulting string. To transform a character between 'a' and 'm' you just add 13 to its integer code. To transform a character between 'n' and 'z' you just remove 13 from its integer code. You do the same thing for the capital letters.
When we call this method with "FireFly you were cancelled too soon"
public static void main(String args[]) {
System.out.println(encode("FireFly you were cancelled too soon"));
}
the result is:
SverSyl lbh jrer pnapryyrq gbb fbba

Strings are immutable. So technically you need to create a new object and assign it a reference. You can assign your previous string itself to it:
s = s.replace(newArray[i], newArray2[i]);

At the end of your code you are returning s but it's value has not actually been changed. You need to assign something else to that variable or else you will get the same value you input as the output.

Related

How to find out if char is number in JAVA, ONLY with string methods?

I need to find out how can I check if a char is a number. The problem is that I can't use any methods except string methods like IndexOf, SubString, length, charAt.
Does anyone have an idea?
If it has to be String methods:
String n = "0123456789";
char c = 'a'; // As I don't know where your char will come from and in what format
int i = n.indexOf(c);
if(i != -1) {
System.out.println("Digit");
} else {
System.out.println("Not digit");
}
But I can't stress enough that this is, well, idiotic and pointless from my point of view.
You can use Character.isDigit() for this.
If you have a string, you can do this :
Character.isDigit(yourString.charAt(index));
And withtout any Character method you can use Regex :
s.substring(startIndex,endIndex).matches("[0-9]")
You can check the character for its UNICODE value:
char c = string.indexOf(...); // or other way to get the character
public static boolean isDigit(char c) {
return c => '0' || c <= '9';
}
You can use the below based on the ASCII values comparison:-
String s = "123456ao";
char[] ss = s.toCharArray();
int intVal = 0;
for( char s1 : ss){
intVal = s1;
if(48 <= intVal && intVal < 58) // checking for ASCII values of numbers
System.out.println(s1+ " is Numeric");
else System.out.println(s1+ " is not Numeric");
}

Scanner.nextInt gives InputMismatchException: For input string: "222234411110000"

In my program I need to insert - between two odd numbers and * between even numbers and ignore if there is 0. For example:
Input = 99946 Output = 9-9-94*6
Input = 56647304 Output = 56*6*47-304
Method getDigits() places the digits of the entered number into array cells. Method insertDashesAsteriks() returns properly concatenated String.
But when I run my program with the following example:
Please enter the numbers so they could be rearranged:
222234411110000
Exception in thread "main" java.util.InputMismatchException: For input string: "222234411110000"
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at DashInsert2.main(DashInsert2.java:9)
then I'm getting InputMismatchException. Why am I getting the error?
import java.util.Scanner;
public class DashInsert2 {
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Please enter the numbers so they could be rearranged: ");
int nums = kbd.nextInt();
int[] numArray = getDigits(nums);
System.out.println("The array representation of the numbers is \n");
System.out.println();
String result = insertDashesAsteriks(numArray);
System.out.println("The result is " + result);
}
public static int[] getDigits(int numbers)
{
int length = Integer.toString(numbers).length();
int[] temp = new int[length];
for(int i = 0; i < length; i++)
{
temp[i] = numbers % 10;
numbers = numbers / 10;
}
return temp;
}
public static String insertDashesAsteriks(int[] numArray)
{
String temp = "";
for(int i = 1; i < numArray.length; i++)
{
if(numArray[i] % 2 == 0 && numArray[i-1] % 2 ==0)
{
temp = numArray[i-1] + "*" + numArray[i] + "*";
}
else if(numArray[i] == 0 || numArray[i-1] == 0)
{
temp = numArray[i-1] + "" + numArray[i] + "";
}
else if(numArray[i] % 2 != 0 && numArray[i-1] % 2 != 0)
{
temp = numArray[i-1] + "-" + numArray[i] + "-";
}
}
return temp;
}
}
Maximum value for int is 2,147,483,647
You entered: 222,234,411,110,000
You'll need to treat the number as a string since the number you input is past the biggest possible 32 bit integer.
Try kbd.next().charAt(0); to parse it character by character instead.
First off, if you're reading in ints, you're limited to their range. That means numbers beyond about +/- two billion are out of the question. For handling larger number, you can move to larger data types (like long) or just handle strings, which have far less stringent limitations.
Once you are handling strings, there's a far simpler way (in terms of the code you have to write) to do this substitution using regular expressions:
public class Test {
static String morph(String s) {
String oldS;
do {
oldS = s;
s = s.replaceAll("([13579])([13579])", "$1-$2");
s = s.replaceAll("([2468])([2468])", "$1*$2");
} while (! s.equals(oldS));
return s;
}
public static void main(String args[]){
System.out.println(morph("99946"));
System.out.println(morph("56647304"));
System.out.println(morph("222234411110000"));
}
}
The morph function simply modifies the string with your substitution rules until it ceases to change. The output of the test harness (using the data you supplied) is:
9-9-94*6
56*6*47-304
2*2*2*234*41-1-1-10000
Now it may be that, if this is a classwork assignment, you're limited in the language facilities you can use. But, since you haven't mentioned that, and no coder in their right mind would (usually) choose a more difficult path, you should consider the use of the regular expression method. Code that is shorter is almost always less prone to bugs.
If you don't want to use regular expressions, you can still make your code relatively short and well structured, with something like:
// Helper functions for inserting characters.
static boolean is2468 (char ch) {
return (ch == '2' || ch == '4' || ch == '6' || ch == '8');
}
static boolean is13579 (char ch) {
return (ch == '1' || ch == '3' || ch == '5' || ch == '7' || ch == '9');
}
static String morph(String str) {
// Use efficient string builder for creating morphed string.
StringBuilder newStr = new StringBuilder();
// Last/current character, starting with '0' simplifies
// start condition.
char lastCh, ch = '0';
// Process every character in string.
for (int idx = 0; idx < str.length(); idx++) {
// Transfer previous current to last, get current.
lastCh = ch;
ch = str.charAt(idx);
// Put '-' between two odds, '*' between two non-zero evens.
if (is13579(lastCh) && is13579(ch))
newStr.append('-');
else if (is2468(lastCh) && is2468(ch))
newStr.append('*');
// Put character there regardless.
newStr.append(ch);
}
// Return string version of string builder.
return newStr.toString();
}

Java character to String

I tried multiple versions, including several solutions found here on StackOverflow, but I always get numbers instead of the characters in the console. For a homework in my uni, we need to invert the characters in a string. But creating the new string seems to be not so easy.
I tried using a StringBuilder,
StringBuilder builder = new StringBuilder();
// ...
builder.append(c); // c of type char
String concatenation,
System.out.print("" + c); // c of type char
and even String.valueOf(),
System.out.print(String.valueOf(c)); // c of type char
and each of them again with explicit conversion to char. But I always get the ordinal number of the characters in a sequence instead of the actual characters as output in the console. How do I correctly build a new string from chars?
/**
* Praktikum Informatik - IN0002
* Arbeitsblatt 02 - Aufgabe 2.6 (Buchstaben invertieren)
*/
public class H0206 {
public static String readLine() {
final StringBuilder builder = new StringBuilder();
try {
// Read until a newline character was found.
while (true) {
int c = System.in.read();
if (c == '\n')
break;
builder.append(c);
}
}
catch (java.io.IOException e) {
; // We assume that the end of the stream was reached.
}
return builder.toString();
}
public static void main(String[] args) {
// Read the first line from the terminal.
final String input = readLine();
// Create a lowercase and uppercase version of the line.
final String lowercase = input.toLowerCase();
final String uppercase = input.toUpperCase();
// Convert the string on the fly and print it out.
for (int i=0; i < input.length(); ++i) {
// If the character is the same in the lowercase
// version, we'll use the uppercase version instead.
char c = input.charAt(i);
if (lowercase.charAt(i) == c)
c = uppercase.charAt(i);
System.out.print(Character.toString(c));
}
System.out.println();
}
}
The problem I see with the sample code you provided is here:
int c = System.in.read();
if (c == '\n')
break;
builder.append(c);
The way you call the method, Stringbuilder.append(int) will be called. As the javadoc says, "the overall effect is exactly as if the argument were converted to a string by the method String.valueOf(int), and the characters of that string were then appended to this character sequence". Casting the integer-value to char like this will result in the desired behavior:
int c = System.in.read();
if (c == '\n')
break;
builder.append((char) c);
Here is a sample how to invert a String, there is another options, i think this one is more didacticism
public static void main(final String[] args) {
String text = "This is a string that will be inverted";
char[] charArray = text.toCharArray();
char[] invertedCharArray = new char[charArray.length];
for (int i = 1; i <= charArray.length; i++) {
char c = charArray[charArray.length - i];
invertedCharArray[i - 1] = c;
}
System.out.println(text);
System.out.println(new String(invertedCharArray));
}
try { // Read until a newline character was found.
while (true) {
int c = System.in.read();
if (c == '\n') break;
builder.append(c);
}
From the sample you gave, I can see that this is causing the problem. Because you are reading the char input as an int, it converts the char to its ordinal value so it can be stored (and therefore used) as an integer.
In public final class StringBuilder you're calling append(int i), which returns int. If int c = System.out.read();
is required for this to be declared as an integer, you can cast c to a char.
char ch = (char)c;
builder.append(ch)
If needed, this leaves c as an integer and stores its "original value" (What it was before it was turned into an int, i.e. the key pressed) in a variable if needed. If you only need to add it to the string, without reusing it for any reason, you can cast c to a char directly with append((char) c).

Trying to toggle cases with ASCII values

Ok,I'm just an amateur in programming,so go easy on me. So, I'm coding the classic toggle cases program but without using the .toUpperCase() or the .toLowerCase() functions but instead using ASCII values of the characters. I manage to convert the upper cases to lower but cant seem to do the opposite.
package toggle;
import java.util.Scanner;
public class Toggle {
String str;
Scanner sc=new Scanner(System.in);
public void toggleStr()
{
System.out.println("Enter a string");
str=sc.nextLine();
char c;
int res;
char ch[]=str.toCharArray();
for(int i=0;i<ch.length;i++)
{
res=(int)(ch[i]);
if((res>=65)||(res<=90))
{
c=(char)(res+32);
System.out.print(c);
}
else if((res>=97)||(res<=122))
{
c=(char)(res-32);
System.out.print(c);
}
else
System.out.print(ch[i]);
}
}
public static void main(String[] args)
{
Toggle t=new Toggle();
t.toggleStr();
}
}
|| should be &&, in both cases. Any number is greater than 65 or less than 90, so the first if block gets executed each time, regardless of the character.
All values from 97 to 122 are greater than 65, so your first if condition will include the lower case as well as the upper case characters. You need to use && instead of || (and instead of or).
If we are talking about good old ASCII table then each small letter differ from big letter by only one bit (2^5, 6th bit) represented by decimal 32 or hex 0x20.
But if we are talking about XXI century unicode we can use the java std library functions.
Below I show both versions:
ASCII style:
public String toggleAscii(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
boolean isLower = (c & 0x20) == 0x20; // binary 100000 (sixth bit, 2^5)
c = (char) (isLower ? (c & 0xdf) : (c | 0x20));
}
sb.append(c);
}
return sb.toString();
}
Unicode style:
public String toggle(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean isUpper = Character.isUpperCase(c);
sb.append(isUpper ? Character.toLowerCase(c) : Character.toUpperCase(c));
}
return sb.toString();
}

How to turn uppercase to lowercase using the charAt method?

I need to create a function that will make all uppercase characters lowercase using the charAt method. I've tried to use typecasting to change the int values to char but got lost after that.
/********************************************************************************
This function will calculate the integer average of characters in the array
********************************************************************************/
public static void lowerCase(char[] letter) {
char mean;
mean = (char) ((int) ch + 32);
}
Oh, actually you don't need to check it using charAt. Just convert everything to lowercase. That will not affect the character that are already in lowercase, and convert the uppercase characters to lowercase. That's what you need.
You don't need to convert your character array to string object and then use String.toLowerCase method, because it internally uses Character.toLowerCase method only.
public static void average( char [] letter ) {
for (int i = 0; i < letter.length; i++) {
letter[i] = Character.toLowerCase(letter);
}
System.out.println(Arrays.toString(letter));
}
If you like to use only charAt, you can try:
String test = "fasdWADFASD242134";
StringBuilder result = new StringBuilder(test);
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
result.setCharAt(i, ch >= 'A' && ch <= 'Z' ? (char) (ch + 'a' - 'A') : ch);
}
System.out.println("result = " + result);
If you have an char array, you can use:
public static void toLower(char[] letter){
for (int i = 0; i < letter.length; i++) {
char ch= letter[i];
letter[i]= ch >= 'A' && ch <= 'Z' ? (char) (ch + 'a' - 'A') : ch;
}
}
If you dont have to use charAt()...
public static void average( char [] letter )
{
String str = new String(letter);
System.out.println("The value is "+str.toUpperCase());
}
Assuming you want to process the characters individually (like a charAt):
char c = letter[i]; // i = 0...len(letter-1)
char upperC = Character.toLowerCase(c);
If you don't actually want to use charAt:
String lowerCaseVersion = (new String(letter)).toLowerCase();
Try this one, looks like a working method
http://www.techlabs4u.com/2011/07/java-code-to-convert-string-to-lower.html
Just do like this:
String string = "some string";
System.out.println(string.toUpperCase());
String class has a method toUpperCase() and also toLowerCase(), which you can use to transform you String into upper or lower case letters and you don't need to use charAt method (in case you need to transform the specific letter).
"abcdefghijklmnopqrstuvwxyz".charAt(character - 'A')

Categories

Resources