Testing For Two Pairs In a Given String - java

You get user input of a string of four positive integers ex "0 1 1 2" test to see if there are two pairs present in the string. The IntegerPairs object will have a constructor that takes no arguments and the following two methods:
public void setPairString(String str) - This method will take a string as an argument and then store it in an instance variable.
public boolean hasTwoPairs() - This will return true when there are only two pairs present in the string.
You can use a Scanner on a string as well as System.in. It works the same way but the constructor takes a string rather than System.in.
After you are done with the scanner be sure to call {your scaner variable name}.close();
Don't be afraid to make local variables. You can use them to hold the numbers you get from the string.
That is my project and I am horribly lost.... Don't want anyone to do it for me, of course, but I would love to have even just a little more instruction on this. My code so far: (not very much at all and I have been sitting here stumped for 3-4 hours straight)
My class:
public class IntegerPairs {
private String str;
public IntegerPairs(String pairs){
str = pairs;
}
public void setPairString(String str){
this.str = str;
}
public boolean hasTwoPairs(){
No idea what to do for the boolean method. I am assuming I have to do a loop somewhere?
Haven't even gotten to the main class because I need to figure this out first.
EDIT
This was more what I was looking for:
public class IntegerPairs {
private String theString;
public IntegerPairs() {
}
public void setPairString(String str) {
theString = str;
}
public boolean hasTwoPairs() {
String a = theString.substring(0, 1);
String b = theString.substring(1, 2);
String c = theString.substring(2, 3);
String d = theString.substring(3, 4);
boolean isThereTwopairs = (a.equals(b) && c.equals(d)) ? true
: ((a + b).equals(c + d)) ? true : false;
return isThereTwopairs;
}
}
Then the main class:
import java.util.*;
public class Main {
public static void main(String[] args) {
IntegerPairs Str = new IntegerPairs();
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter 4 numbers:");
String pairIn = keyboard.nextLine();
keyboard.close();
Str.setPairString(pairIn);
boolean isThereTwoPairs = Str.hasTwoPairs();
String whatToPrint = (isThereTwoPairs == true) ? "There Are Two Pairs"
: "There Are Not Two Pairs";
System.out.print(whatToPrint);
}
}
Took me a while but finally got it. My next question is: I am running a Junit test but it's telling me that:
"Newly constructed IntegerPairs object should not have two pairs.",
ip.hasTwoPairs());
Not quite sure what that means because my constructor has no assignment.

Is it absolutely necessary to resolve this through constructors? It seems like regex is the perfect key.
Below is one, **not elegant & quickly baked **, solution. Enjoy.
public class Success {
static int f = 4; //declare a static variable that may suffer modifications below
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Insert, please, 4 digits!"); // the input may be any character
int one= input.replaceAll("[^1]", "").length(); //using regex and the length() method, we count for how many times the digit 1 is repeated in our String: input. The result is stored in int one
int two= input.replaceAll("[^2]", "").length(); // the same here, for digit 2
int three= input.replaceAll("[^3]", "").length(); // the same, for digit 3
int four= input.replaceAll("[^4]", "").length(); // the same, for digit 4
int five= input.replaceAll("[^5]", "").length(); // the same, for digit 5
int six= input.replaceAll("[^6]", "").length(); // the same, for digit 6
int seven= input.replaceAll("[^7]", "").length(); // the same, for digit 7
int eight= input.replaceAll("[^8]", "").length(); // the same, for digit 8
int nine= input.replaceAll("[^9]", "").length(); // the same, for digit 9
int zero= input.replaceAll("[^0]", "").length(); // the same, for digit 0
if(one == 2){ // if the stored result in int one, from the operation above is 2, then we have a pair in the inputted String
f = f-2; // thus, we remove 2 from f (f was declared above as static, 4). The point is if f, by the end of those if statements will be equal to 0, then our String has 2 pairs of digits
}
if(one == 3){ // if the stored result in int one, from the operation above is 3, then we have a pair in the inputted String
f = f-2; // thus, we remove 2 from f
}
if(one == 4){ // if the stored result in int one, from the operation above is 4, then we have two pairs in the inputted String
f=f-4;
}
if(two == 2){
f = f-2;
}
if(two == 4){
f=f-4;
}
if(two == 3){
f = f-2;
}
if(three == 2){
f = f-2;
}
if(three == 4){
f=f-4;
}
if(three == 3){
f = f-2;
}
if(four == 2){
f = f-2;
}
if(four == 4){
f=f-4;
}
if(four == 3){
f = f-2;
}
if(five == 2){
f = f-2;
}
if(five == 4){
f=f-4;
}
if(five == 3){
f = f-2;
}
if(six == 2){
f = f-2;
}
if(six == 4){
f=f-4;
}
if(six == 3){
f = f-2;
}
if(seven == 2){
f = f-2;
}
if(seven == 4){
f=f-4;
}
if(seven == 3){
f = f-2;
}
if(eight == 2){
f = f-2;
}
if(eight == 4){
f=f-4;
}
if(eight == 3){
f = f-2;
}
if(nine == 2){
f = f-2;
}
if(nine == 4){
f=f-4;
}
if(nine == 3){
f = f-2;
}
if(zero == 2){
f = f-2;
}
if(zero == 4){
f=f-4;
}
if(zero == 3){
f = f-2;
}
if (f == 0) {
JOptionPane.showMessageDialog(null, "There are TWO pairs!");
} else if (f == 2) {
JOptionPane.showMessageDialog(null, "There is only ONE pair!");
} else if (f == 4) {
JOptionPane.showMessageDialog(null, "There are NO pairs!");
}
}

What you have to do is use a loop and an if statement to compare every character to every other character in the string and use a counter when a pair is found but if the counter is not equal to two, your boolean should be made to return false. Your boolean method should check the counter that's all.

One solution for this would be to split your String by spaces and put each token into a Map<String, Integer> where the key is the token and the value is a count.
Here's a quick & dirty example:
String input = "0 1 1 2";
// splitting on space
String[] split = input.split(" ");
// initializing map
Map<String, Integer> map = new HashMap<String, Integer>();
// iterating over split
for (String s: split) {
// token already present: incrementing its count
if (map.containsKey(s)) {
map.put(s, map.get(s) + 1);
}
// token not there yet: putting count as 1
else {
map.put(s, 1);
}
}
// initializing counter for # of pairs
int pairsCounter = 0;
// iterating counts
for (Integer i: map.values()) {
// a count == 2 is a pair: increasing count of pairs
if (i == 2) {
pairsCounter++;
}
}
// printing output: do we have exactly 2 pairs?
System.out.printf("Input contains 2 numerical pairs? %b%n", pairsCounter == 2);
Output
Input contains 2 numerical pairs? false

If your working with numbers, you should store them to int, double etc. I would recommend that you would do that in constructor, after that, you can easily check if first two numbers are pair, and do same for second two numbers.

So the first thing is:
IntegerPairs object will have a constructor that takes no arguments
But your constructor does take an argument.
Now to the solution. Try to implement the following algorithm:
Split the string by using the space ' ' as delimiter
Hint: look at the documentation for String.split()
The result is an array of the split strings. You can insert a check, if there are really four elements. If you don't want to: skip this point
Then you can simply check, if first and second element are equal and third and fourth element are equal, since this is the only possible way of having two pairs.
Good Luck!

Related

Getting the final else statement to run Java recursive method

Everything works in this class except for the final else statement. This is a recursive java letter tester. The program tests a user's word for all three letters (e, l, f). So far, Program throws exception error string index out of bounds if the word doesn't contain e, l and f
import java.util.Scanner;
public class FrettyRecursionMethod {
static boolean e = false;
static boolean f = false;
static boolean l = false;
static int n = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userWord;
System.out.println("Enter a single word.");
userWord = input.nextLine();
elfish(userWord, 0);
} // end main
public static void elfish(String userWord, int n) {
char ee = userWord.charAt(n);
if (ee == 'e' || ee == 'E') {
e = true;
} // end if
else if (ee == 'f' || ee == 'F') {
f = true;
} // end else if
else if (ee == 'l' || ee == 'L') {
l = true;
} // end else if
if (e == true && f == true && l == true) {
System.out.println("Your word is elfish!");
}
else if (n < userWord.length()) {
elfish(userWord, n + 1);
}
else
{
System.out.println("Your word isn't elfish.");
} // end if-else else
} // end elfish method
}// end class
I'm pretty sure it's because you don't terminate your recursion properly. In order to check the n+1 character, the current n has to be n-2 or the value of n+1 is going to be out of range. That's because charAt() is limited to at most n-1.
So you want to make sure that n is less than n-1 before you pass it.
else if (n < userWord.length()-1) {
elfish(userWord, n + 1);
Replace n < userWord.length() with n < userWord.length()-1
Why? If input word has 3 letters, the last index you can access of it is 2. But the length() method returs the number of lettets that string contains, and it cointains 3 letters.
So 2 < 3 == true and program calls the eflish function with n=3, and it throws Index Out Bounds Exception.

How do I fix my java method to correctly iterate through string?

I need some major help.
My assignment is to recognize a lowercase string and return a true or false statement despite the presence of other characters or words. So far, I'm able to recognize the string in all lowercase, but my code still returns a TRUE value if the word is all uppercase; I only want it to recognize the lowercase values.
The assignment:
Write a program that takes in a string line and prints true if letters of my name (“john”) have appeared in the string in the same order, all in lowercase. Please note that there might be other characters between the letters of my name.
Here's my code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
boolean output = Check();
if (output == true) {
System.out.println("true");
}
else if (output == false) {
System.out.println("false");
}
}
public static boolean Check() {
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
String word = "john";
for (int i = 0; i < word.length(); i++) {
if (random.contains(word.substring((i)))) {
return true;
}
}
if (random.contains("JOHN")) {
return false;
}
return false;
}
}
Any help would be great thanks.
Some sample outputs:
Sample Input 1:
hello John
Sample Output 1:
false
Sample Input 2:
j123o23h56n
Sample Output 2:
true
Sample Input 3:
joh'n
Sample Output 3:
true
Sample Input 4:
ho0jn
Sample Output 4:
false
Sample Input 5:
J2j##oh123$NNNnn
Sample Output 5:
true
You need to write a logic where you pick each char from "john" string and compare it in order whether all of them occurred in that order or not. The moment it finds all the characters are found in the input string, it immediately return true without the need to further scan the input string. You may write something like this,
public static boolean Check() {
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
String word = "john";
sc.close();
int findIndex = 0;
char findChar = word.charAt(findIndex);
for (char c : random.toCharArray()) {
if (findChar == c) {
findIndex++;
if (findIndex == word.length()) {
return true;
}
findChar = word.charAt(findIndex);
}
}
return false;
}
You can simply do this (I didn't understand your condition for uppercase though; this Check method can find whether j,o,h,n appear in the string in the proper order),
public static boolean Check(){
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
HashMap<String, Boolean> map =new HashMap<String, Boolean>();
for(int i=0;i<random.length();i++){
if(map.size() == 0){
//find j
if(random.charAt(i) == 'j'){
map.put("j", true);
}
}else if(map.containsKey("j") && map.size() == 1){
//find o
if(random.charAt(i) == 'o'){
map.put("o", true);
}
}else if(map.containsKey("o")&& map.size() == 2){
//find h
if(random.charAt(i) == 'h'){
map.put("h", true);
}
}else if(map.containsKey("h")&& map.size() == 3){
//find n
if(random.charAt(i) == 'n'){
map.put("n", true);
}
}
}
return map.size() == 4;
}
Alternatively, you can use a stack to solve this too,
public static boolean Check(){
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
ArrayDeque<Character> stack = new ArrayDeque<Character>();
stack.push('n');
stack.push('h');
stack.push('o');
stack.push('j');
for(int i=0;i<random.length();i++){
if(random.charAt(i) == stack.peek()){
stack.pop();
}
if(stack.size() == 0){
return true;
}
}
return false;
}

Check if the input number is in a valid binary format

i tried to make a simple program,which check if the input number from the user is a binary number and that number is in correct binary format -> without leading zeros. That below is my code,but it doesn't work. I would appreciate if someone could help.
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
num = sl.nextInt();
int firstDigit = Integer.parseInt(Integer.toString(num).substring(0, 1));// i want to get the first digit from the input
if (firstDigit>0||firstDigit==1 ){
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
} else System.out.printf("WARNING: The number starts with 0");
}
}
There are a better solution, you can check if your input contain only 0 and 1 and the input great then 0 then valide number, so instead you can use String for example :
String num;
Scanner sl = new Scanner(System.in);
num = sl.next();
if (num.matches("[01]+") && !num.startsWith("0")) {
System.out.println("Correct number :" + num);
}else{
System.out.println("Not Correct number!");
}
num.matches("[01]+") will check if your input contain only 0 and 1.
!num.startsWith("0") this to answer this part without leading zeros
Test:
10010 -> Correct number :10010
00001 -> Not Correct number!
11101 -> Correct number :01101
98888 -> Not Correct number!
You can try something like this:
public static void main(String args[]) {
boolean binary=true; // boolean for final decision
String input;
int counter=0; // to count how many leading zeros there are in the input
int target = 5; // specify how many leading zeros allowed!!
Scanner in = new Scanner(System.in);
input = in.nextLine(); // take the entire line as a String
//first loop through the whole input to check for any illegal entry (i.e. non digits)
for(char digit : input.toCharArray()){
if(!Character.isDigit(digit)){ // catch any non-digit !
System.out.println("Illegal Input Found!"); // inform user and exit
System.exit(0);
}
if(digit!='0' && digit!='1'){ // check if it's not 1 and not 0
binary = false;
}
}
// now if there are no illegal inputs, check if it starts with leading zeros
if(input.charAt(0)=='0'){ // potential leading zeros, check the rest
while(input.charAt(counter)=='0'){ // while there are followed zeros
counter++;
if(counter>target && binary){ // leading zeros only in case it's a binary
System.out.println("Illegal Leading Zeros!");
System.exit(0);
}
}
}
// now if your program reach this point that means the input is valid and doesn't contain leading zeros in case it's a binary
if(binary){
System.out.println("It is a binary number");
}
else{
System.out.println("It is NOT a binary number");
}
}
Test:
01010101 -> It is a binary number
01010105 -> It is NOT a binary number
0000001 -> Illegal Leading Zeros!
0000005 -> It is NOT a binary number
000000A -> Illegal Input Found!
Why not simply use the standard library methods?
static boolean isValidBinary(final int input) {
final String binary = String.valueOf(input);
return binary.replaceAll("[01]", "").isEmpty() && !binary.startsWith("0");
}
you should not use sl.nextInt(); it will transfer '011' to 11, so when user input '011', the variable 'num' get the int value 11.
You should simply use sl.next() to get the input of user.
I think you need to check your "if" condition before the while, because you don't want that the number starts with 0, right? so... just ask for it, I have tryied and worded fine to me:
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
String input = sl.next();
num = Integer.parseInt(input);
String firstDigit = (input.length() > 0 ? input.substring(0, 1) : "" );
if (firstDigit.equals("0")) {
System.out.printf("WARNING: The number starts with 0");
} else {
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
}
}
}
The rest of your code Fulfills its mission! It tells you if the number is binary or not, and now plus tells you if your code begins with useless zeros
import java.util.*;
public class BinaryTest {
public static void main(String [] args){
Scanner input=new Scanner(System.in);
int count=0;
boolean check=true;
System.out.print("Enter a number: ");
int num=input.nextInt();
for(int i=0; i<=num; i++){
count=num%10;
if(count>1) {
check=false;
break;
}
else {
check=true;
}
num=num/10;
}
if(check)
System.out.println("Binary");
else
System.out.println("Not Binary");
}
}

Java: checking if a phone number fits a valid format

I am trying to find if a phone number fits the format (xxx)xxx-xxxx where x is a digit. First, I have the program for the length and the '(',')', and '-'. When I type in something that doesn't work, I get the logical output. However, when I type in a properly formatted number, my program doesn't return anything.
import java.util.Scanner;
public class Program04 {
public static void main(String args[])
{
Scanner stdIn = new Scanner(System.in);
String pN;
System.out.print("Please enter a phone number (ddd)ddd-dddd :");
pN = stdIn.nextLine();
char a = pN.charAt(1);
char b = pN.charAt(2);
char c = pN.charAt(3);
char d = pN.charAt(5);
char e = pN.charAt(6);
char f = pN.charAt(7);
char g = pN.charAt(9);
char h = pN.charAt(10);
char i = pN.charAt(11);
char j = pN.charAt(12);
if (pN.length() == 13 && pN.charAt(0)=='(' && pN.charAt(4)== ')' && pN.charAt(8)=='-')
{
if (a>=0 && a<=9)
{
if (b>=0 && b<=9)
{
if (c>=0 && c<=9)
{
if (d>=0 && d<=9)
{
if (e>=0 && e<=9)
{
if (f>=0 && f<=9)
{
if (g>=0 && g<=9)
{
if (h>=0 && h<=9)
{
if (i>=0 && i<=9)
{
if (j>=0 && j<=9)
{
System.out.print("This is a valid phone number!");
}
}
}
}
}
}
}
}
}
}
}
else System.out.println("Not a vaid phone number.");
}
}
It's easier to use pattern-matching (regex) for validation:
...
pN = stdIn.nextLine();
System.out.println(pN.matches("\\(\\d{3}\\)\\d{3}-\\d{4}"));
Even if you want to have it check if each character is a digit, using so many nested if's is not the way to go. Instead, define a simple method that applies the check, say:
private static boolean isDigit(char x) {
return x>=0 && x<=9;
}
and then do:
if ( isDigit(a) && isDigit(b) && ...) {
return true;
}
else {
return false;
}
If you're not allowed to use RegEx or if it is too difficult to understand, try simplifying your nested if's by a simple switch inside a loop, it is much more readable and maintenance is the easiest :
public static void main(String[] args) {
String pn = scan.nextLine();
boolean valid = true;
if (pn.length() == 13){
for (int i = 0 ; i < 13 ; i++){
switch(i){
case 0 : valid = pn.charAt(0) == '(';break;
case 4 : valid = pn.charAt(4) == ')';break;
case 8 : valid = pn.charAt(8) == '-';break;
default : valid = Character.getNumericValue(pn.charAt(i)) >= 0 && Character.getNumericValue(pn.charAt(i))<= 9 ; break;
}
if (!valid) break;
}
if (!valid) System.out.println("Invalid number");
}else{
valid = false;
System.out.println("Invalid length");
}
if (valid){
System.out.println(pn + " is a valid telephone number");
}
}
Also, to avoid working with the ASCII value of a char, try using the Character.getNumericValue(Char c) method. It returns a numeric that you can use for your tests, like above.
It is better to use regex in this case:
You can use following :
String pattern = "(\\(\\d{3}\\)\\d{3}-\\d{4})";
Pattern r = Pattern.compile(pattern);
pN = stdIn.nextLine();
Matcher m = r.matcher(pN);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}

How to recognize an input of numbers and letters

I've fixed my code so that it recognizes if their's 4 digits and less or 6 digits and higher but now I want to know whether or not it contains letters within the numbers.
The code below detects the letters and prints the line I want only when I input 5 letters, and I want it to detect even if their's more digits than letters or more letters than digits.
String digit;
String regex;
String regex1;
regex = "[0-9]{5}";
regex1 = "^[a-zA-Z0-9]{5}";
String test;
String validLength= "5";
char one, two, three, four, five;
{
System.out.println("In this game, you will have to input 5 digits.");
do
{
System.out.println("Please input 5-digits.");
digit = console.next();
test = digit.replaceAll("[a-zA-Z]", "");
if (digit.matches(regex))
{
one = (char)digit.charAt(0);
two = (char)digit.charAt(1);
three = (char)digit.charAt(2);
four = (char)digit.charAt(3);
five = (char)digit.charAt(4);
System.out.println((one + two + three + four + five) / 2 );
}
else if (test.length() > 5 || test.length() < 5)
{
System.out.println("You have letters in there.");
}
else if (digit.matches(regex1))
{
test = digit.replaceAll("[a-zA-Z]", "");
System.out.println("You have letters in there.");
}
else
if (digit.length() < 5)
{
System.out.println("You don't have enough digits.");
}
else if (digit.length() > 5)
{
System.out.println("You have to many digits.");
}
} while (!digit.matches(regex));
I won't go into regex here because honestly I think there is some misunderstandings that should be dealt with far before the road of niceties is undergone; plus, I'm no expert and I personally think they are more like rights of passage.
Anyway, let's start from the beginning, or at least when you determine they've entered a valid digit,
if (digit.matches(regex)).
Let's say...
String digits = "12345";
System.out.println(getSum(digits) / 2);
where...
public int getSum(String digits) {
int sum = 0;
for(int i = sum; i < digits.length(); i++) {
sum += digits.charAt(i);
}
return sum;
}
Same as your System.out.println((one + two + three + four + five) / 2 );.
I hope the output of 127 makes you smile.
Going out on a limb, and since you didn't speak of the "char" value sum that, you expected it to treat your chars as decimal digits. Well, that would result in 7. I only guess because of the whole (char)charAt() thing. This -> (char)charAt() sort of shows a lack of understanding that would make the use of regex highly questionable, IMHO of course.
Beyond that else if (test.length() > 5 && test.length() < 5). This says, "if test's length is greater AND less than 5"! Without using some mathematical paradox, tell me that number.
So, on to your question -
but now i want to know whether or not it contains letters within the
numbers.
well let's look at how finding out if any non-digit exists might be done - without regex so we can understand it...
public boolean containsNonDigits(String digits) {
for(int i = 0; i < digits.length(); ++i) {
if(Character.isDigit(digits.charAt(i))) {
continue;
} else {
return true;
}
}
return false;
}
This says, "if the character is a digit keep going; everything's fine, otherwise false".
The other "question" -
i want it to detect even if their's more digits than letters or more
letters than digits.
is an "additive" to the method above so I'll leave that one to you.
You can use Charachter.isDigit(char) and Charachter.isLetter(char) methods.
Here code sample that implements what you asked:
public static void main(String[] args)
{
System.out.println("In this game, you will have to input 5 digits.");
int validLength = 5;
boolean valid = false;
Scanner console = new Scanner(System.in);
while (!valid)
{
System.out.println("Please input 5-digits.");
String digit = console.next();
if (digit.length() != validLength)
{
//if length not valid, mark as not valid and return to next iteration
valid = false;
String message = digit.length() < validLength ? "You don't have enoght digits." : "You have to many digits.";
System.out.println(message);
continue;
}
//here digit.length = 5
int nDigits = 0,nLetters = 0,sum = 0;
for (int i = 0; i < digit.length(); i++)
{
Character ch = digit.charAt(i);
if (Character.isDigit(ch))
{
nDigits++;
sum += Integer.parseInt(ch.toString());
}
else if (Character.isLetter(ch)) {
nLetters++;
}
}
if (nLetters == 0 /* no letters */
|| /* and */
nDigits == validLength /* all chars are digits */)
{
System.out.println(sum/2);
valid = true;
}
else{
System.out.println("You have letters in there.");
}
}
}

Categories