Arrange letters in one line - java

I have written a code that takes a string parameter and returns string that results from changing the capitalization of characters in the following way:
all vowels must be in uppercase(vowels are a,e,i,o,u)
all consonants must be in lowercase
any characters that are not letters must not be changed
Here is my code:
public class Simple {
public char ChangeCase() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an input String: ");
String inputString = scanner.nextLine();
//String isVowel = "aeiou";
char c='\0';
for (int i = 0; i < inputString.length(); i++) {
c = inputString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U') {
c = Character.toLowerCase(c);
System.out.println(c);
}
else if (c=='b'||c=='c'||c=='d'||c=='f'||c=='g'||c=='h'||c=='j'||c=='k'||c=='l'||c=='m'||c=='n'||c=='p'||c=='q'||c=='r'||c=='s'||c=='t'||c=='v'||c=='w'||c=='x'||c=='y'||c=='z'||
c=='B'||c=='C'||c=='D'||c=='F'||c=='G'||c=='H'||c=='J'||c=='K'||c=='L'||c=='M'||c=='N'||c=='P'||c=='Q'||c=='R'||c=='S'||c=='T'||c=='V'||c=='W'||c=='X'||c=='Y'||c=='Z'){
c = inputString.charAt(i);
c =Character.toUpperCase(c);
System.out.println(c);
}
else if(c=='#'||c=='!'||c=='"'||c==' '||c=='!'||c=='"'||c=='#'||c=='$'||c=='%'||c=='&'||c=='('|| c==')'||c=='*'||c=='+'||c==','||c=='-'||c=='.'||c=='/'||c==':'||c==';'||c=='<'||c=='='||c=='>'||c=='?'||c=='['||c==']'||c=='^'||c=='_'||c=='`'||c=='{'||c=='|'||c=='}'||c=='~'||c=='"'){
c=inputString.charAt(i);
c=c;
System.out.println(c);
}
else
c=c;
}
return c;
}
}
Runner class:
public class Runner {
public static void main(String[] args) {
Simple smpl=new Simple();
smpl.ChangeCase();
}
}
Results i get when I type hello:
Enter an input String: hello
H
e
L
L
o
Expected results:
HeLLo
What should I change to get the expected results?

Change println to print since println will always add an extra row.

change println() to print() to omit the linefeed character from the output. Swap toUpperCase and toLowerCase to make the code do what the specification requires.
You are also currently not printing other characters such as linefeed (the requirement "any characters that are not letters must not be changed").
Get rid of the second else if and the else branches and replace them with
else {
System.out.print(c);
}
Also get rid of the extra c = inputString.charAt(i); statements. You only need the first one.
Regarding the problem you are solving, if I were you I would use regular expressions for that.
Anyway, here is a solution for Simple.java without regular expressions with some other improvements applied as well:
import java.util.Scanner;
public class Simple {
public void ChangeCase() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an input String: ");
String inputString = scanner.nextLine();
String vowels = "aeiouAEIOU";
for (char c: inputString.toCharArray()) {
if (vowels.indexOf(c) != -1) { // found vowel
c = Character.toUpperCase(c);
} else if (Character.isLetter(c)) { // must be a consonant
c = Character.toLowerCase(c);
}
System.out.print(c);
}
}
}

As a first starter - simply swap
c = Character.toLowerCase(c);
respectively that other call that does toUpperCase() within your if blocks.
Your code is basically correct - you are just changing cases in the wrong place. So simply "swap" these calls! And of course - don't use println() - as this prints a "line" - meanning it adds a "new line" in the end.

Just use print() method instead of println() because println() always add new line.

First some hints for better code:
Structorize sour code, so please use Methods for each step (IF).
Only variable with 1 letter should be a iteration-variable, but better no variable with only 1 letter. (c)
Here some simple examples for you (can be optimized):
public class Simple {
public void ChangeCase() {
String resultString;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an input String: ");
String inputString = scanner.nextLine();
// make alle chars lower-case
resultString = inputString.toLowerCase();
// make vowels upper-case
resultString = uppercaseVowels(resultString);
// print the result or change to return String for main()
System.out.println("Input: " + inputString);
System.out.println("Result: " + resultString);
}
private String uppercaseVowels(String inputString) {
inputString = inputString.replace('a', 'A');
inputString = inputString.replace('e', 'E');
inputString = inputString.replace('i', 'I');
inputString = inputString.replace('o', 'O');
inputString = inputString.replace('u', 'U');
return inputString;
}
}

Related

find non-existant alphabetic letters in string

This is my code and I need it to return all letters that the user has not entered from the alphabet. For example, if the input is "abcd" the output in result should be the rest of the alphabet. It'd be really nice if someone could help. Right now the output of my code is the whole alphabet no matter what input is given. I tried getting the same letters to be output using "==" instead of "!=" and that worked. So I really don't understand why the opposite won't work.
String s;
System.out.println("input string:");
s = sc.nextLine();
char c;
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Set<String> str = new HashSet<String>();
for(int i=0; i<s.length(); i++) {
c = s.charAt(i);
if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
for(int j=0; j<alphabet.length(); j++){
if(c!=alphabet.charAt(j)) {
str.add(alphabet.charAt(j)+"");
}
}
}
}
System.out.println("result:");
System.out.println(str);
sc.close();
}
The contains method is appropriate in this case:
String s;
System.out.println("input string:");
s = sc.nextLine();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Set<String> str = new HashSet<String>();
for(int j=0; j<alphabet.length(); j++){
if(!s.contains(alphabet.charAt(j)+"")){
str.add(alphabet.charAt(j)+"");
}
}
System.out.println("result:");
System.out.println(str);
sc.close();
}
The best way to do this would be to use regular expressions (I don't know if you are allowed to do this)
Here's how to write it:
String s;
System.out.println("input string:");
s = sc.nextLine();
//then turn those letters into a regex character capture group
s = "[" + s + "]";
//then run the regular expression
String ans = alphabet.replaceAll(s,"");
If you're not allowed to use Regex, please update your question, and I'll delete this answer okay?
Your inner for-if actually says "for each input character c, output whole alphabet except c and union all results", which produces whole alphabet for any input of two distinct characters.
Initialize str set with all characters of alphabet and then remove each character from input. LinkedHashSet is important to preserve order (thanks to ControlAltDel).
static List<String> listByChar(String s) {
return s.chars().mapToObj(i -> String.valueOf((char)i)).collect(toList());
}
public static void main(String[] args) {
...
Set<String> str = new LinkedHashSet<>(listByChar(alphabet));
str.removeAll(listByChar(s));
System.out.println(str);
}
What remains in str is result you want.
s = sc.nextLine().toLowerCase();
It would be better to add this code.

with help of only charAt() and isSpaceChar() make first latter uppercase in java

I want to use only charAt() and toUpperCase() function and capitalize the first letter of each word in a sentence.
Like make the letter capital, that is just after the space.
I tried with this following code.
import java.util.Scanner;
class firstscap
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a sentence");
String s=sc.nextLine();
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(Character.isSpaceChar(c))
{
char ch=s.charAt(++i);
ch=ch.toUpperCase();
}
}
System.out.println(s);
}
}
Several problems here.
s.charAt(n) gives you the n-th character of the String, not a pointer to the n-th character of the String. Changing that character does nothing to the String.
Also Strings are not mutable, which means you have no way to change them.
You can start build a new String from parts of the old String plus the Chars you have made uppercase.
You are capitalizing the characters but not storing them anywhere. I recommend you append all the characters to a StringBuilder*.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine().trim(); // Input & omit leading/trailing whitespaces
StringBuilder sb = new StringBuilder();
// Append the first character, capitalized
if (s.length() >= 1) {
sb.append(Character.toUpperCase(s.charAt(0)));
}
// Start with character at index 1
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isSpaceChar(c)) {
sb.append(c).append(Character.toUpperCase(s.charAt(++i)));
} else {
sb.append(c);
}
}
s = sb.toString();
System.out.println(s);
}
}
A sample run:
Enter a sentence: hello world how are you?
Hello World How Are You?
* You can use String instead of StringBuilder but I recommend you use StringBuilder instead of String for such a case because repeated string concatenation in a loop creates additional as many instances of String as the number of concatenation. Check this discussion to learn more about it.
Strings are immutable, you can't modify them.
Consider building a new String for the result e.g by using StringBuilder.
In the following example, a boolean flag is used to know if the last character was a space .
Also we check if the current character is a letter before putting it to upper case, otherwise it makes no sense.
This will also prevent possible crashes if the line ends with a space (since index charAt(i+1) would crash):
public static void main(final String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a sentence");
String s = sc.nextLine();
boolean wasSpace = false;
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (wasSpace && Character.isLetter(c)) {
resultBuilder.append(Character.toUpperCase(c));
} else {
resultBuilder.append(c);
}
wasSpace = Character.isSpaceChar(c);
}
System.out.println(resultBuilder.toString());
}
Note :
If you also want the first letter of the whole sentence to be capitalized, just initialize wasSpace to true .
import java.util.Scanner;
public class A {
public static void main(String args[]) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the string: ");
String a1 = (obj.nextLine()).trim();
String s1 = "";
char c2;
char arr[] = a1.toCharArray();
for (int i = 0; i <= a1.length() - 1; i++) {
if (Character.isSpaceChar(arr[i]) == true) {
++i;
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + " " + c2;
} else {
if (i == 0) {
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + "" + c2;
} else {
s1 = s1 + arr[i];
}
}
}
System.out.println(s1);
}
}

Changing single chars to upper or lower case depending on user input in Java

I have tried to find guidance on this, but I keep getting solutions on an entire string, or a single character. I am in my 4th week of Java, and have hit a roadblock.
I have to ask a user to input three letters ("Enter three letters: abc"). Depending on which case they type, I have to write a program that swaps upper with lower and visa versa. For example, if the user types "aBc", my output will be "AbC".
This is what I have so far. If my code is horrible, I'm sorry. I'm learning as I go.
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
}
When I typed "abc" for the input, the output was:
A
B
C
A
B
C
A
B
C
The format of the output is supposed to be "Result: ABC". I can work on that later. I'm just trying to figure out how to get this to execute correctly. My hunch is that I'm definitely going wrong on my if/else statements. I do not know how to print the changed chars all in a row (abc, AbC, ABC, etc). I thought I did it correctly at the beginning with the indexing of the string (0,1,2).
By the way, it's not showing my output correctly this forum. It is supposed to be one letter per line, not "ABCABCABC", if I made sense with that.
The reasoning for this is because it's inside of a for loop, which is essentially worthless, because you are never using the integer 'i'. If you remove the for loop, it should only execute once, thus for outputting "ABC", instead of "A B C A B C A B C". To print the chars in a row, you can simply append each character to a string, and then output that.
The biggest issue I see is that you've got a loop going over the length of the string but you're not using the loop index i to reference the individual characters. In short, you're trying too hard and overlooking the obvious.
Wouldn't this do the trick?
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
if (Character.isUpperCase(letter1)) {
System.out.println(Character.toLowerCase(letter1));
} else {
System.out.println(Character.toUpperCase(letter1));
}
}
The reason why you get a redundant printing 'coz you loop the three variables which already contain all characters.
To solve your problem. just remove the for loop. 'coz you already
store each character to the three variables.
You code will look like this now:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
Ok, here is my new code. It compiled with no errors and the output was just as it was supposed to be:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.print("Result: " + Character.toLowerCase(letter1));
else {
System.out.print("Result: " + Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.print(Character.toLowerCase(letter2));
else {
System.out.print(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.print(Character.toLowerCase(letter3));
else {
System.out.print(Character.toUpperCase(letter3));
}
}
}
The problem is that you have a loop then do each letter individually. So get rid of the loop. It would look better if you re-wrote it with a loop but only had one if/else statement inside the loop based on i not 0,1&2.
Replace your for loop with:
System.out.println(letters.toUpperCase());

How do I make a new String based on another string's unknown length?

I am currently in a computer programming class and at a dead end for "creating a template" for this 2-person hang man game.
First, person#1 is prompted for a phrase (contains all lowercase)
Then, I must take whatever phrase they choose and turn it into a template with all ?'s.
Then, as person#2 guesses letters, I must "reveal" the phrase and have the ?'s turn into the phrase letters.
I can't get past turning it into the template though. An example is:
person#1's phrase: "hello world"
desired template outcome: "????? ?????"
This is what I have so far... I'm having trouble at public static String createTemplate(String sPhrase)
import java.util.Scanner;
public class Program9
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
Scanner stdIn = new Scanner (System.in);
int cnt = 0; //counter is set to zero
String sPhrase;
boolean def;
System.out.print("Enter a phrase consisting of only lowercase letters and spaces: ");
sPhrase = scanner.nextLine(); //reads into variable set to Scanner.nextLine()
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String template = createTemplate(sPhrase); //will run through "createTemplate" and show whatever on there.
do
{
char guess = getGuess(stdIn); //will run through "getGuess" and show whatever SOP and return from that. WORKS.
cnt = cnt + 1; //counts the guess
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String updated = updateTemplate(template, sPhrase, guess); //runs throuhgh and prints updated template
} while (!exposedTemplate(sPhrase)); //will loop back if updated template still has ?'s
System.out.println("Good job! It took you " + cnt + " guesses!");
}
public static String createTemplate(String sPhrase)
{
String template = null;
String str;
sPhrase.substring(0, sPhrase.length()+1); //not sure if +1 needed.
sPhrase.equals(template);
//THIS IS WHERE IM HAVING PROBLEMS
}
public static char getGuess(Scanner stdIn)
{
//repeatedly prompts user for char response in range of 'a' to 'z'
String guess;
do
{
System.out.print("Enter a lowercase letter guess : ");
guess = stdIn.next();
} while (Character.isDigit(guess.charAt(0)));
char firstLetter = guess.charAt(0);
return firstLetter;
}
public static String changeCharAt(String str, int ind, char newChar)
{
return str.substring(0, ind) + newChar + str.substring(ind+1);
//freebie: returns copy of str with chars replaced
}
public static String updateTemplate(String template, String sPhrase, char guess)
{
//will have to include changeCharAt
}
public static boolean exposedTemplate(String template)
{
// returns true exactly when there are no more ?'s
}
}
A simple solution would be:
public static String createTemplate(String sPhrase)
{
return sPhrase.replaceAll("[a-zA-Z]", "?");
}
the replaceAll method of the String class in Java replaces all parts of the string that match the supplied regular expression with a string (in this case ?)
Learning regular expressions (known as regexes) may not be in the scope of this assignment, but is a very useful skill for all computer programmers. In this example I've used the regular expression [a-zA-Z] which means replace any upper or lower case character, however you could also use a character class like \\w.
There is an excellent tutorial on Java regexes here: https://docs.oracle.com/javase/tutorial/essential/regex/
You'll need a for-loop, you'll need to check each character of the phrase, String#charAt should help. If the character is not a space, you would append an ? to the template, otherwise you'll need to append a space...
See The for Statement for more details...
StringBuilder sb = new StringBuilder(sPhrase.length());
for (int index = 0; index < sPhrase.length(); index++) {
if (sPhrase.charAt(index) != ' ') {
sb.append("?");
} else {
sb.append(" ");
}
}
sTemplate = sb.toString();
Equally you could use...
StringBuilder sb = new StringBuilder(sPhrase.length());
for (char c : sPhrase.toCharArray()) {
if (c != ' ')) {
sb.append("?");
} else {
sb.append(" ");
}
}
sTemplate = sb.toString();
But I thought the first one would be easier to understand...
Just use a regex and String.replaceAll() method:
public static String createTemplate(String sPhrase)
{
return sPhrase.replaceAll(".", "?");
}
In this example, the first parameter is a regex, so "." matches all characters. The second parameter is the string to replace all regex matches with, a "?".

What's wrong with my Java code? It should count the spaces, but returns 0

The code is copied below. It should return the number of spaces if the character variable l is equal to a space, but always returns a 0.
I've tested it with letters and it worked, for example if I'm asking it to increment when the variable l is equal to e and enter a sentence with e in, it will count it. But for some reason, not spaces.
import java.util.Scanner;
public class countspace {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = input.next();
System.out.println(wc(str));
}
public static int wc(String sentence) {
int c = 0;
for (int i = 0; i < sentence.length(); i++) {
char l = sentence.charAt(i);
if (l == ' ') {
c++;
}
}
return c;
}
}
Scanner.next() (with the default delimited) is only parsing as far as the first space - so str is only the first word of the sentence.
From the docs for Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Use nextLine instead. You can also print the line for debugging:
System.out.println(str);
Use String str = input.nextLine(); instead of String str = input.next();
This is the way you should do to get the next string.
You could have checked that str has the wrong value.

Categories