How do I validate erate to two decimal places? - java

When I try to use the validation methods for erate it always comes up as invalid, how do I fix the validation method using the code I used inside the method.
input = JOptionPane.showInputDialog("Enter employee hourly rate: ");
while(checkEname(input) == false)
{
input = JOptionPane.showInputDialog("Invalid! Only rate of two decimal places allowed! Re-enter employee hourly rate ");
}//end while
erate = Double.parseDouble(input);
This is the validation methods called
boolean checkErate(String input)
{
int dotCount = 0;
for(int i = 0; i < input.length(); i++)
if(input.charAt(i) == '.')
dotCount++;
else
if(!Character.isDigit(input.charAt(i)))
return false;
if(dotCount !=1 )
return false;
else
if(input.charAt(input.length() - 3) == '.')
return true;
else
return false;
}//end checkErate

There is a simpler way to check if the erate is a valid number.
Instead of doing the search for the decimal point, and evaluating it's position, what you can do instead is something like this:
String [] inputSplit = input.split(".");
if (inputSplit.length() >2) {
return false;
}
if (Pattern.matches("[a-zA-Z]+", inputSplit[0]) == false || Pattern.matches("[a-zA-Z]+", inputSplit[1]) == false){
return false;
}

Related

Compilation Error in a very silly program

import java.util.Scanner;
public class KekOrCringe {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userGuess = "";
boolean Continue = true;
boolean ProperResponse = true;
boolean IsCorrect = true;
boolean YesNo = true;
while (Continue)
{
int secretAnswer = (int)(Math.random() * 2 + 1);
kekOrCringe(secretAnswer);
while (!IsCorrect)
{
System.out.println("Kek or Cringe?");
ProperResponse = false;
while (!ProperResponse) {
userGuess = scan.nextLine();
if (userGuess != "Kek")
System.out.println("Your entry is invalid, please try again!");
else if (userGuess != "Cringe")
System.out.println("Your entry is invalid, please try again!");
else
ProperResponse = true;
}
for (int guessCount = 0; guessCount < 1; guessCount++) {
if (userGuess = "Cringe" && userGuess != secretAnswer) {
System.out.println("It's KeK!");
guessCount++; }
else if (userGuess = "Kek" && userGuess != secretAnswer) {
System.out.println("It's CrInGe!");
guessCount++; }
else
System.out.println("Mr. Morgan, you got it right my boy!");
IsCorrect = true;
}
}
}
YesNo = false;
while(!YesNo) {
System.out.println("Would you like to play again? Yes/No");
String answer = scan.nextLine();
if (answer.equals("No")) {
Continue = false;
YesNo = true;
System.out.println("Fine. You were Cringe anyway!");
}
else if (answer.equals("Yes")) {
YesNo = true;
Continue = true;
IsCorrect = false;
}
}
}
public static String kekOrCringe(int secretAnswer) {
if (secretAnswer = 1) { return "Kek";}
if (secretAnswer = 2) { return "Cringe";}
}
}
Probably an overly complex way to do something unnecessary, but this is my first year in college learning to code, and I was asked to give this a try. I think it's funny, and will probably be funnier if it work, along with being good practice. I'm having trouble converting the int secretAnswer to a returned string, and then comparing the userGuess to the return type. Getting compilation errors on line 32 and 35. Any tips would be appreciated.
P.S. I realize it's silly. Trying to use this silly code as a learning opportunity.
Im guessing line 32 and 35 are the two ifs. userGuess != secretAnswer doesn't work since one is a String, the other an Integer. Your static method kekOrCringe(secretAnswer); returns the String you want, you just need to save it in a variable and then compare it to the userGuess.
Also please use lowercase variable names.
I can't add a comment so I am writing here.
userGuess is String but secretAnswer is int, and you are trying to check if they are equal (userGuess != secretAnswer).
You can use a new variable like secretGuess, assign kekOrCringe(secretAnswer) to secretGuess and check if userGuess is equal to secretGuess.
Like this:
String secretGuess = kekOrCringe(secretAnswer);
if (userGuess != secretGuess) {
//...
}
You are trying to compare int to string which is wrong
userGuess != secretAnswer
Also, instead of comparing you are assigning values inside if condition.
if (secretAnswer = 1) { return "Kek";}
if (secretAnswer = 2) { return "Cringe";}
It should be:
if (secretAnswer == 1) { return "Kek";}
if (secretAnswer == 2) { return "Cringe";}

Rejecting Duplicates of Same Number

Here are the instructions for what I am supposed to be doing.
Write a program that inputs a string that represents a binary number.
The string can contain only 0s and 1s and no other characters, not
even spaces.
Validate that the entered number meets these requirements. If it does
not, display an error message. If it is a valid binary number,
determine the number of 1s that it contains. If it has exactly two 1s,
display "Accepted". Otherwise, display "Rejected".
All input and output should be from the console. Here are some sample
inputs to test:
abc 10102011 10101FF 0000 1111 (note the space in this test case)
00000000 1111 01110000001 1000001
What I have so far is written here:
import java.util.Scanner;
import java.util.Set;
class ValidateBinary1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
boolean notCorrect = false;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
isCorrect = true;
}
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
}
}
if(isCorrect)
System.out.println("Accepted");
else if(notCorrect)
System.out.println("Rejected");
}
}
What can I write to have the program output the "rejected" line?
Try this ( you are using bitwise operator & instead of logical operator &&) but I dont think using && either is correct; you have to use bitwise or ||. Also you are not check for the number of ones, the number of ones in the input string must be exactly 2 according to your problem description.
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
short numberOfOnes = 0;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
numberOfOnes++;
}
else if(! (binary.charAt(i) == '0' || binary.charAt(i) == '1'))
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
break;
}
}
if(isCorrect && numberOfOnes == 2)
System.out.println("Accepted");
else
System.out.println("Rejected");
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
boolean isCountCorrect = true;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1' || binary.charAt(i) == '0') {
continue;
} else {
isCorrect = false;
break;
}
}
if (isCorrect == true) {
int count = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
count++;
}
}
if (count > 2) {
isCountCorrect = false;
}
}
if (isCorrect = true && isCountCorrect == true) {
System.out.println("Approved");
} else
System.out.println("Rejected");
}
Here we go. I took one of the answers and used it to modify my code and came up with this:
import java.util.Scanner;
import java.util.Set;
class ValidateBinary1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
short numberOfOnes = 0;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
numberOfOnes++;
}
else if(binary.charAt(i) != '0' && binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
}
}
if(isCorrect && numberOfOnes == 2)
System.out.println("Accepted");
else
System.out.println("Rejected");
}
}
This is exactly what I needed. Thanks!

How do I break out of a loop while reading in a string?

For example:
Scanner keyboard = new Scanner(System.in);
int counter=1;
while (!(keyboard.equals('0')))
{
for (int i=1;i<=counter;i++)
{
prodNum[i]=keyboard.nextInt();
quantity[i]= keyboard.nextInt();
}
counter++;
}
How do I break out of a loop when I enter in a zero? I can't seem to figure it out. It keeps taking input, even when I enter a zero? I need for it keep taking input until the user enters a zero.
Any ideas what I'm doing wrong?
keyboard.equals('0') will compile, but it is never going to evaluate to true, because Scanner object cannot possibly be equal to a Character object.
If you would like to wait for the scanner to return zero to you, you should call next() or nextLine() on it, and compare the resultant String object to "0".
while (true) {
while (keyboard.hasNext() && !keyboard.hasNextInt()) {
System.out.println("Please enter an integer value.");
keyboard.nextLine();
}
if (!keyboard.hasNextInt())
break;
prodNum[i]=keyboard.nextInt();
if (prodNum[i] == 0)
break;
while (keyboard.hasNext() && !keyboard.hasNextInt()) {
System.out.println("Please enter an integer value.");
keyboard.nextLine();
}
if (!keyboard.hasNextInt())
break;
quantity[i]=keyboard.nextInt();
if (quantity[i] == 0)
break;
i++;
}
Demo.
int counter=1;
int flag = 1;
while (flag != 0)
{
for (int i=1;i<=counter;i++)
{
if(flag == 0)
{
break;
}
prodNum[i]=keyboard.nextInt();
quantity[i]= keyboard.nextInt();
flag = quantity[i];
}
counter++;
}

Data validation in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Well let's just say that this used to work fine then I started it up again today and now it doesn't....
pin is 1234 and no matter what I do it says it's not valid...
and yes I know that it doesn't check the third time. I have to fix that too:
import java.util.Scanner;
import java.util.Scanner;
public class ATM
{
public ATM()
{
Scanner console = new Scanner(System.in);
final String pin = "1234";
String userPin = "";
int pinCount = 1;
boolean error = false;
do{
System.out.print("Enter PIN: ");
userPin = console.nextLine();
if (pinCount == 3) {
System.out.println("Bank account is blocked");
break;
}
else if (userPin.length() < 4 || userPin.length() > 4) {
error = true;
pinCount += 1;
}
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
else{
System.out.println("Your PIN is incorrect");
error = true;
pinCount += 1;
}
}while(error);
}
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
Don't ask me why I have it split:
public class ATMtest
{
public static void main(String[] args)
{
ATM atm = new ATM();
}
}
Any help would be greatly appreciated.
You don't compare String objects with ==. You should use the equals() method. I know it does not make sense if you are new in java but == means "are they the same reference?" and equals() means "are they equal?".
userPin == pin should be userPin.equals(pin)
You declare two String variables in your code:
final String pin = "1234";
String userPin = "";
and you validate them whether they are equal to or not.
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
String comparison should be used equals method rather than ==
Change
userPin == pin
To
userPin.equals(pin)
For digit match with exact 4 length use \d{4} regex and remove all boilerplate code on if else statement for validation.
public static boolean isNumeric(String str) {
Pattern p = Pattern.compile("\\d{4}");
Matcher matcher = p.matcher(str);
return matcher.matches();
}
For String comparison use equals method inted of == . Change it from
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
To
else if (isNumeric(userPin) && userPin.equals(pin) && pinCount < 3) {
Change this as
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
this
else if (isNumeric(userPin) && userPin.equals(pin) && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
Would a switch not be better here instead of all those if conditions?

Looping an array

void searchForPopulationChange()
{
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
input = scan.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
}
}
}
hello!
I am working on a method that will take an users input,
lets say (5000) and search a data file with those corresponding numbers.
and return the corresponding number, and county that it corresponds with.
However, I am able to get this code to run to return the correct value,
but i am unable to get it to run when i enter an "incorrect" value.
Any pointers?
Thank you!
It's a bit unclear, but I assume you want something to handle if the input is incorrect (not an integer)? Use hasNextInt so you will only capture integers.
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
int num = scanner.nextInt();
This will keep looping the input until it is a valid integer. You can include a message in the loop reminding the user to input a correct number.
If you want something to display if your number has no match inside of the array, simply add code after your for block, if found == false. For example:
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}
Since found is still false, your while loop kicks in and prints your line requesting for input again.
EDIT: Since you seem to have problem adding these two concepts to your code, here's the whole function:
void searchForPopulationChange() {
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
input = scanner.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}
}
}

Categories