I am trying to take user input and modify it so that I print the string without any vowels. I have been able to do this successfully with the following code.
Scanner in = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = in.next();
String newString = word.replaceAll("[aeiouAEIOU]","1");
System.out.printf("%s", newString);
However, I am trying to get the same effect by using a loop without the above method, replaceAll(). I have tried one other time, but got mixed up in the logic and restarted. My latest attempt is below and I cannot understand why it will not run properly. I will enter a string and without any error message it will not print back anything. The only time I get it to work is when I give it single characters to find in the string using something like
if(letter.contains("a"))
If the condition is found true it will print back a string of a's, however, this does not work for any combination of characters, only single ones. My complete code is below.
import java.util.Scanner;
public class practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = in.next();
int i = 0;
while (i < word.length()){
String letter = word.substring(i, (i+1));
if(letter.contains("[bcdfghjklmnpqrstvwxyz]")){
System.out.printf("%s",letter);
}
i++;
}
}
}
I am simply trying to find a way to complete this program only using conditionals, loops, UI, and only the methods length(), contains() or indexOf(), charAt(), and substring(x,y). Thanks in advance for any help I hope I have provided enough information.
Here is some sample output:
Enter a word:
Jordan
After I entered the word the program stops.
One way would be to convert your string to an array of characters toCharArray() and then compared with a case and add a new chain StringBuilder
String word = in.next();
StringBuilder bul = new StringBuilder();
for (char arg : word.toLowerCase().toCharArray()) {
switch(arg)
{
case 'a': System.out.println("A");break;
case 'e': System.out.println("E");break;
case 'i': System.out.println("I");break;
case 'o': System.out.println("O");break;
case 'u': System.out.println("U");break;
default:
bul.append(arg);
}
}
System.out.println(bul); //String not Vowels
in your code might change why a selected character with subtring can never contain such a long string like that "[bcdfghjklmnpqrstvwxyz]"
if(letter.contains("[bcdfghjklmnpqrstvwxyz]")){...}
for
if("[bcdfghjklmnpqrstvwxyz]".contains(letter.toLowerCase())){...}
You can use Scanner.useDelimeter(Pattern pattern) with regex. The regexfor removing vowel is - [^aeiou]+
If you want to ignore case then use this pattern - (?i)[^aeiou]+ .
And finally try the following code snippet -
scanner.useDelimeter(Pattern.compile("[^aeiou]+"));
When you say,
if(letter.contains("bcdfghjklmnpqrstvwxyz"))
your code will check if letter has the exact sequence of letters bcdfghjklmnpqrstvwxyz
In other words, it won't not check if any of these letters individually exists in the String.
Instead, you could go like this:
for (int i = 0; i < word.length(); i++) {
String currentLetter = String.valueOf(word.charAt(i));
if (!currentLetter.matches("a|e|i|o|u"))
System.out.print(currentLetter);
}
other way of doing is
Scanner s = new Scanner(System.in);
System.out.print("Enter input String");
String input = s.next();
StringBuilder sb = new StringBuilder("");
for(char c : input.toLowerCase().toCharArray())
if( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ){}
else sb.append(c+"");'
System.out.println("Given input without vowels : "+sb);
Related
Here is my program.
// Here we use a BufferredReader to read characters from console.
package fileIO;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BRRead {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char ch;
System.out.println("Enter characters, 'q' to quit.");
do {
ch = (char)br.read();
System.out.println(ch);
} while(ch!='q');
}
}
Input 1: testq
Output:
t
e
s
t
q
Input 2: test
Output:
t
e
s
t
""
""
""
""
where "" means empty line.
My question is why 4 empty lines are printed for the case when the input characters doesn't contain letter 'q' but aren't printed when the input characters contain letter 'q'?
Complete-er answer at the bottom
Haven't run it at all to check, though it seems like it could have something to do with the use of a do-while loop instead of a while loop
This format will make sure that the character 'q' is not read before it attempts to output anything
while(ch!='q')
{
System.out.println(ch);
ch = (char)br.read();
}
And this format prints the read character before testing if it is valid
do {
ch = (char)br.read();
System.out.println(ch);
} while(ch!='q');
EDIT after some trial/error
With this version, I have used the Scanner class which is quite similar, and I am more familiar with it. It may go something like so:
Create Object(s) for reading the data BufferedReader,Scanner,etc.
Check if there is content present
Accept the data as a String and read the first character
Output if the String is is not q
Cycle the test-> read -> print -> loop, till q is entered
Scanner input = new Scanner(System.in);
System.out.println("Enter characters, 'q' to quit.");
String read = input.nextLine();
while(read.length() <= 1 && read.charAt(0) != 'q')
{
System.out.print(read);
read = input.nextLine();
}
The (almost) original method*
Eureaka!
name.read() Reads a single character --
However, this returns an int datatype which cannot be converted with the (char) mask.
name.readLine() Reads a line of text -- With this, you can simply take the character at index 0
https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html
do {
full = br.readLine();
System.out.print(full);
} while(full.length() <= 1) && full.charAt(0) != 'q');
Not sure what the best way to do it would be between a do-while and a while loop, and that may ultimately come down to use case and opinion. and you may want to make a boolean method too
// true if String matches 'q' or "quit"
public static boolean isQuit(input)
{
String lowercase = input.toLower();
char start = input.charAt(0);
return (lowercase.equals("quit")
|| (input.length() <= 1 && start == 'q'));
}
I am writing a hangman program and one of the requirements to a hangman game is preventing the user from entering the same letter twice.
I have written the code for that, but the problem is every time I enter a letter it says it is already entered. I need to only say it when it is entered the second time. You guys have any suggestions? I've been trying to fix this for the past few hours, I figured I could ask on here to find some help. I already looked at another Stackoverflow question regarding something similar to this but all those solutions have the same result.
In Java, how can I determine if a char array contains a particular character?
I've tried something like this but it won't work either:
boolean contains = false;
for (char c : store) {
if (c == character) {
System.out.println("Already Entered");
contains = true;
break;
}
}
if (contains) {
// loop to top
continue;
}
SECOND CLASS-
public void hangman(String word, int life) {
KeyboardReader reader = new KeyboardReader();
char[] letter = new char[word.length()];
char[] store = new char[word.length()];
String guess;
int i = 0, tries = 0, incorrect = 0, count = 1, v = 0;
while (i < word.length()) {
letter[i] = '-';
I would just use the String.contains() method:
String aString = "abc";
char aChar = 'a';
return aString.contains(aChar + "");
To keep track of guessed letters you can use a StringBuffer, appending them using a StringBuffer.append() to append new letters (maintaining state) and use the StringBuffer.toString() method to get the String representation when you need to do the comparison above.
Since Java 1.5 the class String contains the method contains(). My idea is to collect all entered letters into a string variable and using above method:
// My code line
String letterAlreadyEntered = "";
// Your code line
char character = reader.readLine().charAt(0);
// My code line
if (letterAlreadyEntered.contains("" + character) == true) {
//Put code here what ever you want to do with existing letter
} else {
letterAlreadyEntered += character;
}
In my opinion, this is an easier way to check for occurrences than in arrays, where you have to write your own check method.
I am trying to get my code to prevent a user input from having a number in it.
Essentially I want the code to do as follows:
ask for input
receive input
test whether or not the input contains a number(ex: 5matt vs matt)
if contains a number I want to System.out.println("Error: please do not input a number");
Heres the kicker (and why it's not a duplicate question): I can't use loops or other statements we haven't learned yet. So far the only true statements we've learned are if/else/else if statements. That means I can not use for loops, like some of the answers are suggesting. While they're great answers, and work, I'll lose points for using them.
System.out.println("Please input the first name: ");
String name1 = in.next();
System.out.println("Please input the second name: ");
String name2 = in.next();
System.out.println("Please input the third name: ");
String name3 = in.next();
name1 = name1.substring(0,1).toUpperCase() + name1.substring(1).toLowerCase();
name2 = name2.substring(0,1).toUpperCase() + name2.substring(1).toLowerCase();
name3 = name3.substring(0,1).toUpperCase() + name3.substring(1).toLowerCase();
I have this already but I can't figure out how to test if the input only contains letters.
Okay, there are many ways to deal with this. A good thing would be to use Regex (text matching stuff). But it seems that you should only use very basic comparison methods.
So, let's do something very basic and easy to understand: We iterate over every character of the input and check whether it's a digit or not.
String input = ...
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
System.out.println("Do not use digits!");
}
}
This code is very straightforward. But it will continue checking even if a digit was found. You can prevent this using a helper-method and then returning from it:
public boolean containsDigit(String text) {
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
return true;
}
}
// Iterated through the text, no digit found
return false;
}
And in your main program you call it this way:
String input = ...
if (containsDigit(input)) {
System.out.println("Do not use digits!");
}
Use a regular expression to filter the input
Eg
str.matches(".*\\d.*")
See this link for more info
There are several ways you could do this, among others:
Iterate over all the chars in the string and check whether any of them is a digit.
Check whether the string contains the number 1, number 2, number 3, etc.
Use a regular expression to check if the string contains a digit.
(Java Regular Expressions)
If you're allowed to define functions, you can essentially use recursion to act as a loop. Probably not what your prof is going for, but you could be just inside the requirements depending on how they're worded.
public static boolean stringHasDigit(String s) {
if (s == null) return false; //null contains no chars
else return stringHasDigit(s, 0);
}
private static boolean stringHasDigit(String s, int index) {
if (index >= s.length()) return false; //reached end of string without finding digit
else if (Character.isDigit(s.charAt(index))) return true; //Found digit
else return stringHasDigit(s, index+1);
}
Only uses if/elseif/else, Character.isDigit, and String.charAt, but recursion might be off limits as well.
so if the user enters "ABCD" how would i change a single char within this string?
example: user enters "ABCD". I want it to output 'T','B','G','D'. so that changed the A to T and C to G.
I tried using a the replace method but found that tedious (and didnt really work).
I want to try use a loop, checking each letter the user has entered and changing it to a different letter. Changing A to T, T to A and C to G, G to C.
public class test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
userInput = input.nextLine();
char arrayInput[] = toCharArray();
for(int i = 0; i > arrayInput.length; i++) {
switch(arrayInput[i]){
case 'a'
case 'A': change to 'T';
break;
case 't'
case 'T': change to 'A'
etc..
}}}}
something like that ^^. that could be totally wrong. but really need help! couldnt find any other help on the internet. thanks in advance
Append the output to a StringBuilder
StringBuilder ouput=new StringBuilder();
for(int i = 0; i > arrayInput.length; i++) {
switch(arrayInput[i]){
case 'a':
case 'A':
output.append('T');
break;
// so on.
}
}
Strings are immutable so you have save the output of replace in another string
String old ="ABCD";
String newString = old.replace('A', 'T').replace('C', 'G');
System.out.println(newString);
You can use the for loop to traverse through the String like this-
String s="ABCD";
for(int i=0;i<s.length;i++)
{
if(s.charAt(i)=="A")
s.charAt(i)="T";
if(s.charAt(i)=="C")
s.charAt(i)="G";
}
Use the charAt() to detect characters and replace them
WOW! LOOKING BACK ON MY EARLY DAYS OF JAVA! Such an easy question now haha.
I am working on a class assignment this morning and I want to try and solve a problem I have noticed in all of my team mates programs so far; the fact that spaces in an int/float/double cause Java to freak out.
To solve this issue I had a very crazy idea but it does work under certain circumstances. However the problem is that is does not always work and I cannot figure out why. Here is my "main" method:
import java.util.Scanner; //needed for scanner class
public class Test2
{
public static void main(String[] args)
{
BugChecking bc = new BugChecking();
String i;
double i2 = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (i2 <= 0.0)
{
i = in.nextLine();
i = bc.deleteSpaces(i);
//cast back to float
i2 = Double.parseDouble(i);
if (i2 <= 0.0)
{
System.out.println("Please enter a number greater than 0.");
}
}
in.close();
System.out.println(i2);
}
}
So here is the class, note that I am working with floats but I made it so that it can be used for any type so long as it can be cast to a string:
public class BugChecking
{
BugChecking()
{
}
public String deleteSpaces(String s)
{
//convert string into a char array
char[] cArray = s.toCharArray();
//now use for loop to find and remove spaces
for (i3 = 0; i3 < cArray.length; i3++)
{
if ((Character.isWhitespace(cArray[i3])) && (i3 != cArray.length)) //If current element contains a space remove it via overwrite
{
for (i4 = i3; i4 < cArray.length-1;i4++)
{
//move array elements over by one element
storage1 = cArray[i4+1];
cArray[i4] = storage1;
}
}
}
s = new String(cArray);
return s;
}
int i3; //for iteration
int i4; //for iteration
char storage1; //for storage
}
Now, the goal is to remove spaces from the array in order to fix the problem stated at the beginning of the post and from what I can tell this code should achieve that and it does, but only when the first character of an input is the space.
For example, if I input " 2.0332" the output is "2.0332".
However if I input "2.03 445 " the output is "2.03" and the rest gets lost somewhere.
This second example is what I am trying to figure out how to fix.
EDIT:
David's suggestion below was able to fix the problem. Bypassed sending an int. Send it directly as a string then convert (I always heard this described as casting) to desired variable type. Corrected code put in place above in the Main method.
A little side note, if you plan on using this even though replace is much easier, be sure to add an && check to the if statement in deleteSpaces to make sure that the if statement only executes if you are not on the final array element of cArray. If you pass the last element value via i3 to the next for loop which sets i4 to the value of i3 it will trigger an OutOfBounds error I think since it will only check up to the last element - 1.
If you'd like to get rid of all white spaces inbetween a String use replaceAll(String regex,String replacement) or replace(char oldChar, char newChar):
String sBefore = "2.03 445 ";
String sAfter = sBefore.replaceAll("\\s+", "");//replace white space and tabs
//String sAfter = sBefore.replace(' ', '');//replace white space only
double i = 0;
try {
i = Double.parseDouble(sAfter);//parse to integer
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println(i);//2.03445
UPDATE:
Looking at your code snippet the problem might be that you read it directly as a float/int/double (thus entering a whitespace stops the nextFloat()) rather read the input as a String using nextLine(), delete the white spaces then attempt to convert it to the appropriate format.
This seems to work fine for me:
public static void main(String[] args) {
//bugChecking bc = new bugChecking();
float i = 0.0f;
String tmp = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (true) {
tmp = in.nextLine();//read line
tmp = tmp.replaceAll("\\s+", "");//get rid of spaces
if (tmp.isEmpty()) {//wrong input
System.err.println("Please enter a number greater than 0.");
} else {//correct input
try{//attempt to convert sring to float
i = new Float(tmp);
}catch(NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
System.out.println(i);
break;//got correct input halt loop
}
}
in.close();
}
EDIT:
as a side note please start all class names with a capital letter i.e bugChecking class should be BugChecking the same applies for test2 class it should be Test2
String objects have methods on them that allow you to do this kind of thing. The one you want in particular is String.replace. This pretty much does what you're trying to do for you.
String input = " 2.03 445 ";
input = input.replace(" ", ""); // "2.03445"
You could also use regular expressions to replace more than just spaces. For example, to get rid of everything that isn't a digit or a period:
String input = "123,232 . 03 445 ";
input = input.replaceAll("[^\\d.]", ""); // "123232.03445"
This will replace any non-digit, non-period character so that you're left with only those characters in the input. See the javadocs for Pattern to learn a bit about regular expressions, or search for one of the many tutorials available online.
Edit: One other remark, String.trim will remove all whitespace from the beginning and end of your string to turn " 2.0332" into "2.0332":
String input = " 2.0332 ";
input = input.trim(); // "2.0332"
Edit 2: With your update, I see the problem now. Scanner.nextFloat is what's breaking on the space. If you change your code to use Scanner.nextLine like so:
while (i <= 0) {
String input = in.nextLine();
input = input.replaceAll("[^\\d.]", "");
float i = Float.parseFloat(input);
if (i <= 0.0f) {
System.out.println("Please enter a number greater than 0.");
}
System.out.println(i);
}
That code will properly accept you entering things like "123,232 . 03 445". Use any of the solutions in place of my replaceAll and it will work.
Scanner.nextFloat will split your input automatically based on whitespace. Scanner can take a delimiter when you construct it (for example, new Scanner(System.in, ",./ ") will delimit on ,, ., /, and )" The default constructor, new Scanner(System.in), automatically delimits based on whitespace.
I guess you're using the first argument from you main method. If you main method looks somehow like this:
public static void main(String[] args){
System.out.println(deleteSpaces(args[0]);
}
Your problem is, that spaces separate the arguments that get handed to your main method. So running you class like this:
java MyNumberConverter 22.2 33
The first argument arg[0] is "22.2" and the second arg[1] "33"
But like other have suggested, String.replace is a better way of doing this anyway.