In my program, I get a user input (String):
ex:
String input = in.nextline();
I want to check (with an if-function) if the user/string has the following:
contains a letter (a-z / A-Z)
only contains one letter (A is valid, AA/AB/LWA is invalid)
so what goes on x/x2?
if(input.equals(x) && input.equals(x2){
//...
}
You can use a simple regex for that:
String input = in.nextline():
if (input.matches("[A-Za-z]{1}")) {
//valid input
}
else {
//invalid input
}
A solution that doesn't involve regular expressions (and, as such, can be easier understood) is simply:
check that the length of the String is 1, using String.length().
check that the first character is between 'a' and 'z' or between 'A' and 'Z', using String.charAt(index) and doing integer comparison on the ASCII value of the characters. This can be also simplified by lowercasing the character and checking that it is between 'a' and 'z' only.
A sample code would be:
private static boolean isValid(String str) {
if (str.length() != 1) return false;
char c = Character.toLowerCase(str.charAt(0));
return c >= 'a' && c <= 'z';
}
And you would use it like
String input = in.nextline();
if (isValid(input)) {
// do something wonderful
}
Using a regex should do the work:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.matches("[A-z]")) {
System.out.println("Valid input");
}
else {
System.out.println("Wrong input");
}
Related
I am new to learning java and I'm doing a project for my online class and currently stuck on part of it.
Write a program that checks the properness of a given variable name. More specifically, your program should specify whether a user-entered variable name is:
illegal (no spaces allowed, must begin with a letter)
legal, but uses poor style (should only use letters or digits)
good
You don’t need to check for an uppercase letter for the first letter in the second word, third word, etc.
So my problem is that since having space in a variable name is illegal, I need to check the user's input for space, and if there is one it needs to print that it is illegal. I also need to check for special symbols (like $%#) and if it is anywhere but the first character, have it print that it is legal but improper.
I feel like this is super simple I just can't figure it out.
import java.util.Scanner;
public class IdentiferCheck
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
String variableName = "";
char ch = ' '; //temp holder
//Get User Input
System.out.println("This program checks the properness of a proposed Java variable name.");
System.out.println("Please enter a variable name (q to quit):");
variableName = in.nextLine();
//Check if variable name is proper
do
{
//Check if first char is lowercase
ch = variableName.charAt(0);
if (Character.isLetter(ch) && Character.isLowerCase(ch))
{
System.out.println("Good!");
}
else if (Character.isDigit(ch) && Character.isUpperCase(ch) && variableName.contains(" "))
{
System.out.println("Illegal!");
}
//Allow user to input another name or quit
System.out.println("Enter another name or press q to quit: ");
variableName = in.nextLine();
} while (!variableName.equalsIgnoreCase("q"));
}
}
make sure to read the following documentation for your task. It's worth noting that the requirements don't actually match the real world requirements of Java variable names. However, the most difficult part of this task is the logic rather than the script. I've written an example script for you below:
Subsequent characters may be letters, digits, dollar signs, or underscore characters. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
import java.util.Scanner;
public class identifierCheck
{
public static void main(String[] args) {
String input = " ";
System.out.printf("type q to exit...\n");
while (input.charAt(0) != 'q' && input.length() == 1) // Note the length so that you can use q for starting variable names
{
input = requestLine();
if (checkValid(input))
{
System.out.printf("%s is legal...\n", input);
}
}
}
public static String requestLine()
{
Scanner cmd = new Scanner(System.in);
System.out.printf("Enter a variable name > ");
return cmd.nextLine();
}
public static boolean startsWithLetter(String input)
{
if (123 > (int)input.toLowerCase().charAt(0) && (int)input.toLowerCase().charAt(0) > 60)
{
return true;
}
else
{
return false;
}
}
public static boolean containsInvalid(String input)
{
if ((input.indexOf('$') != -1 || input.indexOf('_') != -1) && input.indexOf(' ') == -1)
{
System.out.printf("Using $ and/or _ in variable names is poor style...\n");
}
if (input.indexOf(' ') != -1) // Has a space in the string
{
return true;
}
else
{
return false;
}
}
public static boolean checkValid(String input)
{
if (!startsWithLetter(input))
{
System.out.printf("%s is illegal, must start with a letter (note: $ and _ are 'valid' to start variable names)...\n", input);
return false;
}
else if (containsInvalid(input))
{
System.out.printf("%s is illegal, it must not contain spaces...\n", input);
return false;
}
else
{
return true;
}
}
}
Good luck with your course! Java's an excellent language to learn.
I have a program that reads an input (a String) and prints that String reversed. Now, I need to read through the reversed String and replace all of the "A"s with "T"s, the "T"s with "A"s, the "G"s with "C"s and the "C"s to "G"s. So basically, the "complement". I tried to use multiple lines with a replace function but once the "A"s are turned into "T"s, it will replace all of those into "A"s so there are no "T"s at all. How can I replace the characters so that they do not override each other?
Here is my code if it helps! I don't have any functions to get the "complement" yet, but here is what I'm working with.
import java.util.*;
public class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read;
read = new Scanner(System.in);
String input = read.next();
String reverse="";
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
}
}
You can convert your reverse string to a char array like this:
char[] charArr = reverse.toCharArray();
Then you can iterate through it and change the characters that you want:
for(int i = 0; i < charArr.length; i++){
if(charArr[i] == 'A'){
charArr[i] = 't';
}
}
At the end you can convert the char array back to a string like this:
String str = new String(charArr);
Here is a code sample that you can try:
import java.util.Scanner;
class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read = new Scanner(System.in);
String input = read.next();
String reverse="";
StringBuilder sb = new StringBuilder();
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
for (char c: input.toCharArray()) { // user 'reverse' to operate on reversed string
switch (c) {
case 'A' : sb.append('T'); break;
case 'T' : sb.append('A'); break;
case 'G' : sb.append('C'); break;
case 'C' : sb.append('G'); break;
default : sb.append(""); break; // handle you're exceptions here
}
}
System.out.println("x: " + sb);
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
read.close();
}}
Well, switch-case is a kind of mapping technique which will map your case (as key) with it's values. In this case:
I am replacing 'A' with 'T' where the string contains 'A' by appending into the StringBuilder (to create a new string) and then break; which is a mandatory statement for single time execution only.
And the default keyword is for default case, which means if all of the cases are unsatisfied to be executed then the default case is called, you can do whatever you want to do by default if no case, condition matched.
Well, for your last question, You can make it generic if the problem states some pattern; if not you, unfortunately have to do it manually.
Use the replace method, but change your values to a "temporary" character. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)
Replace T -> x
Replace A -> T
Replace x -> A
Repeat for all your pairs.
I am writing a program that takes a string, splits it into words, converts the words into pig latin, and then returns the result string. I have it working to a certain point.
For example if I enter these words that do not start with a vowel into the program I get:
pig -> igpay
trash -> rashtay
duck -> uckday
(for words that do not start with vowels, they have their first letter removed, added to the end of the word along with "ay")
It also works when the word starts with a vowel (just take the word and add "yay" to the end).
For example if I enter these words into the program I get:
eat -> eatyay
areyay -> areyay
omelet -> omeletyay
Now the issue I am having is if I combine 2 words, one that starts with a vowel and one that doesn't, it prints out both like they both start with vowels.
For example if I enter these words into the program I get:
pig -> pigyay (should be igpay)
eat -> eatyay (correct)
It might be worth mentioning that the methods "isVowel" & "pigLatinEncrypt" are required to have in this program. Please disregard the other methods that are in the program.
public static void main(String[] args) {
// TODO code application logic here
String input, message;
int ans1, ans2, key;
input = JOptionPane.showInputDialog("1. to decrypt a message\n2. to encrypt a message");
ans1 = Integer.parseInt(input);
input = JOptionPane.showInputDialog("1. for an entire message reversal encryption\n"
+ "2. for a Pig-Latin encryption\n3. for a simple Caesar style encryption");
ans2 = Integer.parseInt(input);
if (ans2 == 3) {
input = JOptionPane.showInputDialog("Please enter a key for encryption");
key = Integer.parseInt(input);
}
input = JOptionPane.showInputDialog("Please enter the message to encrypt or decrypt");
message = input;
if (ans2 == 1) {
reverseEncryptandDecrypt(message);
}
if (ans2 == 2) {
String[] words = message.split(" ");
if (ans1 == 2) {
boolean isVowel = isVowel(words);
pigLatinEncrypt(words, isVowel);
}
if (ans1 == 1) {
pigLatinDecrypt(message);
}
}
}
public static void reverseEncryptandDecrypt(String message) {
char[] stringToCharArray = message.toCharArray();
System.out.print("You entered the message: ");
for (char c : stringToCharArray) {
System.out.print(c);
}
int i = stringToCharArray.length - 1, j = 0;
char[] reverse = new char[stringToCharArray.length];
while (i >= 0) {
reverse[j] = stringToCharArray[i];
i--;
j++;
}
System.out.print("\n\nThe result is: ");
for (char c : reverse) {
System.out.print(c);
}
System.out.println();
}
public static void pigLatinEncrypt(String[] words, boolean isVowel) {
for (String word : words) {
if (isVowel == true) {
System.out.print(word + "yay ");
} else {
System.out.print(word.substring(1) + word.substring(0, 1) + "ay ");
}
}
}
public static boolean isVowel(String[] words) {
boolean isVowel = false;
for (String word : words) {
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o")
|| word.startsWith("u")) {
isVowel = true;
}
}
return isVowel;
}
}
This method:
public static void pigLatinEncrypt(String[] words, boolean isVowel)
takes an array of words and a single isVowel boolean. Thus, if there is more than one word, and some, but not all, of them begin with vowels, there's no way to tell the method that.
You'll need to change the method definition. Either it should take only one word String (simplest), or it needs to take an array of isVowel booleans that correspond to the array of word
Edit: When I wrote this, I didn't look carefully at the rest of your code. But the isVowel method has the same problem: it takes an array of words, but returns a single boolean. This can't work, for the same reason--if some of the words start with vowels and some don't, what would the method return?
If you can make the isVowel method take a single String argument, that would be simplest. Then you'd call it multiple times. If you want to make isVowel return a boolean[], the method would do something like
boolean[] result = new boolean[words.length];
to create an array of boolean that has the same number of elements as words.
I have the following problem:
Today, everyone comes up with some clever phrase so you can remember
their phone number. You have been given the task to decipher these
phrases and find out what numbers you need to dial in order to contact
these places.
Description: You input will be series of letters, numbers and dashes. You will need to determine the number that the input sequence
represents in regular three - dash- four format (see example output).
You will also need to determine if the resulting number is a valid
number (seven digits) or if there is a number in the input at all.
Input: All letters will be in uppercase. The input string may be up to 25 characters long.
Output: A single line of output is all that is needed either printing the phone number, if the number is not a valid number or if
there is no number at all.
Translation Key ABC = 2 DEF = 3 GHI = 4 JKL = 5 MNO = 6 PRS = 7 TUV = 8 WXY = 9 Numbers will be as themselves and ignore all Q, Z
and dashes. Example Input: ITS-EASY Example Output : 487-3279
Example Input: ---2---3---TS-4 Example Output : Not a valid number.
Example Input: QZ---I-M-A-TEST Example Output : 462-8378 Example
Input: ---------- Example Output : No phone number.
I'm having trouble separating the dashes and unnecessary letters from the actual phrase that translates to the phone number. This is my program so far:
public static void main(String[] args) {
String cleverPhrase = getCleverPhrase("Input the phrase you use to remember a specific phone number (Max 25 characters allowed): ");
checkPhrase(cleverPhrase);
}
public static String getCleverPhrase(String prompt) {
String input;
System.out.print(prompt);
input = console.nextLine();
return input;
}
public static String checkPhrase(String cleverPhrase) {
int len = cleverPhrase.length();
String output = "";
do {
for(int i = 0; i <= len; i++) {
char current = cleverPhrase.charAt(i);
if (Character.isLetter(current)) {
String newCurrent = Character.toString(current);
if (newCurrent.equals('Q') || newCurrent.equals('Z')) {
}
}
}
} while ()
}
As you can see, I haven't made much progress. I don't know how to get the program to pick out the unnecessary letters and dashes and return just the letters that form the number. Could someone help me?
Check the following code..
public static String checkPhrase(String cleverPhrase) {
int len = cleverPhrase.length();
String output = "";
for (int i = 0; i <= len; i++) {
char current = cleverPhrase.charAt(i);
if (Character.isLetter(current)) {
if (current == 'A' || current == 'B' || current == 'C') {
output += "2";
} else if (current == 'D' || current == 'E' || current == 'F') {
output += "3";
} else if (...) {
....
}
}
if(output.length()==3){
output += "-";
}
}
if(output.isEmpty()){
output = "No phone number";
}else if(output.length()!=8){
output = "Not a valid number";
}
return output;
}
You can extend else-if for all other combinations of numbers. You don't have to check for invalid characters like - or Q or Z. The output variable will be get edited if it goes inside a if statement.
This method will be very handy in your case. Thanks to that you can replace this
if (current == 'A' || current == 'B' || current == 'C')
...
} else if (current == 'D' || current == 'E' || current == 'F') {
...
with this
StringUtils.replaceChars(input, "ABCDEF", "222333")
You can also get rid of all non-numbers simply by output.replaceAll( "[^\\d]", "" ). At the end, you can add the dash in a specific position and check if the number is valid.
To strip out the unwanted characters in your string, have a look at String.replaceAll
I'm fairly new to java and I was wondering on how to return my code to false if the 1st and last letter aren't the same
he whole instruction was to define and test a method called checkString that will take in the word as a parameter and checks whether the String begins and ends with the same letter. If both letters are the same the method returns true otherwise false (returns a boolean). The program treats lower and uppercase letters as equivalent
here's what I have:
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
System.out.printf ("%s begins and ends with the same letter.", checkString(word));
}
public static boolean checkString (String word) {
int stringLength = word.length();
String letter1 = (word.substring (0,1)).toUpperCase();
String lastletter = (word.substring ((stringLength-1),(stringLength))).toUpperCase();
if (letter1.equals(lastletter)){
return true;
} else {
return false;
}
}
}
As per your code; instead of:
if (letter1.equals(lastletter)) {
return true;
} else {
return false;
}
Just do:
return letter1.equals(lastletter);
However your checkString() {...} code should be:
public static boolean checkString (String word) {
int len = word.length();
word = word.toUpperCase(); //since you are testing them as upper case
char firstLetter = word.charAt(0);
char lastLetter = word.charAt(len - 1);
return firstLetter == lastLetter;
}
Also instead of:
System.out.printf (word + " begins and ends with the same letter.", checkString(word));
Use print():
System.out.print(word + " begins and ends with the same letter: " + checkString(word));
Edit:
If you want to use printf() try something like:
System.out.printf("%s begins and ends with the same letter. %s", word , checkString(word));
%s is like a place holder for word and the value returned by checkString(word).
You could do the following:
public boolean firstAndLast(String word)
{
return Character.toUpperCase(word.charAt(0)) == Character.toUpperCase(word.charAt(word.length()-1));
}
This checks the positions of 0 and length - 1 to see if they're equal to each other. If they are, it returns true, if not, false.
If you want to one-line it:
return (word.substring (0,1)).toUpperCase().equals(word.substring(word.length()-1).toUpperCase());
Before the .equals(...) it fetches the first character, converts it to one case, doesn't matter which one as long as you are using the same case later on.
word.substring(string.length()-1).toUpperCase();
Fetches the last key and converts it to upper case.
This is how I would write it most likely
private boolean isFirstAndLastEqual (String word) {
char first = Character.toUpperCase(word.charAt(0));
char last = Character.toUpperCase(word.charAt(word.length()-1));
return first == last;
}
You do not need such a complicated code.
Here is a very simple written method that does the work perfectly.
Code
public static boolean checkString (String word) {
return word.toLowerCase().charAt(0) == word.toLowerCase().charAt(word.length()-1);
}
Explaination
It compares the first and the last character of the String input put to lowercase so that it matches the lower and uppercases.
Your use of printf is wrong as you are not printing out the true/false value. Either add a boolean specifier to your output string or use println instead.
System.out.printf (word + " begins and ends with the same letter - %b\n", checkString(word));
System.out.println (word + " begins and ends with the same letter " + checkString(word));
You could do the following
public static boolean checkString(final String word) {
final String checkedString = word.toLowerCase();
final char[] chararray = checkedString.toCharArray();
if (chararray.length > 1) {
return chararray[0] == chararray[chararray.length-1];
} else {
return true;
}
}
This will convert the String to lower case. (You could also achieve this with word.toUpperCase();) After that the String is converted to a char Array and then checks the first and the last "char". if the given String is of length "0" then true will be returned. Depending on how you want to decide for emtpy Strings you could also change this to false
This should give you what you're looking for.
This gets the first letter (character at index 0): firstletter = (word.charAt(0)).toUpperCase();
This gets the last letter: firstletter = (word.charAt(0)).toUpperCase();The last character is at index word.length-1. For example, if your word is "apple", it has a length of 5, but the last character is at index 4 (remember, 0-4 not 1-5; letter1 is misleading, it's actually letter0).
As mentioned by Savior Self, using charAt is more efficient. Also, being that you'd use char's rather than String's and == to compare them.
Also, you would assign the return value to a variable when you call checkString. For instance, boolean checkStr = checkString(word); and then use checkStr in your print statement.
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
boolean checkStr = checkString(word);
System.out.println(word + " begins and ends with the same letter: " + checkStr;
}
public static boolean checkString (String word) {
char firstletter = (word.charAt(0)).toUpperCase();
char lastletter = (word.charAt(word.length-1)).toUpperCase();
return (firstletter == lastletter);
}
}
Also, since I don't have enough points to comment, a better one-liner would be:
return (word.charAt(0)).toUpperCase() == (word.charAt(word.length-1)).toUpperCase());