Replacing a character in a scanner string - java

So for an assignment I'm supposed to create a program that doubles every letter and triples every exclamation mark of a phrase that is inputted into a scanner. Here is what I got so far:
import java.util.Scanner;
public class DoubleLetters{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a statement");
String x = scan.nextLine();
String y = x.replace("! ","!!! ");
for(int j=0; j< x.length(); j++){
System.out.print(y.charAt(j));
System.out.print(y.charAt(j));
}
}
}
Doubling the letters work, but not tripling the exclamation marks. I tried to use the replace method and it did not work. Please, any help is appreciated.

Just add if statement inside a loop
if(y.charAt(j) == '!') {
System.out.print(y.charAt(j));
}
and remove empty spaces in replace method
String y = x.replace("!","!!!");

try this
String y = x.replace("!","!!!");
or this
for (char c : x.toCharArray()) {
System.out.print(c);
System.out.print(c);
if (c == '!') {
System.out.print(c);
}
}

Convert String into char array than do double and triplet and display . Start reading from left hand side and move to right hand side using double and triplet condition update char array and finally display result(char array) .

You could go over all the characters and append them to a StringBuilder:
String str = /* recieved from scanner */
StringBuidler builder = new StringBuilder();
for (char c : str.toCharArray()) {
// Any character needs to be included at least once:
builder.append(c);
// If it's a letter, you need another copy (total of 2)
if (Character.isLetter(c)) {
builder.append(c);
// If it's an excalmation mark, you need another two copies (total of 3)
} else if (c == '!') {
builder.append(c);
builder.append(c);
}
}
System.out.println(builder);
System.out.print(y.charAt(j));
System.out.print(y.charAt(j));
}

Try the follwing code, it will work efficiently as you like,
import java.util.Scanner;
public class DoubleLetters
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a statement");
String x = scan.nextLine();
for(int j=0; j< x.length(); j++)
{
if(y.charAt(j)=='!')
System.out.println("!!!");
else
{
System.out.print(y.charAt(j));
System.out.print(y.charAt(j));
}
}
}
}

As u havn't succeeded to replace '!' . so for a another approach instead of replace you can tokenize your string using StringTokenizer as this piece of code. and by this u can add what u want as for your case at the end of each ! u can add 2 more !!. code as.
System.out.println("---- Split by comma '!' ------");
String s = "My Name !is !Manmohan"; //scanner string
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(s, "!");
String now = "";
while (st2.hasMoreElements()) {
now += st2.nextElement() + "!!!";
}
System.out.println(now.substring(0, now.length() - 3));
//op ... My Name !!!is !!!Manmohan

Related

Printing userinput with charAt()?

I am a beginner in java and am having trouble with printing out userinput with charAt(). I need to create a program that takes userinput and adds "op" before vowels in that text. (example: Userinput -> "Beautiful" would be translated as "Bopeautopifopul") I am struggling to figure how to write this. So far I have come up with this small bit.
import java.util.Scanner;
public class oplang {
static Scanner userinput = new Scanner(System.in);
public static void main(String[] args) {
char c ='a';
int n,l;
System.out.println("This is an Openglopish translator! Enter a word here to translate ->");
String message = userinput.nextLine();
System.out.println("Translation is:");
l = message.length();
for (n=0; n<l; n++);
{
c = message.charAt();
if (c != ' ');
{
System.out.println(" ");
}
c++;
}
}}
I would use a regular expression, group any vowels - replace it with op followed by the grouping (use (?i) first if it should be case insensitive). Like,
System.out.println("Translation is:");
System.out.println(message.replaceAll("(?i)([aeiou])", "op$1"));
If you can't use a regular expression, then I would prefer a for-each loop and something like
System.out.println("Translation is:");
for (char ch : message.toCharArray()) {
if ("aeiou".indexOf(Character.toLowerCase(ch)) > -1) {
System.out.print("op");
}
System.out.print(ch);
}
System.out.println();
And, if you absolutely must use charAt, that can be written like
System.out.println("Translation is:");
for (int i = 0; i < message.length(); i++) {
char ch = message.charAt(i);
if ("aeiou".indexOf(Character.toLowerCase(ch)) > -1) {
System.out.print("op");
}
System.out.print(ch);
}
System.out.println();

java doubling characters/tripling characters

I am trying to write a Java program that will print letters twice; all other characters, such as spaces, numbers, and punctuation marks, are to be left alone, except for "!" which should be tripled. My program only doubles all characters so I'm not too sure what to do now as I am very new to Java.
This is what I have so far:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a line of text.");
String myStr = scan.nextLine();
if (myStr.length()>0){
String answer = "";
for(int j=0; j<myStr.length(); j++){
char ch = myStr.charAt(j);
answer = answer + ch + ch;
}
System.out.println(answer);
}
else {
System.out.println("Please enter a string longer than 0 characters");
}
}
How about something like this, using each line as IntStream, since char values are just integers;
String myStr = scan.nextLine().chars()
.flatMap(ch -> {
if (ch == '!') {
return IntStream.of(ch, ch, ch);
} else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
return IntStream.of(ch, ch);
}
return IntStream.of(ch);
})
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
It works great, and so much fun to work with Java streams
You can do this:
String str = "abc!123";
for(int x=0; x<str.length(); x++)
if(str.substring(x, x+1).matches("[a-zA-Z+]")) //if is alphabet
System.out.print(str.substring(x, x+1) + str.substring(x, x+1));
else if (str.substring(x, x+1).equals("!"))
System.out.print("!!!");
else
System.out.print(str.substring(x, x+1));
A rather straight forward approach which works accordingly to what you currently is doing. check whether a character is alphabet, print twice. If it is !, print 3 times. Else print the respective character once.
Input:
abc!123
Output:
aabbcc!!!123
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String str = input.nextLine();
doubleStr(str);
}
public static void doubleStr(String s)
{
char[] array = s.toCharArray();
for(char a: array)
{
if(a>='0' && a<='9')
{
System.out.print(a);
}else if(a=='!')
{
for(int i=0; i<=2; i++)
{
System.out.print(a);
}
}
else
{
for(int i=0; i<=1; i++)
{
System.out.print(a);
}
}
}
}
Result
Original: abc ! 9
aabbcc !!! 9
A simple for loop of the characters will do it. Assuming you might want the result for other than simple printing, a transformation method returning the result would be better. That will also allow unit testing, if needed.
private static String transform(CharSequence input) {
StringBuilder buf = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
buf.append(ch);
if (ch == '!')
buf.append(ch).append(ch);
else if (Character.isLetter(ch))
buf.append(ch);
}
return buf.toString();
}
Test
System.out.println(transform("abc234&#!ff"));
System.out.println(transform("He said: \"You can't do that!\""));
Output from Ideone
aabbcc234&#!!!ffff
HHee ssaaiidd: "YYoouu ccaann'tt ddoo tthhaatt!!!"
Very Simply you can do it like this: Use regex, no need to any kind of loop.
Just Edit this line:
String answer = myStr.replaceAll("(\\p{Alpha}|(!))", "$1$1$2");
Usage:
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a line of text.");
String myStr = scan.nextLine();
if (myStr.length()>0){
String answer = myStr.replaceAll("(\\p{Alpha}|(!))", "$1$1$2");
System.out.println(answer);
}
else {
System.out.println("Please enter a string longer than 0 characters");
}
}
And the result: It is just what you want.
Input: abc234&#!ff
Output: aabbcc234&#!!!ffff

Simple space trimming program

I have this java code to trim all spaces in a String for me.
import java.util.Scanner;
import java.util.Arrays;
public class trimSpace {
public static void main( String[] args ) {
Scanner input = new Scanner(System.in);
String str;
System.out.print("Please enter a string:");
str = input.nextLine();
System.out.println("The result is : ");
char[] charArray = new char[A.length()];
for(int i=0;i<A.length();i++){
if (A.charAt(i) != ' ') { //This line should ignore the space in the str
charArray[i] = A.charAt(i);
System.out.print(charArray[i]);
}
}
//Expected output [j,a,v,a,,,]
System.out.println(Arrays.toString(charArray)); //Output [j," ",A," ",V," ",A]
}
}
If I insert "J A V A" into str, the charArray still include the spaces after printing i.e. [j," ",A," ",V," ",A] What am I doing wrong here?
You put the "correct characters" into the same index where you found them. That way you skip the spaces and leave them.
charArray[i] = A.charAt(i);
System.out.print(charArray[i]);
You need to add a counter in charArray:
charArray[counter++] = A.charAt(i);
That way you'll only advance in charArray if the input was not a space. Or more complete:
int counter = 0;
for(int i=0;i<A.length();i++){
if (A.charAt(i) != ' ') { //This line should ignore the space in the str
charArray[counter++] = A.charAt(i);
}
You can try this:
String str = "J A V A";
str = str.replaceAll("\\s+", "");

How do I take an input and make the program print out each letter on a new line while making every space encounter to print out "<space>"?

import java.util.Scanner;
public class TwoDotSevenNumbaTwo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String input;
int num1, num2, leng;
char word;
Scanner inputscan = new Scanner(System.in);
System.out.println("Give me some love baby");
input = inputscan.nextLine();
leng = input.length();
num1 = 0;
num2 = 1;
while (num1 < leng) {
input = input.replaceAll(" ", "<space>");
System.out.println(input.charAt(num1));
num1++;
}
}
}
I can't seem to figure out how to get the <space> on a single line. I know I can't do it because it is a char but I can't find a way around it.
You could do
for(int i = 0; i < leng; ++i) {
char x = input.charAt(i);
System.out.println(x == ' ' ? "<space>" : x);
}
Once you've stored the input as a String, you can write:
// Break the string into individual chars
for (char c: input.toCharArray()) {
if (c == ' ') { // If the char is a space...
System.out.println("<space>");
}
else { // Otherwise...
System.out.println(c);
}
}
Regex powa:
yourText.replaceAll(".", "$0\n").replaceAll(" ","<space>");
Explanation:
First replaceAll takes every charachter (. = any character) and replaces it with the same character ($0 = matched text) followed by a newline \n, thusly every character is on separate line.
Second replaceAll just replaces every acctual space with the word "<space>"
For java regex tutorial, you can follow this link or use your favourite search engine to find plenty more.

During while loops, interpret next character?

public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please insert a word.: ");
String word = (" ");
while (in.hasNextLine()){
System.out.println(in.next().charAt(0));
}
}
}
I am attempting to read each letter from the input and seperate it with a space.
For example: Input is Yes.
The output should be
Y
E
S
.
I do not understand how to make the char go to the next letter in the input. Can anyone help?
You've got a bug in 'hasNextLine' your loop -- an extraneous ; semicolon before the loop body. The semicolon (do nothing) will be looped, then the body will be executed once.
Once you fix that, you need to loop over the characters in the word. Inside the 'hasNextLine' loop:
String word = in.nextLine();
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
// print the character here.. followed by a newline.
}
You could do
while (in.hasNext()) {
String word = in.next();
for (char c: word.toCharArray()) {
System.out.println(c);
}
}

Categories

Resources