Printing userinput with charAt()? - java

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();

Related

Produce lowercase character instead of uppercase in Java

The output is fine but the output is in Uppercase letter, I want the output to be lowercase character, what should I do?
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
int a[]=new int[26];
Scanner sc = new Scanner (System.in);
String str=sc.nextLine();
for(int i = 0; i<str.length();i++) {
if(str.charAt(i)>=65 && str.charAt(i)<=90) {
a[str.charAt(i)-65]++;
}
else if(str.charAt(i)>=97 && str.charAt(i)<=122) {
a[str.charAt(i)-97]++;
}
}
for(int i=0;i<26;i++) {
if(a[i]>0) {
System.out.print(" "+(char )(i+65)+ "(" + a[i]+")");
}
}
}
}
'A' is 65. 'a' is 97. Use 97 instead of 65 in your final loop.
Alternatively use 'a' directly instead of the number. This makes it more obvious what you're doing in that code.
It may be more straightforward to convert the entire string to lower case to avoid checking for upper case letters.
Also, as suggested earlier using character literals as a instead of 97 would make the code more readable.
Scanner sc = new Scanner(System.in);
int a[] = new int[26];
String str = sc.nextLine().toLowerCase();
for (char c : str.toCharArray()) {
if (c >= 'a' && c <= 'z') {
a[c - 'a']++;
}
}
for (char c = 'a'; c <= 'z'; c++) {
int i = c - 'a';
if (a[i] > 0) {
System.out.print(" "+ c + "(" + a[i] + ")");
}
}
Check out this post with a accepted answer How do I convert strings between uppercase and lowercase in Java?
You could probably do something like this
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
int a[]=new int[26];
Scanner sc = new Scanner (System.in);
String str=sc.nextLine();
String lowerCaseInput = str.toLowerCase();
System.out.print(lowerCaseInput);
}
}

Read in a sentence and print out only words that have the same letter repeated 3 or more times in a row

I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers

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

Replacing a character in a scanner string

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

Finding all uppercase letters of a string in java

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));
}
}
}
}

Categories

Resources