Reputation: 19
import java.io.*;
import java.util.*;
public class Test
{
public static String solve(String str) {
String result = "Invalid string"; // prepare result
if (null != str && str.length() % 2 == 0) { // check the null and length of the input
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i += 2) {
if (Character.isDigit(arr[i]) || Character.isDigit(arr[i + 1])) {
// if any digit found, return "Invalid string"
return result;
}
// do the swap
char t = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = t;
}
// make the result string
result = new String(arr);
}
return result;
}
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for(int i = 0; i < t; i++)
{
String str = br.readLine();
try
{
System.out.println(solve(str));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
}
Only perform the swapping if length of string is even and does not contain numeric value. if string contain numeric value then throw exception invalid input. if string length is odd then throw exception invalid length.
Test Cases :
INPUT:
4 ( represent the number of test-cases)
afafas
ajanta
sdf
sasfd3sf
OUTPUT:
fafasa
janaat
invalid string length
invalid input
Therefore swapping will be perform keep in mind these scenarios
Upvotes: 0
Views: 912
Reputation: 196
Your code needs a little correction which I have pointed out below.
public static String solve(String str) {
String result = "invalid string length"; // prepare result if the length is not correct
if (null != str && str.length() % 2 == 0) { // check the null and length //of the input
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i += 2) {
if (Character.isDigit(arr[i]) || Character.isDigit(arr[i + 1])) {
// if any digit found, return "Invalid string"
return "invalid input"; // return this as digit is found
}
// do the swap
char t = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = t;
}
// make the result string
result = new String(arr);
}
return result;
}
Upvotes: 1
Reputation: 368
I ran the above program the above test case falied are for last two cases only. The result statement alone want to be changed.by default it has given -- Invalid string
public static String solve(String str) {
String result; // prepare result
if (null != str && str.length() % 2 == 0) { // check the null and length of the input
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i += 2) {
if (Character.isDigit(arr[i]) || Character.isDigit(arr[i + 1])) {
// if any digit found, return "Invalid string"
result = "invalid input";
return result;
}
// do the swap
char t = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = t;
}
// make the result string
result = new String(arr);
}
else {
result ="invalid string length";
}
return result;
}
Upvotes: 0