I want a java code to encrypt a given string using 2 main strings like below
s1 = "qwertyuiopasdfghjklzxcvbnm";
s2 = "mnbvcxzasdfghjklpoiuytrewq";
If our input string is "mnb", then it is compared with s2 and the same index in s1 is added 3 then output will be "rty" but I am not getting proper output.
Can any one help me to solve this problem?
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for(int i=0;i<s2.length();i++){
if(input.charAt(i)==s2.charAt(i)){
out+=s1.charAt(i+3);
}
System.out.println(out);
}
sc.close();
}
You almost had the solution! The problem is when you input one of the last 3 characters of s2 you'll have to use the modulo operator (when the position gets larger than 25 you will reach the end of the string and have to start searching at the beginning!)
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
int position = s2.indexOf(input.charAt(i));
position = (position + 3) % 26;
out = out + s1.charAt(position);
}
sc.close();
}
In order to avoid wrong user input you should check the position if it's -1 (if the character is not found in s2) and handle that case properly (exception/outprint + break in the loop)
You need an extra loop to check which character matches from s2 string.Other than that,you will have to use modulo operator to avoid ArrayIndexOutOfBound.
Try this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input, out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
if (input.charAt(i) == s2.charAt(j)) {
out += s1.charAt((j + 3)%26);
}
}
}
System.out.println(out);
sc.close();
}
UPDATE
As pointed in comment by #ParkerHalo,to handle ArrayIndexOutOfBound,you can use modulo operator like this
out += s1.charAt((j + 3)%26);
Related
I'm searching for word(s) in a string array and if found I want to return their line.
I have tried to divide the searched input in an array and then search it in the paragraph array line by line. Which does not really work.
public static void main(String[] args) {
String paragraph[] = new String[10];
String toBeSearched;
String curSearch;
boolean intIndex = false ;
paragraph[0] = "Hello my name is";
paragraph[1] = "Jack the reaper";
paragraph[2] = "what up";
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int j = 0 ;j <=10 ; j++) {
curSearch = divide[j];
for (int k = 0; k <=paragraph[j].length() ; k++) {
intIndex = paragraph[j].contains(curSearch);
if(intIndex == true) {
System.out.printf("Found at line %d \n",j );
}
}
}
Assuming I can search for at most 10 words at a time.
Lets say user enters : "Hello name the up"
I want the answer : At line 1
At line 1
At line 2
At line 3
If I ask for a word in the 2nd or the 3rd index of the paragraph it does not work I dont understand why (getting no error messages)
Here is a working code compare it to yours and figure out the issue:
public static void main(String[] args)
{
String paragraph[] = {"Hello my name is","Jack the reaper", "what up"};
String toBeSearched;
String curSearch;
boolean intIndex = false ;
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int i = 0; i < divide.length ; i ++) {
String word = divide[i];
for(int y = 0; y < paragraph.length ; y++) {
if(paragraph[y].contains(word)) {
System.out.println(word+ "found at line: "+ y);
}
}
}
}
I have created a palindorme java program which is getting an error.the error is saying int cannot be converted to boolean.
import java.util.Scanner;
public class palindrome
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int l,i;
String s,s1;
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i=0;l-i-1;i++)
{
s1 = s + s.charAt(i);
}
if(s1==s)
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
}
For loop condition seems wrong.
for(initial counter; condition to terminate; increase counter) {}
for(i=0; i<l; i++) {}
Along with the answer above you can try a different approach. You don't need to go all the string length to check a palindrome. A palindrome can be checked iterating half of the array length like this -
public void checkPalindrome(String strToCheck){
char[] arr = strToCheck.toCharArray();
int size = arr.length;
char [] original = Arrays.copyOf(arr,arr.length);
for (int i = 0; i < size / 2; i++) {
char temp = arr[i];
arr[i] = arr[size-i-1];
arr[size-i-1] = temp;
}
if(Arrays.equals(arr, original)) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}
}
What are done here:
reversing the string first iterating the halfway
comparing the reversed string with the original using Arrays.equals() method.
There are quite a few things off here, first here is the fixed code:
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int l,i;
String s = "",s1 = "";
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i = l - 1; i >= 0; i--)
{
s1 = s1 + s.charAt(i);
}
if(s1.equals(s))
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
The first thing to fix was your for loop, as you saw you were getting an error. This was fixed by setting the initial i to the length minus 1, changing the loop condition to i >= 0, and using i-- to subtract 1 from i each loop.
These changes to the loop were made so that the character starting from the last position in the String is the first one being return by s.charAt(i) so you can reverse the String. I think you were attempting to do something along these lines to add the characters starting from the end to a String.
I also changed s1 = s + s.charAt(i) to s1 = s1 + s.charAt() so the correct String is being appended. (This should probably be StringBuilder however).
s and s1 now have the initial condition of "" instead of nothing.
And finally you cannot compare String equality with ==, it must be s1.equals(s).
Test Run:
Enter your string
racecar
This is Palindrome
I know there's some way to change a string into an integer but it's not really working out for me when I try to do it.
I was asked to take in an integer 'n' and 'a' string 's' and print 's' 'n' times
Here's my code and my main question / question is how do I easily turn the string into an integer so I can multiply the two together:
public static void main(String args[])
{
System.out.println("Enter the number of times you want to print a string");
Scanner n = new Scanner(System.in);
int x = n.nextInt();
System.out.println("Enter the string you want printed");
Scanner y = new Scanner(System.in);
String s = y.nextLine();
}
You only need one Scanner, and if I understand your question then you might use a loop like, also an int n.
System.out.println("Enter the number of times you want to "
+ "print a string");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
for (int i = 0; i < n; i++) {
System.out.print(s);
}
System.out.println();
Of course, you could put the loop in a method like
private static String multiply(String str, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
Then you could call it like,
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println("Enter the string you want printed");
String s = scan.nextLine();
System.out.println(multiply(s, n));
So I'm having a bit of trouble with my Computer Science class. I need to write some code that will take a string and print it backwards in reverse word order. He told me to find an empty space, then print from there and then keep searching....and repeat this until the end of the string. I typed my code out and all it does it print the first word 3 times. I know this will probably seem obvious to you guys.
public class Backwords
/*
* Gets words from main and prints in reverse order
*/
public static String BackwardsString(String str)
{
String str1 = (" " + str);
String answer = (" ");
int lastpos = str1.length();
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
return answer;
}
public static void main(String [] args)
{
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in); //gets string input
String str = firststr.next();
System.out.println(BackwardsString(str));
}
}
Set answer back to answer = "" before the second nested for loop
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
answer = "";
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
You should use StringBuilder instead of String here since there can be lot of String concatenation which may create more object in the heap.
Using StringBuilder you can do this easy way too.
Eg:
public static String BackwardsString(String str) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
return stringBuilder.reverse().toString();
}
public static void main(String[] args) {
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in);
String str = firststr.next();
System.out.println(BackwardsString(str));
}
try this
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string ");
String str = sc.nextLine();
String[] strArray = str.split(" ");
StringBuilder reverseString = new StringBuilder("");
for (int i = strArray.length - 1; i >= 0; i--) {
reverseString.append(strArray[i]+" ");
}
System.out.println("Reverse of string is : "+reverseString.toString());
You'd probably have an easier time splitting the string:
String[] words = str1.split(" ");
Then you'd work on each word[i] reversing it, you could break it down to a char array, or use a stringbuilder as others have suggested, up to you on what you think is appropriate for your class.
So I'm trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException
Here is my code for finding the uppercase letters and printing them:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
I'd really appreciate any input and or help.
for(int y = 0; y <= z; y++){
should be
for(int y = 0; y < z; y++){
Remember array index starts from ZERO.
String length returns
the number of 16-bit Unicode characters in the string
Because loop started from ZERO, loop should terminate at length-1.
The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length
Most iterating for loops should be in the form:
for (int i = 0; i < array.length; i++) {
// access array[i];
}
It's the same with a string.
Perhaps a cleaner way would be:
String inputString; // get user input
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
outputString += Character.isUpperCase(c) ? c + " " : "";
}
System.out.println(outputString);
Edit: Forgot String Doesn't implement Iterable<Character>, silly Java.
With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
.chars()
.filter(Character::isUpperCase)
.collect(StringBuilder::new, // supplier
StringBuilder::appendCodePoint, // accumulator
StringBuilder::append) // combiner
.toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase
Inspired by:
Adam Bien - Streaming A String
Simplest way to print anIntStream as a String
Try this...
Method:
public int findUpperChar(String valitateStr) {
for (int i = valitateStr.length() - 1; i >= 0; i--) {
if (Character.isUpperCase(valitateStr.charAt(i))) {
return i;
}
}
return -1;
}
Usage:
String passwordStr = password.getText().toString();
.......
int len = findUpperChar(passwordStr);
if ( len != -1) {
capitals exist.
} else {
no capitals exist.
}
Hi one of the easy step to find uppercase char in a given string...
Program
import java.io.*;
public class testUpper
{
public static void main(String args[]) throws IOException
{
String data,answer="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String : ");
data=br.readLine();
char[] findupper=data.toCharArray();
for(int i=0;i<findupper.length;i++)
{
if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
{
answer+=findupper[i]; //adding only uppercase
}
}
System.out.println("Answer : "+answer);
}
}
Output
Enter any String :
Welcome to THe String WoRlD
Answer : WTHSWRD
You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.
import java.util.Scanner;
public class P43 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
String x = in.next();
x.chars().filter(c -> Character.isUpperCase(c))
.forEach(c -> System.out.print((char) c + " "));
}
}
Sample input:
saveChangesInTheEditor
Sample output:
C I T E
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
StringBuilder s=new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.println("Enter your String");
String str= input.nextLine();
for(int i=0; i<str.length(); i++)
{
if(Character.isUpperCase(str.charAt(i)))
{
System.out.print(str.charAt(i)+" ");
}
}
}
}
The simplest way I know is to use regex replacement.
isUp = x.replaceAll("[^A-Z]", "");
In simple terms, this uses a regular expression which matches any character which is not in the A-Z range, and replaces it with an empty string.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
String str= input.nextLine();
int ascii;
for(int i=0; i<str.length(); i++) {
ascii = str.charAt(i);
System.out.println(ascii);
if (ascii >= 65 && ascii <= 90) {
System.out.println("captal letter found ::: "+ascii);
}
}
}
public class Cama {
public static void main(String[] args) {
String camal = "getStudentByName";
String temp = "";
for (int i = 0; i < camal.length(); i++) {
if (Character.isUpperCase(camal.charAt(i))) {
System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
} else if (i == 0) {
System.out.print(Character.toUpperCase(camal.charAt(i)));
}else{
System.out.print(camal.charAt(i));
}
}
}
}