简体   繁体   中英

Testing For Two Pairs In a Given String

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!");

    }

}

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

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.

如果使用数字,则应将它们存储为int,double等。我建议您在构造函数中进行此操作,之后,您可以轻松地检查前两个数字是否为对,对后两个数字也是如此。

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:

  1. Split the string by using the space ' ' as delimiter Hint: look at the documentation for String.split()

  2. 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

  3. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM