Getting the final else statement to run Java recursive method - java

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.

Related

How do I get these conditions to apply properly in an if statement?

I am a student going into software engineering and am taking my first computer science class on coding with java. I'm struggling to get my program to apply a certain set of conditions to a String in order to print a message regarding whether or not a user's input is indeed a valid double literal.
Here are the conditions:
Consists of exactly the following characters: ’+’, ’-’, ’.’ (decimal point), and ’0’ through ’9’
Either the ’+’ or ’-’ character may appear only as the first character
The ’.’ (decimal point) character must appear exactly once
All other characters must be the ’0’ through ’9’ characters
And here is my code:
String doubleliteral;
int a;
char j;
char k;
char l;
char m;
char n;
System.out.print("Enter a valid four character double literal: ");
doubleliteral = keyboard.nextLine();
a = doubleliteral.length();
j = doubleliteral.charAt(0);
k = doubleliteral.charAt(1);
l = doubleliteral.charAt(2);
m = doubleliteral.charAt(3);
n = '.';
char i = (char)(a + 0);
if (i <= 4)
{
System.out.print("\n" + doubleliteral + " is a valid four character double literal.");
}
else if ((j == '+') || (j == '-') || (j <= 9))
{
}
else if ((k <= 9))
{
}
else if (l <=9)
{
}
else if (m <= 9)
{
}
else if ((j != '.') && (k != '.') && (l != '.') && (m != '.'))
{
System.out.print("\n" + doubleliteral + " is not a valid four character double literal.");
}
else
{
System.out.print("\n" + doubleliteral + " is not a valid four character double literal.");
}
keyboard.close();
I've been searching on the internet, in my textbook, and through my professor's presentations for about three days now trying to figure this out but nothing has come of it, please help.
Here is some psudo-code to get you in the right direction. I can't write your school answer here.
Loop through each character. Special case the first. Track if you have dot.
hasDot = false
for (i=0; i<input.length; i++) {
ch = input[i]
if (i === 0) {
validChars = [0,1,2,3,4,5,6,7,8,9,-,+,.]
// validChars must contain ch
// if ch === dot, set hasDot = true
}
else {
validChars = [0,1,2,3,4,5,6,7,8,9,.]
// validChars must contain ch
// if ch === dot and hasDot then error, else set hasDot = true
}
}
There are few conditions you need to check to figure out the validity. Let's see one by one.
+ Or -
There can be maximum one + or - operator and it has to be at the beginning of the given input.
So what you can do is, whenever you're getting a + or - operator, just check whether current index is 0 or not.
If it's not, then mark the input as invalid.
boolean isValid = true;
for(int i = 0; i < doubleliteral.length(); i++)
{
if((doubleliteral[i] == '+' || doubleliteral[i] == '-'))
{
if(i != 0)
{
isValid = false;
}
else
{
// it's valid.
}
}
}
The . (decimal point) character
There can be maximum one . character.
So you keep a count of it, check if it ever becomes more than 1.
boolean isValid = true;
int dotCounter = 0;
for(int i = 0; i < doubleliteral.length(); i++)
{
if( doubleliteral[i] == '.')
{
if(dotCounter != 0)
{
isValid = false;
}
else dotCounter++;
}
}
Check if there's any character other than digits (o to 9)
While traversing each character of the string, you can check if it's digit or not like following-
for(int i = 0; i < doubleliteral.length(); i++)
{
if(Character.isDigit(doubleliteral.charAt(i)))
{
// it's a digit
}
}
Now if we combine everything it'll look like this:
boolean isValid = true;
int dotCounter = 0;
int doubleliteralLength = doubleliteral.length();
for(int i = 0; i < doubleliteralLength; i++)
{
if((doubleliteral[i] == '+' || doubleliteral[i] == '-'))
{
if(i != 0)
{
isValid = false;
break; // we don't need to check any further
}
}
else if( doubleliteral[i] == '.')
{
if(dotCounter != 0)
{
isValid = false;
break;
}
else dotCounter++;
}
else if(Character.isDigit(doubleliteral.charAt(i)) != true)
{
// it's not a digit, not + or -, not .
isValid = false;
break;
}
}
if(doubleliteralLength == 4 && isValid)
{
System.out.print("\n" + doubleliteral + " is a valid four character double literal.");
}
else
{
System.out.print("\n" + doubleliteral + " is not a valid four character double literal.");
}
This question can be easily answered by using Regular Expressions and apply the expression to the inputted String object. Although this question is technically correct, it is not correct for the lesson your professor is teaching (which I am guessing is String parsing).
That said, here are my clues to you:
Symbols (+ or -) can only be present at character index 0.
The (decimal) ASCII values for numbers 0-9 are 48-57. Therefore, an ASCII
value outside this range that is not a "+", "-", or "." (43, 45, or
46 respectively) is an illegal character.
The next thing you need to do is write down a few combinations of characters and test them out manually. For example:
1.34 // invalid (first character must be the sign)
.123 // invalid (first character must be the sign)
-.98 // valid
-0.1 // valid
+2.3 // valid
2.+6 // invalid
4.3- // invalid
30-4 // invalid
+23. // valid (by your requirements, but it should not be)
+0.- // invalid
All of the above contain nothing but valid characters, but not all are correctly formatted. Once you test these out, you should try using other non-numeric characters.
Your code should be something like this (in psedocode)
IF STRING LENGTH > 4, ERROR (String has too many characters)
IF PERIOD COUNT > 1, ERROR // See * note
IF CHAR AT 0 NOT VALID, ERROR (Special case for symbols, period, or numbers)
IF CHAR AT X NOT VALID, ERROR (index 1-3 can only be numbers or the period)
IF CHAR AT 3 == ., ERROR (Last index cannot be the period)
PRINT STING MESSAGE
(*) My suggestion is to use a loop operation to count the number of times the period appears on the String. There are other ways to do this, but my guess is that they are not related to your current lesson. Some of those alternative methods are using regular expressions, using Streams API, using recursion, or using 3rd party libraries. Stay away from any of those solutions.
If all the tests passed, then the only thing that will be printed out will be the message containing the valid numeric string.
Last hint: Do all of the CHAR AT evaluations in a single pass (i.e. loop through your String (array of characters) to determine if the character at any given position is valid. A multiple pass solution is OK, just not elegant or effective.
The solution
import java.util.Scanner;
public class NumericStringEvaluator {
public static void main (String[] args) {
System.out.print("Enter a valid four character double literal: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
scanner.close();
if (input.length() > 4) {
System.err.println("String must be exactly 4 characters");
System.exit(-1);
}
//1. Consists of exactly the following characters: ’+’, ’-’ ...
//2. Either the ’+’ or ’-’ character may appear only as the first character
if (input.charAt(0) != '+' && input.charAt(0) != '-') {
System.err.println("Invalid character at index 0: " + input.charAt(0));
System.exit(0);
}
int periodCount = 0;
for (int i = 1; i < 4; i++) {
char c = input.charAt(i);
//1. Consists of ... ’.’ ...
if (c == '.') {
periodCount++; //3. The ’.’ (decimal point) character must appear exactly once
}
// 1. Consists of ... and ’0’ through ’9’
// 4. All other characters must be the ’0’ through ’9’ characters
// ASCII values for number are 48-57 (anything outside the range is not a number)
// and the special characters have been accounted for already
else if (c < 48 || c > 57) {
System.err.println("Invalid character at index " + i + ": " + input.charAt(i));
System.exit(0);
}
}
// At this point, every character in the string has been validated (no errors found)
//3. The ’.’ (decimal point) character must appear exactly once
if (periodCount != 1) {
System.err.println("Decimal point appears more than once in numeric String.");
System.exit(0);
} else {
System.out.print("\n" + input + " is a valid four character double literal.");
}
}
}

Number identifying program

Very amateur coder here,
I'm in the process of making a simple program to tell whether a number is positive, negative, odd or even. So far everything works apart from positive odd numbers, but cant figure out why ?
Also, how would i loop it ? would i use a for or while loop ?
Thanks
package weekeleven;
import java.util.Scanner;
public class week111 {
static int number;
static String pE;
static String pO;
static String nE;
static String nO;
static String eR;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
number = -input.nextInt();
pE = ("Positive Even");
pO = ("Positive Odd");
nE = ("Negative Even");
nO = ("Negative Odd");
eR = ("Error");
Object x = null;
x=getSignAndParity(x);
System.out.println(x);
}
public static String getSignAndParity(Object x) {
if ((number > 0) && (number % 2 == 0)) { //negative and even
return nE;
} else if((number < 0) && (number % 2 == 1)) { // positive and odd
return pO;
} else if((number < 0) && (number % 2 == 0)) { // positive and even
return pE;
} else if((number > 0) && (number % 2 == 1)) { // negative and odd
return nO;
} else { // other cases
return eR;
}
}
}
There are multiple issues with your code causing it not to work as expected.
1) You are using mod 2 on negative numbers to check if a negative number is even or odd. But that will not work. For e.g., -7 mod 2 = -1 (which is neither 1 nor 0)
2) You are negating the user's input :
number = -input.nextInt();
and you flipped the signs >, < which is unnecessary
3) You should not be passing the int input as Object. You could just simply:
public static String getSignAndParity(int x)
Removing all the superfluous and unnecessary declarations and code, you can have this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
System.out.println(getSignAndParity(number));
}
public static String getSignAndParity(int num) {
if(num == 0)
return "Error";
String sign = num>0?"Positive":"Negative";
String parity = Math.abs(num)%2==0?"Even":"Odd";
return sign + " " + parity;
}
Change with this
else if((number > 0) && (number % 2 == 1)) { // positive and odd
return pO;
}
For positive odd numbers and for looping you need either existing the code or have a condition that is taken from scanner and then close the scanner.
scanner : https://www.javatpoint.com/Scanner-class
You have to change positive odd like this:
else if((number < 0) && (number % 2 == -1)) { // positive and odd}

Removing vowels from an input string using a loop

I need my output to only be 5 characters long NOT counting the removed vowels. Currently my code is counting the input length and returning that number minus the vowels. This might be confusing. If I input "idontthinkso" it only returns "dnt" instead of what I want it to print out which is "dntth". Btw, I'm not allowed to use Stringbuilder or anything like that, only a loop, so forgive the code. How can I fix this? Here is my code:
import java.util.Scanner;
public class TweetCompressor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int f = 0;
int tweetLengthAllowed = 5;
for (int i = 0; i < tweetLengthAllowed; i++) {
char c = input.charAt(i);
if (c == 'a' ||
c == 'e' ||
c == 'i' ||
c == 'o' ||
c == 'u' ||
c == 'A' ||
c == 'E' ||
c == 'I' ||
c == 'O' ||
c == 'U') {
f = 1;
} else {
s = s += c;
f = 0;
}
}
System.out.println(s);
}
}
I'm very much in favor of using a while loop for this, but since you stated you can only use a for loop...
The problem is that your loop will iterate until i = 5, even if a vowel is detected. We need a way to tell the loop to pretend that never happened. You can't decrement i, or you'll be stuck at the same character forever.
Here's what I came up with, I decided to simply increment the tweetLengthAllowed to negate the i increment.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int f = 0;
int tweetLengthAllowed = 5;
for(int i = 0; i < tweetLengthAllowed; ++i) { //Must be a for loop
char c = input.charAt(i);
if(c == 'a'|| c == 'e'|| c == 'i'|| c == 'o'|| c =='u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
f = 1;
tweetLengthAllowed++; //Allows the loop to continue for one more interation
} //end if
else{
s = s += c;
f = 0;
}//end else
} //end for
System.out.println(s);
} //end main
} //end class
Also, if you're going to use a big chain of ORs, please do yourself a favor and make it more readable as I did above.
You can do this simpler. Here I iterate every char in the input and break if it reaches the limit:
import java.util.Scanner;
public class TweetCompressor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int tweetLengthAllowed = 5;
int i = 0;
boolean isNotVowel;
boolean limitReached;
for (char c : input.toCharArray()) {
isNotVowel = "AEIOUaeiou".indexOf(c) == -1;
limitReached = tweetLengthAllowed <= i;
if (limitReached) { // exit the loop
break;
} else if (isNotVowel) { // append the char
s += c;
i++;
}
}
System.out.println(s);
}
}
Run output:
Type a tweet:
idontthinkso
dntth
Here is my way of doing it:-
import java.util.Scanner;
import java.lang.StringBuffer;
public class Program {
private static String RemoveVowel(String text)
{
int len = text.length();
char[]vowels = {'a','e','i','o','u','A','E','I','O','U'};
StringBuffer sb = new StringBuffer(text);
for(int i = 0;i<len;i++)
{
for(char v : vowels)
{
if(v == text.charAt(i))
{
sb.setCharAt(i,'\0');
}
}
}
return sb.toString();
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter some text to remove vowels from it: ");
String val = scan.nextLine();
System.out.println(RemoveVowel(val));
}
}
I have used string buffer to make the string modifiable and a "for" loop iterates through the length of the string, and one iterates through the "vowels" array; an "if" statement checks if the current character is equal to one of the vowels and if true, it sets the current character to null, which removes the vowel.
public class RemoveVowels {
public static void main(String[] args) {
String inputString = "Java - Object Oriented Programming Language";
System.out.println(inputString.replaceAll("[aeiouAEIOU]", " "));
}
}
Output:
J v - bj ct r nt d Pr gr mm ng L ng g

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

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

Categories