I'm writing a program that's supposed to replace all of the instances of a single letter with another letter. I have some restrictions on the code though, I'm only allowed to use the String methods .length, .substring, .indexOf, and .equals. I can concatenate things using + instead of .concat.
My problem right now is, when I'm printing my results to the program, the answer has to be contained in a variable. I was previously using this code before I realized this:
if (userCommand.equalsIgnoreCase("replace all")) {
System.out.println("Enter the character to replace");
String replace = keyboard.nextLine();
System.out.println("Enter the new character");
String replaceWith = keyboard.nextLine();
int count = 0;
System.out.print("The new string is: ");
while (lastCharacter >= 0) {
char nextCharacter = userString.charAt(count);
count++;
String nextCharacterString = nextCharacter + "";
if (nextCharacterString.equals(replace)) {
nextCharacterString += replaceWith;
}
System.out.print(nextCharacterString);
lastCharacter--;
}
System.out.println("");
}
As you can see, this prints each character to the console one by one, instead of as a variable that can be manipulated later. The code I'm using right now (it is nowhere near working) is:
if (userCommand.equalsIgnoreCase("replace all")) {
System.out.println("Enter the character to replace");
String replaceString = keyboard.nextLine();
char replace = replaceString.charAt(0);
System.out.println("Enter the new character");
String replaceWithString = keyboard.nextLine();
char replaceWith = replaceWithString.charAt(0);
String allLetters = "";
int count = 0;
int indexOfReplacement = 0;
for (int i = 0; i < length; i++) {
char nextCharacter = userString.charAt(count);
count++;
if (replace == nextCharacter) {
indexOfReplacement = count;
nextCharacter = replaceWith;
}
}
String sub1 = userString.substring(0, indexOfReplacement);
System.out.println(sub1);
}
Any help would be very much appreciated.
Here is a small snippet I wrote up. I made some assumptions about the contents of variables to make it be able to run, but it works, replacing all instances of replace with replaceWith:
String your_string = ""; // Variable to copy the new string into
String userString = "this_string"; // String to do replacement on
int lastCharacter = userString.length() - 1; // Length of inputted string
String replace = "g"; // Thing to replace
String replaceWith = "d"; // Thing to replace with
int count = 0; // Index of character in string
while(lastCharacter >= 0) {
char nextCharacter = userString.charAt(count);
String nextCharacterString = nextCharacter + "";
if (nextCharacterString.equals(replace)) {
nextCharacterString = replaceWith; // I changed += to = because we want to replace, not add
}
System.out.print(nextCharacterString);
your_string = your_string + nextCharacterString; // This is where we add the correct character to the string
lastCharacter--;
count++;
}
you can use an arraylist
ArrayList<String> list=new ArrayList<String>();
while(lastCharacter >= 0)
{
char nextCharacter = userString.charAt(count);
count ++;
String nextCharacterString = nextCharacter + "";
if (nextCharacterString.equals(replace))
{
nextCharacterString += replaceWith;
}
System.out.print(nextCharacterString);
list.add(nextCharacterString);
lastCharacter --;
}
so you can manipulate it later
Related
I am trying to reduce the string array by using a for a loop. This is an example I tried to do
User string input: Calculus
User input:5
output: CalcuCalcCalCaC
I have turned the string to a char array but the issue presents itself when trying to print them out multiple times. It only prints once and has the right starting output.
input string: Oregon
input number: 4
output: Oreg
I notice my for loop says that it is not looping when I hover over it on the IDE that I downloaded from JetBrains.
I tried different combinations of decrementing and incrementing but could not get that "for statement is not looping". Other than that I have tried different ways to do something in the for loop but I don't think anything needs to be done for now if the for loop is not looping then, right?
So my question is, how to reduce a string or char array and print the decrement value over and over again?
Here is my code so far for it.
public String wordDown(String userString, int userNum)
{
String stringModded = userString.substring(0, userNum);
char[] charArray = stringModded.toCharArray();
char repeat = ' ';
for(int i = 0; i<userNum; ++i)
{
repeat = (char) (repeat +charArray[i]);
charArray[i] = repeat;
for(int j = 1; i > charArray.length; ++j)
{
String modWord = String.valueOf(charArray[i + 1]);
return modWord;
}
}
return null;
}
public static void main(String[] args)
{
int userNumber;
String userString;
RandomArrayFunctionalities ranMethod = new RandomArrayFunctionalities();
Scanner in = new Scanner(System.in);
System.out.println("\nEnter a word:");
userString = in.next();
System.out.println("\nEnter a number within the word scope that you just enter:");
userNumber = in.nextInt();
System.out.println(ranMethod.wordDown(userString, userNumber));
}
You do not need to modify the original array. Use a StringBuilder to concatenate the successive parts of the word. Use the String.substring(int,int) method to pull out those parts. The example that follows uses a decrementing index to generate the successively smaller substrings.
public String wordDown(String word, int userNum) {
StringBuilder sb = new StringBuilder();
for (int length = userNum ; length > 0 ; --length) {
sb.append(word.substring(0, length));
}
return sb.toString();
}
I think you are over complicating things, you don't need a char array at all and you only need a single loop, and a single return statement:
public String wordDown(String userString, int userNum) {
String finalString = "";
for (int i = 0; i < userNum; ++i) {
finalString = finalString + userString.substring(0, userNum - i);
}
return finalString;
}
Simply loop up to the inputted number and substring from 0 to inputtedNumber - loopCounter and append the result to the previously held String value.
Example Run:
Enter a word:
Calculus
Enter a number within the word scope that you just enter:
5
CalcuCalcCalCaC
Sidenote:
Technically you would want to use StringBuilder instead of appending String in a loop, but that is probably out of the scope of this question. Here is that version just for reference:
public String wordDown(String userString, int userNum) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < userNum; ++i) {
sb.append(userString.substring(0, userNum - i));
}
return sb.toString();
}
So the problem that I am currently running into is that the statement "Enter your command (reverse, replace first, replace last, remove all, remove)" is printing twice after I go through all the steps.
What I believe is happening is the loop is executing twice but I don't know why. Any help would be appreciated in solving this problem. Sorry in advance if my code formatting is bad still learning how to properly format.
import java.util.Scanner;
public class StringChangerenter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
// While loop
while (!command.equalsIgnoreCase("quit")) {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
// Bracket for while loop
}
}
}
The reason you are getting two entries after you've processed a character, is that you have not fully read the line containing the character.
Specifically, you use keyboard.nextInt(); in the upper branch, and keyboard.next(); in the lower branch. While these read the next integer and character, respectively, they do not process the end of line marker.
Then when you reach the top of the loop, you call keyboard.nextLine() which processes whatever characters occurred after the int (or character, in the remove all case) until the end of line marker. With the expected user input, that's just an empty string.
To fix this, you need to ensure you read all the way through the keyboard.nextLine() in the cases where you are reading only integers, or a single character.
what is happening is, the condition for you while loop is
while (!command.equalsIgnoreCase("quit"))
which in english mean, as long as command is not equal to "quit" then run this loop.
Inside the loop, command is never actually set to "quit". ex if I give input string as "abcde" and ask to remove "c" at position 1.
Then your logic sets command to "remove" here
command = keyboard.nextLine();
and then prints the final value as "abde". Now when the loop ends, command is still "remove" and hence the loop executes again.
A possible solution is to explicitly ask the user if he wants to retry using a do while loop. Also just a tip, i see you have used nextInt. It is advisable to use a nextLine immediately after next int. see this for the reason why: Java Scanner doesn't wait for user input
this is what you code would be if you explicitly took user consent if you want to run any more commands:
public static void main (String[] args) throws java.lang.Exception
{
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
String retry = "";
// While loop
do {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
keyboard.nextLine();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
System.out.println("Do you want to go again?");
retry = keyboard.nextLine();
// Bracket for while loop
}while("yes".equalsIgnoreCase(retry));
}
I would like to split this input: 12132002(177) 012(207.5) 014(184) into two arrays, like this:
num[500] = 12132002,012,014, etc.
and
mark[500] = 177,207.5,184, etc.
The Fact is that I'm accepting values from user like this, where i don't know the total number which he/she will input.
How can I code in Java that kind of splitting? Is it like this?
int number[500];
for(int i=0;i<500;i++) {
number=num.split("//(");
}
To code "that kind of splitting", you will have to:
Declare your variables: String[] number, String[] mark, String num, and String[] numSplit.
Split num by " " (spaces). Assign this to numSplit.
Loop through numSplit from 0 to numSplit.length with i.
Set number[i] to numSplit[i] from the beginning to the first occurrence of a "(".
Set mark[i] to numSplit[i] from one character after the first occurrence of "(" to one character before the end.
Output number and mark
The full code:
String[] number = new String[500]; //1
String[] mark = new String[500];
String num = "12132002(177) 012(207.5) 014(184)";
String[] numSplit = num.split(" "); //2
for(int i = 0; i < numSplit.length; i++) { //3
number[i] = numSplit[i].substring(0, numSplit[i].indexOf("(")); //4
mark[i] = numSplit[i].substring(numSplit[i].indexOf("(") + 1, numSplit[i].length() - 1); //5
}
for(int i = 0; i < number.length; i++) System.out.println(number[i]); //6
for(int i = 0; i < mark.length; i++) System.out.println(mark[i]);
Which outputs:
12132002
012
014
null (x497)
177
207.5
184
null (x497)
Notice that number, mark, and numSplit are String arrays because the leading zeros would be cut off in not otherwise. If you don't mind the leading zeros being cut off then you can change num to an int array and mark to a double array (Because of the decimal in 207.5).
Ok buddy, this could be a solution for your problem. I chose to use the methods I have already created for some other project, but I think those can fit for this purpose as well, instead of using some complex REGEX expression. The output is good, though you have to figure out the way you want to store num and mark variables (I suggest arrays). Hope I helped.
public class Example {
public static void main(String[] args) {
String s = "12132002(177)012(207.5)014(184)";
// output 12132002,012,014 && 177,207.5,184
// it works good with this string as well -> s = "12132002(177)012(207.5)014(184)111(024)";
int numOfParanthesis = numOfParanthesis(s, '(');
String num = "";
String mark = "";
// array which contains positions of (
int[] indexesOpening = indexes(s, '(');
// array which contains positions of )
int[] indexesClosing = indexes(s, ')');
// logic
for(int i = 0; i < numOfParanthesis; i++){
if(i == 0){
num = s.substring(i, indexesOpening[i])+",";
mark = s.substring(indexesOpening[i]+1,indexesClosing[i])+",";
}else if(i!=numOfParanthesis-1){
num += s.substring(indexesClosing[i-1]+1, indexesOpening[i])+",";
mark += s.substring(indexesOpening[i]+1, indexesClosing[i])+",";
}else{
num += s.substring(indexesClosing[i-1]+1, indexesOpening[i]);
mark += s.substring(indexesOpening[i]+1, indexesClosing[i]);
}
}
System.out.println(num);
System.out.println(mark);
}
// returns array of positions for the given character
public static int[] indexes(String s, char c){
int numOfParanthesis = numOfParanthesis(s, c);
int[] indexes = new int[numOfParanthesis];
int delimetar = s.indexOf(c);
for(int i = 0; i < numOfParanthesis; i++){
if(i != -1){
indexes[i] = delimetar;
}
delimetar = s.indexOf(c, delimetar+1);
}
return indexes;
}
// returns how many times a character repeats in a string
public static int numOfParanthesis(String s, char c){
int number = s.indexOf(c);
int i = 0;
while (number >= 0){
number = s.indexOf(c, number+1);
i++;
}
return i;
}
}
Try this:
public class Test {
public static void main(String[] args) {
// Guess this is a string since it is a mix of integers
// and non-integers, characters like '(', ')' and space.
String str = "12132002(177) 012(207.5) 014(184)";
System.out.println("Your string:");
System.out.println("str=\"" + str + "\"");
System.out.println();
// remove all ')' since they will not be used
// using space as a delimiter is enough
String str2 = str.replaceAll("\\)", "");
System.out.println("Your string after removing ')' character:");
System.out.println("str2=\"" + str2 + "\"");
System.out.println();
// Since your input has spaces, we split on spaces
String[] strings = str2.split("\\s+");
System.out.println("Result after splitting str2 by spaces:");
for (String s : strings) {
System.out.println(s);
}
System.out.println();
// Lets make two array
String[] num = new String[500];
String[] mark= new String[500];
// loop strings
int cnt = 0;
for (String s : strings) {
String[] a = s.split("\\("); // a[0]="012", a[1]="207.5"
num[cnt] = a[0];
mark[cnt] = a[1];
cnt++;
}
System.out.println("Result num: ");
System.out.print("num[500] = ");
for(String s : num) {
if(s==null) {break;}
System.out.print(s + ",");
}
System.out.println(" etc.\n");
System.out.println("Result mark: ");
System.out.print("mark[500] = ");
for(String s : mark) {
if(s==null) {break;}
System.out.print(s + ",");
}
System.out.println(" etc.\n");
}
}
Output:
Your string:
str="12132002(177) 012(207.5) 014(184)"
Your string after removing ')' character:
str2="12132002(177 012(207.5 014(184"
Result after splitting str2 by spaces:
12132002(177
012(207.5
014(184
Result num:
num[500] = 12132002,012,014, etc.
Result mark:
mark[500] = 177,207.5,184, etc.
Given question is:
A string can contain only a, b or c. There cannot be 2 consecutive same character. First and last character cannot be same. Now given a string with ‘a’, ‘b’, ‘c’ or ‘?’. We need to find the string replacing ‘?’ that satisfy the above conditions. For multiple answer display lexicographically smallest string. For no answer possible display “Not Possible”.
import java.util.*;
class Replace {
public static void main(String args[]) {
char[] arr = { 'a', 'b', 'c' };
char Pre, Suc;
Scanner in = new Scanner(System.in);
String str = new String();
String str2 = new String();
System.out.println("Enter the String");
while (in.hasNextLine()) {
str = in.nextLine();
}
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '?') {
Pre = str.charAt(i - 1);
Suc = str.charAt(i + 1);
for (int j = 0; j < 3; i++) {
while (arr[j] != Pre && arr[j] != Suc) {
str2 = str.substring(0, i) + arr[j]
+ str.substring(i + 1, (str.length() - 1));
}
}
}
}
System.out.println(str2);
}
}
The code is compiling without any errors. I still have to add a couple of things to the code as per question but I was trying to check if the code was correct so far but I am not getting any Output. Any tips/suggestions to improve the code is welcome.
The code Pre = str.charAt(i-1); and Suc = str.charAt(i+1); is problematic when "?" is the first/ last letter. It will cause then a java.lang.StringIndexOutOfBoundsException
At present you are not leaving the while-loop used for reading the input, hence System.out.println(str2); is never reached.
The problem is the program gets stuck in your while(in.hasNextLine()) { str = in.nextLine(); } loop. There is no exit condition. hasNextLine will block until a new line is entered. As per the Javadoc:
This method may block while waiting for input.
You need a condition to break the first while loop. When the user insert the input string he press enter, so the Scanner get the second input as an empty string. You could check the empty string and exit from the while loop.
import java.util.*;
class Replace
{
public static void main(String[] args)
{
char[] arr = {'a','b','c'};
char Pre,Suc;
Scanner in = new Scanner(System.in);
String str = new String();
String str2 = new String();
System.out.println("Enter the String");
while(in.hasNextLine())
{
if(str.isEmpty()) break;
str = in.nextLine();
}
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='?')
{
Pre = str.charAt(i-1);
Suc = str.charAt(i+1);
for(int j=0;j<3;i++)
{
while(arr[j]!=Pre && arr[j]!=Suc)
{
str2 = str.substring(0,i)+arr[j]+str.substring(i+1,(str.length()-1));
}
}
}
}
System.out.println(str2);
}
}
Im have to write a method to check if a word is a palindrome. There is probably a easier way then I have it but this is just based off what I have learned so far. My method works except if there is a capital letters compared to a lowercase.
Edit: wasn't very clear. My method returns that a capital and lower case letter are the same. But I would like it to say they are different
public static void printPalindrome(Scanner kb) {
System.out.print("Type one or more words: ");
String s = kb.nextLine();
int count = 0;
for(int i = 0; i < s.length();i++) {
char a = s.charAt(i);
char b = s.charAt(s.length()-(i+1));
if (a==b) {
count ++;
} else {
count = count;
}
}
if (count == s.length()) {
System.out.print(s + " is a palindrome!");
} else {
System.out.print(s + " is not a palindrome.");
}
}
I'd recommend a slightly different approach, I'd reverse the string using StringBuilder#reverse and then compare the two strings using String#equalsIgnoreCase
String s = kb.nextLine();
StringBuilder sb = new StringBuilder(s).reverse();
if (s.equalsIgnoreCase(sb.toString())) {
...
} else {
...
}
You can solve your problem by converting the input String to upper case :
String s = kb.nextLine().toUpperCase();
Or if you wish to preserve the case of the original String, create a new String and test if it's a palindrome.
String s = kb.nextLine();
String u = s.toUpperCase();
int count = 0;
for(int i = 0; i < u.length();i++) {
char a = u.charAt(i);
char b = u.charAt(u.length()-(i+1));
if (a==b) {
count ++;
} else {
count = count;
}
}
i think you can do it with its ascii values
look this picture
then you shoul convert your char to ascii
char character = 'a';
int ascii = (int) character;
then compare the integers