swapping two letters in an unknown string in java - java

i am writing a program that must scramble a word. First I read in the word backwards using .reverse. Then I turned the string into a charArray.I am suppose to create a for loop to figure out if the First letter is "A" and if it is then i have to see if the next letter is not an "A". if its not then i am suppose to swap the two letters. If any of the two letters have a;ready been swapped than they cannot be swapped again.
Some examples are
Input: “TAN” Output: “ATN”
Input: “ALACTRIC” Output:“AALCTRIC”
Input: "Fork" Output:"Fork"
Here is my code so far: i cannot figure out what to put in the for loop. Thank you!
import java.util.Scanner;
public class scrambleWordRetry {
public static void main(String[] args)
{
}
public static String scramble( Random random, String inputString)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word to scramble.");
inputString = scan.nextLine();
char a[] = inputString.toCharArray();
for( int i=0 ; i<a.length-1 ; i++ )
{
}
return inputString;
}
}

I hope this code is useful for you
Scanner x = new Scanner(System.in);
String str = x.next();
System.out.println("Before Swapping" + str);
str = scramble(str);
System.out.println("After Swapping " + str);
}
public static String scramble(String inputString) {
char s[] = inputString.toCharArray();
for (int i = 1; i < s.length; i++) {
if (s[i] == 'A' || s[i] == 'a') {
char temp = s[i - 1];
s[i - 1] = s[i];
s[i] = temp;
}
}
return new String(s);
}
then if you input 'ALACTRIC' the output will be 'AALCTRIC',
'Tan = aTn',
'fork = fork'.

Related

Multiply single character by given number in String

I have one goal:
1) Multiply character in String n-times (character, String, n [int] - from user input)
Example:
User input1 (String) : future
User input2 (char) : u
User input3 (int) : 2
Output: fuutuure
First i tried with char[] array but IndexOutOfBoundsException brought me back to reality. Second try-StringBuilder but its not working aswell-empty result window. Should I use StringBuilder (and if answer is yes-how?) ? Or there is other, better solution.
Thank you for help.
package Basics.Strings;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Ex4 {
static String giveAWord() {
Scanner scanWord = new Scanner(System.in);
System.out.println("Give a word");
String word = scanWord.nextLine();
return word;
}
static char giveALetter() {
Scanner scanALetter = new Scanner(System.in);
System.out.println("Give a letter");
char let = scanALetter.next().charAt(0);
return let;
}
static int giveANumber() {
Scanner scanNumber = new Scanner(System.in);
System.out.println("Give a number");
int numb = scanNumber.nextInt();
return numb;
}
static String multiplyLetter(String word, char letter, int number) {
StringBuilder sb= new StringBuilder();
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
sb.append(i*number);
}
}
return sb.toString();
}
public static void main(String[] args) {
String word = giveAWord();
char letter = giveALetter();
int number = giveANumber();
System.out.println(multiplyLetter(word, letter, number));
}
}
There are several things in your multiplyLetter method that would make it not work.
First, you have to initialise the StringBuilder using the word so:
StringBuilder sb = new StringBuilder(word) ;
Else, your StringBuilder will be empty.
Second, you should use the insert(int pos, char c) method, so you can specify where you want tthe character inserted.
And last, you can't just multiply a char and an int and get away with it. If you want to repeatedly insert a character, I think you should use a loop.
So, in summary, try:
StringBuilder sb= new StringBuilder(word);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
for ( int j = 0 ; j < number ; j++ ) {
sb.insert(i, letter);
i++ ;
}
}
}
Notice I added i++ inside the loop, as sb.length() will increase with each character inserted.
Also, maybe someone more experienced can provide with a more efficient way than just using a loop.
If you are using at least Java 11 (eleven) then the following will work:
String word = "future";
String letter = "u";
int count = 2;
String replacement = letter.repeat(count);
String result = word.replace(letter, replacement);
Note that only method repeat(int) was added in Java 11.
Method replace(CharSequence, CharSequence) was added in Java 5
Java 8 functional way:
String alterString(String input, Character charMatch, int times) {
return input.chars()
.mapToObj(c -> (Character) c) // converting int to char
.flatMap(c -> {
if (c == charMatch) {
Character[] ca = new Character[times];
Arrays.fill(ca, c);
return Arrays.stream(ca); // stream of char c repeated 'times' times
}
return Stream.of(c);
})
.collect(
// following is the string collecting using StringBuilder form stream of characters
Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString,
);
);
}
A simple way to solve this problem is by using the following functions:
String#join
Collections#nCopies
String#replace
Demo:
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = kb.nextLine();
System.out.print("Enter the character: ");
String ch = kb.nextLine();
System.out.print("How many times to repeat?: ");
int n = kb.nextInt();
String result = str.replace(ch, String.join("", Collections.nCopies(n, ch)));
System.out.println("Result: " + result);
}
}
A sample run:
Enter the string: future
Enter the character: u
How many times to repeat?: 2
Result: fuutuure

How to reverse the word after getting a Capital letter at the end of the word in JAVA?

Suppose you have a String and a CAPITAL letter in that indicates ending of a word. For example, if you have wElovEcakE where E, E and K indicates end of the words wE, lovE and cakE respectively. You need to reverse each word (as you know where it ends). Don’t reverse the String as a whole. To illustrate, if we give wElovEcakE as input output should be EwEvolEkac. See wE became Ew, lovE became Evol and so on....
And the way i tried to approach with ..
import java.util.Scanner;
public class Alternative {
public static void main(String[]args) {
Scanner robo=new Scanner (System.in);
System.out.println("Enter a word ");
String word=robo.nextLine();
char[] array=word.toCharArray();
for(int i =0;i<array.length;i++){
int count =0;
for(int j=0;j<=("EMPTY");j++) // here i am trying to operate a loop where it will work up to the Capital letter.
count ++;
}
//Code incomplete
}
}
}
Above i have mentioned "EMPTY" in the condition part ... i want to operate a loop where my loop will work up to the capital letter , then i will count all the letter that i have counted up to capital letter then last step will be like i will make another loop where i will reverse all the letter where condition for the loop will <=count ;Example:lovE (counted 4 letters i will reverse four times back).
Can you guys help me to write the condition at "EMPTY" part if you think that my approach is correct ..
Can you guys help me to solve the problem in any other way ?
test if this works for you:
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
String textInvert = "";
int indexAnt = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
String wordSplit = word.substring(indexAnt, i + 1);
for (int j = wordSplit.length() - 1; j >= 0; j--)
textInvert += wordSplit.charAt(j);
indexAnt = i + 1;
}
}
System.out.println(textInvert);
Here is my solution with Regex pattern
String[] in = "wElovEcakE".replaceAll("([A-z]+?[A-Z])","$1,").replaceAll(",$","").split(",");
String out = "";
for(String current: in){
StringBuilder temp = new StringBuilder();
temp.append(current);
out+=temp.reverse();
}
System.out.println(out);
Result:
EwEvolEkac
Here is a solution that makes use of the StringBuilder class to hold and reverse each found word.
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word:");
String word = robo.nextLine();
robo.close();
String upperCase = word.toUpperCase(); //used to find uppercase letters
StringBuilder builder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char nextChar = word.charAt(i);
builder.append(nextChar);
if (nextChar == upperCase.charAt(i)) {
String subWord = builder.reverse().toString();
System.out.print(subWord); //It's not clear what to do with the found words
builder = new StringBuilder();
}
}
System.out.println();
Example
Enter a word:
makEmorEpiE
EkamEromEip
You can try this solution:
String textInvert = "wElovEcakE";
String revertText = textInvert
.chars().mapToObj(c -> (char) c)
.reduce(new LinkedList<>(Arrays.asList(new StringBuilder())), (a, v) -> {
a.getLast().append(v);
if (Character.isUpperCase(v)) {
a.add(new StringBuilder());
}
return a;
}, (a1, a2) -> a1)
.stream()
.map(s -> s.reverse())
.reduce(StringBuilder::append)
.map(StringBuilder::toString)
.get();
System.out.println(revertText);
public class Alternative {
public static void main(String[] args) {
Scanner robo = new Scanner(System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
char[] array = word.toCharArray();
int count = -1;
for (int i = 0; i < array.length; i++) {
if (Character.isUpperCase(array[i])) { //find the upper case letters in the word
for (int j = i; j > count; j--) //loop through the letters until the last count variable value is encountered
System.out.print(array[j]); //print the reversed values
count = i; //assign the last encountered uppercase letter's index value to count variable
}
}
}
}

why does "ig" repeat twice?

I was given to code something similar to piglatin. But I am getting the "ig" of pig in latin. What is wrong with the code?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
String end = "ay";
int i, j;
String word = "";
String[] arr = str.split(" ");
for (j = 0; j < arr.length; j++) {
String indWord = arr[j];
char c = indWord.charAt(0);
for (i = 1; i < indWord.length(); i++) {
word = word + indWord.charAt(i);
}
String res = "";
res = word + c + end + " ";
System.out.print(res);
}
}
}
Axpected:
pig latin ----> igpay atinlay
Actual:
Because you are not clearing the word variable for each iteration... that was hard to see because your indentation is wrong.
Move the String word=""; line to the inside of the for(j=0;j<arr.length;j++){ loop so that the word variable is cleared for every word and you start over (instead of carrying its contents from the last word)

Java - moving first letter of string to the end, and determining if word is the same when spelled backwards

I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.
e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.
Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.
Thank you in advance for any help.
Jack
This is what I've got so far, but I don't think it works properly.
public class WordPlay {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word;
String palindrome = "";
String quit = "quit";
do {
System.out.print("Enter a word: ");
word = scanner.nextLine().toUpperCase();
int length = word.length();
for (int i = length - 1; i >= 0; i--) {
palindrome = palindrome + word.charAt(i);
}
if (word.equals(palindrome)) {
System.out.println("Is the word + palindrome + " same as " + word + "?", true);
} else {
System.out.println(false);
}
} while (!word.equals(quit));
System.out.println("Good Bye");
scanner.close();
}
}
Here it is.
public static void main(String[] args) {
// To take input.
Scanner scan = new Scanner(System.in);
System.out.print("Enter Word: ");
String word = scan.next(); // taking the word from user
// moving first letter to the end.
String newWord = word.substring(1) + word.charAt(0);
// reversing the newWord.
String reversed = new StringBuffer(newWord).reverse().toString();
// printing output.
System.out.println("You have entered '"+word+"'. "
+ "Is "+newWord+" same as "+word+"? "
+reversed.equals(word)+".");
// closing the input stream.
scan.close();
}
This works:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
String s1 = scan.next();
char s2 = s1.charAt(0);
String s3 = s1.substring(1) + s2;
s3 = new StringBuilder(s3).reverse().toString();
if(s1.equals(s3))
System.out.println("They are same");
else
System.out.println("They are not the same");
}
}
This is very simple with some of observation. Your question is you have to move the first latter to the end and check reverse if the new string is same or not.
My ovservation:
For BANANA new string is ANANAB. Now reverse the string and check weather it is same as the first one.
Now If you ignore the first char B the string will be ANANA. As you have to reverse the string and check this one is same as the first one so this is like palindrome problem. For the input BANANA ANANA is palindrome. We are moving the first char to the end so there is no impact of it on checking palindrome. So I ignore the first char and check the rest is palindrome or not.
The Method is like:
private static boolean getAns(String word) {
int st = 1;
int en = word.length() - 1;
while (st < en) {
if (word.charAt(en) != word.charAt(st)) {
return false;
}
st++;
en--;
}
return true;
}
The main function is:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input your String:");
String word = scanner.nextLine();
boolean ans = getAns(word);
System.out.println("You have entered " + word + ". Is " + word.substring(1) + word.charAt(0) + " same as " + word + "? : " + ans + ".");
}
The Runtime for this problem is n/2 means O(n) and no extra memory and space needed,
I have tried to code it. See if it helps
import java.util.Scanner;
class StringCheck
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
String tempstr = new String();
System.out.println("Enter your String ");
str = sc.next();
int len = str.length();
//putting first character of str at last of tempstr
for (int i = 1 ; i<len; i++)
{
tempstr += str.charAt(i);
}
tempstr += str.charAt(0);
//reversing tempstr
char[] tempchar = tempstr.toCharArray();
int j = len-1;
char temp;
for ( int i = 0; i<len/2 ; i++)
{
if(i<j)
{
temp = tempchar[i];
tempchar[i] = tempchar[j];
tempchar[j]= temp;
j--;
}
else
break;
}
//reversing completed
tempstr = new String(tempchar);
// System.out.println("the reversed string is "+tempstr);
if(str.compareTo(tempstr)==0)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
}

By using while/for loop, how to subtract ONLY the uppercase of a line input by users?

Here is my code, i used is.upperCase to check but it doesn't seem to work. And i have trouble concatenating all the uppercases together. Any suggestion and help would be appreciated!
import java.util.Scanner;
public class UpperCase {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.next();
int i = 0;
while (i < str.length() - 1) {
if(Character.isUpperCase(i)) {
char upperLetter = str.charAt(i);
}
Object outputLetter = str.charAt(0) + str.charAt(i++);
char upperLetter = str.charAt(i++);
}
System.out.println("The uppercase letters are:" );
}
}
I guess below would solve your problem.
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.nextLine();
char[] cr = str.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
for(int i=0;i<cr.length;i++){
if(Character.isUpperCase(cr[i])){
stringBuffer.append(cr[i]);
}
}
System.out.println("The uppercase letters are:" + stringBuffer);
First, your idea is correct, but the way you did implement has some mistakes
1. isUperCase of i -> Wrong
2. outputLetter should be declare outside the loop to advoid re-init data
3. outputLetter should be something like outputLetter += anUpperCase
4. finally, refer this bellow code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.next();
in.close();
int i = 0;
String result = "";
while (i < str.length() - 1) {
char aChar = str.charAt(i);
if (Character.isUpperCase(aChar)) {
result += aChar;
}
i++;
}
System.out.println("The uppercase letters are: " + result);
}

Categories