Java User input YY-MM-DD format - java

This is for an assignment in data structures and I can't seem to find the exact answer I need.
I am attempting to take user input for a date, preferably YY-MM-DD format, then check for validity.. if not valid, cycling until valid. This really seems very tedious and I am receiving two illegal starts of expression errors.
I did a search on Google and StackOverflow, but only find things addressing Date
public String hireDate(){
Scanner input = new Scanner(System.in);
boolean answer = false;
while(answer == false){
String temp = input.nextLine();
if((temp.charAt(0) >= 0 && temp.charAt(0) <= 9) && (temp.charAt(1)
>= 0 && temp.charAt(1) <= 9) && (temp.charAt(2) == -)
&& (temp.charAt(3) >= 0 && temp.charAt(3) <= 9) && (temp.charAt(4)
>= 0 && temp.charAt(4) <= 9) && (temp.charAt(5) == -)
&& (temp.charAt(6) >= 0 && temp.charAt(6) <= 9)){
answer = true;
} else {
answer = false;
}
}
return temp;
}

You can do it easily with Regex. Just check if your input string matches your pattern (YY-MM-DD)
if (temp.matches("\\d{2}-\\d{2}-\\d{2}"))

temp.charAt(1)>=0
You are comparing a character to an integer.

Related

Do while loop for Try again program not working correctly (java)

I created a program that convert text to ASCII value and now when i press Y to try again and input a new string there will be a error that string is out of range etc.
I am new in this field, I will appreciate your help.
And here is the Error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 17,length 17
at java.base/java.lang.String.checkIndex(String.java:3278)
at java.base/java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:307)
at java.base/java.lang.StringBuffer.charAt(StringBuffer.java:242)
at com.company.Main.main(Main.java:26)
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
boolean Flag; // The Boolean variable for the do while lopp
int n,l,j=0,m,i,ch;
char t;
StringBuffer data = new StringBuffer();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter any string and it will convert into numbers:- ");
data.append(input.nextLine());
l = data.length();
m = l;
System.out.println(l);
for (i = 0; i < m; i++) {
t = data.charAt(j);
n = (int) t;
System.out.print(n);
System.out.print(",");
j++;
}
data.delete(0, m-1);
System.out.println("\nDo you want to try again? Y/N");
ch = input.nextInt();
//Those are the condition for that the program should be run again or not
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
}
while(Flag=true);
System.out.println("Thanks, Come Again");
}
}
while(Flag=true);
this doesn't check whether the value of Flag is true, it sets it to true, and thus automatically returns true.
What you want is:
while(Flag==true);
or,
while(Flag);
for short.
You may also want to read up about naming conventions.
As for your Exception:
Y is not an int, change your
ch = input.nextInt();
to
ch = input.nextLine().charAt(0);
this will solve the initial problem, but still might lead to false results with unexpected input (or lack there of)
int n,l,j=0,m,i,ch;
This declaration is invalid. If all of these values are supposed to be
0, the declaration should look like:
int n, l, j, m, i, ch = 0
Also your logic in the nextInput section is incorrect.
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
Instead of the AND ( && ) this should be an OR ( || ). If it's 'Y' OR it's 'y'. It will likely never be both Y and y. This should be fixed as follows:
if (ch == 'Y' || ch == 'y') {
Flag = true;
} else if (ch == 'N' || ch == 'n') {
Flag = false;
}
Also, as mentioned by #Stultuske, you'll want to change your while condition to:
while (Flag == true)
One thing that's niggling at me here is that ch is an integer, but you're asking it if that value is 'Y, y, N, n' those are characters and not integers. I'm guessing that's why you got the 'Input_Mismatch_Exception'. Hope this helps.
Edit: Formatting

Logical OR does not work properly in the while loop

The problem is that, the first condition in the while loop does not get executed at all even if its true. If i remove the Logical OR from the while loop and just write the first condition (selection.compareToIgnoreCase("O") >0) it works fine. But if there are two conditions with Logical OR, it does not work.
I've tried using equals(), I've also tried to negate the logic using
while(!selection.equals("O") || !selection.equals("E")). The second condition works fine but the first does not work at all.
public class OddsOrEvens {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
System.out.println("Let’s play a game called \"Odds and Evens\"");
System.out.println("Whats your name ? ");
String name = sc.nextLine();
System.out.println("Hi "+ name +", which do you choose? (O)dds or (E)vens?");
String selection = sc.nextLine();
System.out.println("selection: " + selection);
while (selection.compareToIgnoreCase("O") >0 || selection.compareToIgnoreCase("E") >0){
System.out.println("Please enter the correct choice. Select 'O' for odds or 'E' for evens");
selection = sc.next();
}
if(selection.equalsIgnoreCase("O")){
System.out.println(name + " has picked Odds! The computer will be evens.");
}else if (selection.equalsIgnoreCase("E")){
System.out.println(name + " has picked Evens! The computer will be Odds.");
}
}
}
Your string comparison is not correct. Compareto returns -1/0/1 for less/equal/greater.
A clearer way to do this is to use toUppercase().equals(....
while (!selection.toUpperCase().equals("O") && !selection.toUpperCase().equals("E")){
That is for not to hold for two cases, one needs !... && ! ... An OR || would have the effect of being always true, as at least one of the cases is false. Alternatively !(... || ...).
while (!selection.equalsIgnoreCase("O") && !selection.equalsIgnoreCase("E")) {
Let's simplify:
!(n == 1) || !(n == 2) // WRONG
n != 1 || n != 2 // WRONG
will always be true, as either n == 1 is false or n == 2 is false: at most one choice can be true, falsifying the others. So on at least on side is !false, true, so the entire expression is true.
!(n == 1) && !(n == 2) // GOOD
n != 1 && n != 2 // GOOD
The mental mistake is that the linguistic OR mostly means EXCLUSIVE OR.
Possible would have been the equivalent:
!(n == 1 || n == 2) <=> n != 1 && n != 2 [De Morgan's law]

Java.... Prints 1 error for each character in the input

Im a rookie Java coder, and I am trying to make a very basic username/password program. The username part of it is working fine, but when I get to the password it gives me some weird problems. I figured out that for example when it checks for an Uppercase letter, if it finds one its all good, but if it doesn't, it prints the error message for every single character in the password. It does this with the number check and the length check as well. If any of you guys could explain this to me rather simply since I am still new to java, that would be awesome. Thanks!
do
{
if (count3 >0)
{
System.err.println("- At least 1 Uppercase");
System.err.println("- At least 1 number");
System.err.println("- At least 7 characters long.");
}
regPassword = input.nextLine();
regPasswordLen = regPassword.length();
for(int count = 0; count < regPasswordLen; count++)
{
if(Character.isUpperCase(regPassword.charAt(count)))
regPasswordUppercaseCheck = true;
else
{
System.err.println("Your password did not contain an Uppercase letter");
regPasswordUppercaseCheck = false;
}
if(regPassword.contains("1") || regPassword.contains("2") ||
regPassword.contains("3") || regPassword.contains("4") ||
regPassword.contains("5") || regPassword.contains("6") ||
regPassword.contains("7") || regPassword.contains("8") ||
regPassword.contains("9") || regPassword.contains("0"))
regPasswordNumCheck = true;
else
{
System.err.println("Your password did not contain at least 1 number.");
regPasswordNumCheck = false;
}
if (regPasswordLen >=7)
regPasswordLengthCheck = true;
else
{
System.err.println("Your password did not meet the minimum length requirements.");
regPasswordLengthCheck = false;
}
}
count3++;
}
while(!regPasswordUppercaseCheck || !regPasswordNumCheck || !regPasswordLengthCheck);
System.out.println("test");
You used same variable every time for "if and else" for every different char i.e. regPasswordUppercaseCheck, if every char of your input is in uppercase except the last char, the variable will contain false.
I think you use count3 for making sure that inner code will run single time but if while goes false and count3 condition is remain true then code will stuck in a infinite loop.
Use
while(regPasswordUppercaseCheck && regPasswordNumCheck && regPasswordLengthCheck); for simplicity.
A few things you can change in your program.
do
{
if (count3 >0)
{
System.err.println("- At least 1 Uppercase");
System.err.println("- At least 1 number");
System.err.println("- At least 7 characters long, but no more than 15 characters.");
}
regPassword = input.nextLine();
regPasswordLen = regPassword.length();
// this check only needs to happen once per password, no need to check it in the for loop. You also specified that the length should not exceed 15 characters, so I threw that in as well
if (regPasswordLen < 7 || regPasswordLen > 15)
System.err.println("Your password did not meet the length requirements.");
// by default, we set these flags to false, and only make them true if the requirements are satisfied
regPasswordUppercaseCheck = false;
regPasswordNumCheck = false;
for(int count = 0; count < regPasswordLen; count++)
{
// store the value of regPassword.charAt(count) in a local variable for reusability
char current = regPassword.charAt(count);
if(Character.isUpperCase(current))
regPasswordUppercaseCheck = true;
// checks if the character is a digit or not
if(current >= '0' && current <= '9')
regPasswordNumCheck = true;
}
if (!regPasswordNumCheck)
System.err.println("Your password did not contain at least 1 number.");
if (!regPasswordUppercaseCheck)
System.err.println("Your password did not contain an Uppercase letter");
count3++;
}
while(!regPasswordUppercaseCheck || !regPasswordNumCheck || !regPasswordLengthCheck);
your checking for uppercase is not done right because the loop
for(int count=0;count<regPasswordLength;count++) should not contain the checking if the password contains a number nor the checking if the password is longer than 7 characters so the loop should look like this
for (int count = 0; count < regPasswordLen; count++) {
if (Character.isUpperCase(regPassword.charAt(count)))
{regPasswordUppercaseCheck = true;break;}
}
i use break here to get out of the loop the moment i found that password contains an uppercase after some modifications your code can look like this
do {
if (count3 > 0) {
System.err.println("- At least 1 Uppercase");
System.err.println("- At least 1 number");
System.err
.println("- At least 7 characters long, but no more than 15 characters.");
}
regPassword = input.nextLine();
regPasswordLen = regPassword.length();
for (int count = 0; count < regPasswordLen; count++) {
if (Character.isUpperCase(regPassword.charAt(count)))
{regPasswordUppercaseCheck = true;break;}
}
if(regPasswordUppercaseCheck==false){
System.err
.println("Your password did not contain an Uppercase letter");
regPasswordUppercaseCheck = false;
}
regPasswordNumCheck = regPassword.contains("1") || regPassword.contains("2")
|| regPassword.contains("3")
|| regPassword.contains("4")
|| regPassword.contains("5")
|| regPassword.contains("6")
|| regPassword.contains("7")
|| regPassword.contains("8")
|| regPassword.contains("9")
|| regPassword.contains("0");
if(regPasswordNumCheck==false) {
System.err
.println("Your password did not contain at least 1 number.");
regPasswordNumCheck = false;
}
if (regPasswordLen >= 7)
regPasswordLengthCheck = true;
else {
System.err
.println("Your password did not meet the minimum length requirements.");
regPasswordLengthCheck = false;
}
count3++;
} while (!regPasswordUppercaseCheck || !regPasswordNumCheck
|| !regPasswordLengthCheck);
System.out.println("test");

While loop one condition always returning true?

I am trying to make a conditional statement with two "ifs", and it works when I input the correct thing, but when I input an incorrect pokemon and a correct level it still works. I am pretty sure that one of the conditions in my while statement is always true (the first part). Here is the code (sorry about the formatting, just know that it is all formatted correctly in the Java environment):
while ((!(Pokemon.equalsIgnoreCase(Pikachu)) || !(Pokemon.equalsIgnoreCase(Charmander)) || !(Pokemon.equalsIgnoreCase(Squirtle)) || !(Pokemon.equalsIgnoreCase(Bulbasaur))) && !((Level <= 15)&&(Level >= 1 ))) {
System.out.println();
System.out.println("Which one would you like? What level should it be?\n1 to 15 would be best, I think.");
Pokemon = sc.next();
Level = sc.nextInt();
if ((Level <= 15) && (Level >= 1)) {
if ((Pokemon.equalsIgnoreCase(Pikachu)) || (Pokemon.equalsIgnoreCase(Charmander)) || (Pokemon.equalsIgnoreCase(Squirtle)) || (Pokemon.equalsIgnoreCase(Bulbasaur))) {
System.out.print("Added level " + Level + " " + Pokemon + " for " + Trainer + ".");
}
else {
System.out.println("Invalid Pokemon!");
}
}
else {
System.out.println("Invalid Level!");
}
}
Pokeman will always be either not X or not Y, it's basic logic since if it's X, then not-Y is true. If it's Y, then not-X is true. If it's neither then both will be true.
Change || to && and think through your logic on paper.
Should be:
while ((!(Pokemon.equalsIgnoreCase(Pikachu)) &&
!(Pokemon.equalsIgnoreCase(Charmander)) &&
!(Pokemon.equalsIgnoreCase(Squirtle)) &&
!(Pokemon.equalsIgnoreCase(Bulbasaur))) &&
!((Level <= 15)&&(Level >= 1 )))

How to turn a user given String into Pig Latin?

Im trying to turn a string taken from the user into Pig Latin. I cannot use any special classes, methods, or arrays. I can only use a Scanner to create a object to take the string from the user and .length and .charAt, in addition to any type of looping. (Also cannot use switch statements or the break keyword)
Here is an example of what my output is suppose to be:
Enter a line of text: this is a test.
Input : this is a line of text.
Output: his-tay is-way a-way ine-lay of-way ext-tay.
Here is my code, I can only get my code to work with one word and it must have a space at the end. Only one loop works at a time depending on the loop. Im not sure what to do if I get an entire String.
I know that when the user enters a space that signals a new word, and when they enter a period, that signals the ending.
I had a hard time understanding your code. (It looks like you are trying to do it two ways at once?) Regardless, I believe I was able to understand your question. Here is a compilable and runnable example:
import java.util.Scanner;
public class PigLatin
{
public static void main(String[] args)
{
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
if (text != null && text.length() > 0)
{
int i = 0;
// this iterates through the whole string, stopping at a period or
// the end of the string, whichever is closer
while (i < text.length() && text.charAt(i) != '.')
{
// these three variables only exist in this code block,
// so they will be re-initialized to these values
// each time this while loop is executed
char first = '\0'; // don't worry about this, I just use this value as a default initializer
boolean isFirst = true;
boolean firstIsVowel = false;
// each iteration of this while loop should be a word, since it
// stops iterating when a space is encountered
while (i < text.length()
&& text.charAt(i) != ' '
&& text.charAt(i) != '.')
{
// this is the first letter in this word
if (isFirst)
{
first = text.charAt(i);
// deal with words starting in vowels
if (first == 'a' || first == 'A' || first == 'e' || first == 'E'
|| first == 'i' || first == 'I' || first == 'o' || first == 'O'
|| first == 'u' || first == 'U')
{
System.out.print(first);
firstIsVowel = true;
}
// make sure we don't read another character as the first
// character in this word
isFirst = false;
}
else
{
System.out.print(text.charAt(i));
}
i++;
}
if (firstIsVowel)
{
System.out.print("-tay ");
}
else if (first != '\0')
{
System.out.print("-" + first + "ay ");
}
i++;
}
System.out.print('\n'); //for clean otuput
}
}
}
There are a few comments in there that might help guide you through my logic. This is almost definitely not the most efficient way to do this (even with your limitations), as I only whipped it up as a example of the type of logic you could use.
You could break it up into words, then process the current word when you hit a space or period:
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
String curWord = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' || text.charAt(i) == '.') {
if (curWord.charAt(0) == 'a' || curWord.charAt(0) == 'e' ||
curWord.charAt(0) == 'i' || curWord.charAt(0) == 'o' ||
curWord.charAt(0) == 'u') {
System.out.print(curWord + "-way ");
} else {
for (int j = 1; j < curWord.length(); j++) {
System.out.print(curWord.charAt(j);
}
System.out.print("-" + curWord.charAt(0) + "ay ");
//System.out.print(curWord.substring(1)+"-"+curWord.charAt(0)+"ay ");
}
curWord = "";
} else {
curWord += text.charAt(i);
}
}

Categories

Resources