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.
Related
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;
}
}
I have the following code that takes 2 strings as inputs and returns Boolean on whether they're anagrams:
import java.util.ArrayList;
import java.util.Scanner;
public class AnagramChecker {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print ("Enter string 1: ");
String str1 = sc.nextLine();
System.out.print ("Enter string 2: ");
String str2 = sc.nextLine();
boolean check = isAnagram (str1, str2);
System.out.println ("Anagram check for '" + str1 + "' and '" + str2 + "': " + check);
sc.close();
}
public static boolean isAnagram (String s1, String s2) {
if(s1.length() != s2.length())
return false;
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
ArrayList<String> myList = new ArrayList<String>();
for(int i = 0; i < s2.length() ; i++ ){
myList.add(String.valueOf(s2.charAt(i)));
}
for(int i = 0; i < s1.length();i++){
for(int j = 0; j < myList.size(); j++){
if(myList.get(j).equals(String.valueOf(s1.charAt(i)))){
myList.remove(j);
j = 0;
break;
}
}
}
return myList.isEmpty();
}
}
It is somewhat limited though, I'm trying to expand it to work for the following cases:
- different cases i.e. eager == AGREE
- single word with whitespaces i.e. eager == a g ree
- different amounts of whitespace i.e. " eager" == agree
Is there a nice and clean way to integrate this into already written code above without much pain and re-writing. Any help much appreciated. Thanks.
Yes there is. Regex to the rescue! You can use the String built in .replaceAll(). Passing it the \s value will remove all spaces and characters not printed such as \n. I would suggest that during comparison you use something like the following:
string1.replaceAll("\\s","").equals(string2.replaceAll("\\s",""));
personally I would do the following
use trim() to remove leading and traiing whitespace
use replace to remove whitespaces
use toLowerCase() to make the text lower case
convert the Strings into an array list of characters
sort the arrays
compare the arrays - if they are the same then you have an anagram
So I have this program I need to write. I'm, supposed to get an input string from a user and then print out how many capital letters and how many lowercased letters are in the string. I've looked everywhere in the book that I have and I just can't seem to find anything about how to print out the uppercase and lowercase letters. I've been doing a lot of googling as well and I couldn't find anything useful.
Anyway here's my code:
import java.util.Scanner; //calls out the method to get input from user
public class Verk1 {
public static void main(String args[])
{
Scanner innslattur = new Scanner(System.in); //input gotten from user
System.out.println("Sláðu inn textabrot í há- og lágstöfum.");
System.out.println("Forritið mun þá segja þér hve margir stafir eru af hverri gerð.");
System.out.println("Textabrot: ");
//The printouts before tell the user to enter in a string, the program will then print out //how many upper- and lowercase letters there are.
String strengur = innslattur.nextLine();
String hastafir = "";
for (int i=0; i<hastafir.length();i++);
{
System.out.println("Í textabrotinu eru " + hastafir + " hástafir");
}
}
}
I know the code is faulty/doesn't work, but do any of you know how I get the number of uppercase- lowercase letters to print them out?
Thanks in advance!
Cheers
I haven't tested it but I would look to do something like this.
String text = "This IS My TEXT StrinG";
int upperCaseCounter = 0;
int lowerCaseCounter = 0;
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
upperCaseCounter++;
}
else if(Character.isLowerCase(text.charAt(i)))
{
lowerCaseCounter++;
}
}
System.out.println("Total Uppercase Characters: " + upperCaseCounter);
System.out.println("Total Lowercase Characters: " + lowerCaseCounter);
You can do their fairly easily if you convert the string to a char[] first. You can then use the isUpperCase(char c) for each character in the string. http://www.tutorialspoint.com/java/character_isuppercase.htm
For some strange reason your for loop is referring to an empty string you've just declared, rather than the string you just read in from the user. However, if you change that, inside your loop you can get at the individual characters in the string with strengur.charAt(i) and you can test whether a letter is capital with Character.isUpperCase(ch) and you can check for a lower case letter with Character.isLowerCase(ch).
public void printCapsAndLowercaseCounts(String s) {
int uppercase = 0;
int lowercase = 0;
if (s != null) {
String s1 = s.toUpperCase();
String s2 = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s1.charAt(i) ^ s.charAt(i) == s2.charAt(i)) {
if (s.charAt(i) == s1.charAt(i)) uppercase++;
else lowercase++;
}
}
}
System.out.println(uppercase + " " + lowercase);
}
Seems like this would do the trick, assuming you're not doing it an excessive amount. Just use a temporary string, and get the difference between the two:
int capLetterCount = originalString.length() - originalString.replaceAll("[A-Z]", "").length();
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.
The output is always a String, for example H,E,L,L,O,. How could I limit the commas? I want the commas only between letters, for example H,E,L,L,O.
import java.util.Scanner;
import java.lang.String;
public class forLoop
{
public static void main(String[] args)
{
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.next();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length(); i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
System.out.print(Str2);
}
}
Since this is homework I'll help you out a little without giving the answer:
If you want the output to only be inbetween letters IE: A,B,C instead of A,B,C, which is what I imagine you are asking about. Then you need to look at your for loop and check the boundary conditions.
The easiest way I see is :
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.nextLine();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length()-1; i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
Str2 = Str2 + Str1.charAt(Str1.length()-1);
System.out.println(Str2);
}
The output it will give is :
run:
Enter a string: Hello world
H,e,l,l,o, ,w,o,r,l,d
BUILD SUCCESSFUL (total time: 5 seconds)
Though I will highly recommend learning regular expression as suggested by #Roman. Till then this will do the trick. :)
Try regular expressions:
String input = scanner.next();
String output = input.replaceAll(".", "$0,");
With spaces it would be a bit easier since you don't need to abandon last 'odd' comma:
output = output.substring (0, ouput.length() - 2);
When you've figured out the loop-solution, you could try the following ;)
System.out.println(Arrays.toString("HELLO".toCharArray()).replaceAll("[\\[ \\]]", ""));
Just don't append the comma when the last item of the loop is to be appended. You have the item index by i and the string length by Str2.length(). Just do the primary school math with a lesser-than or a greater-than operator in an if statement.
The following snippet should be instructive. It shows:
How to use StringBuilder for building strings
How to process each char in a String using an explicit index
How to detect if it's the first/last iteration for special processing
String s = "HELLO";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (i == 0) { // first
sb.append("(" + ch + ")");
} else if (i == s.length() - 1) { // last
sb.append("<" + ch + ">");
} else { // everything in between
sb.append(Character.toLowerCase(ch));
}
}
System.out.println(sb.toString());
// prints "(H)ell<O>"