java - Check duplicates of numbers input by user -
i'm doing program user input 5 numbers , in end numbers printed out working fine. can't work boolean function check duplicates. should check duplicates user write them in, e.g. if number 1 5 , second numbers 5, should error until write in different number. meaning if user input duplicate should not saved in array. assignment, i'm asking hint or two.
this program written based on pseudo-code given me, , therefore have use boolean check duplicates public boolean duplicate( int number )
class.
i've tried getting head around , tried myself, i'm doing stupid mistake. e.g.:
if(int != mynumbers[i]) checkduplicates = false else checkduplicates = true; return checkduplicates;
duplicatestest class:
public class duplicatestest { public final static int amount = 5; public static void main(string[] args) { duplicates d = new duplicates(amount); d.inputnumber(); d.duplicate(amount); d.printinputnumbers(); } }
duplicates class:
public class duplicates { private int amount; private int[] mynumbers; private boolean checkduplicates; public duplicates(int a) { amount = a; mynumbers = new int[amount]; } public void inputnumber() { for(int = 0; < amount; i++ ) { int input = integer.parseint(joptionpane.showinputdialog("input 5 numbers")); mynumbers[i] = input; } } public boolean duplicate( int number ) { <boolean check duplicates, return false or true> } public void printinputnumbers() { jtextarea output = new jtextarea(); output.settext("your numbers are:" + "\n"); for(int = 0; < mynumbers.length; i++) { if (i % 5 == 0) { output.append("\n"); } output.append(mynumbers[i] + "\t"); } joptionpane.showmessagedialog(null, output, "numbers", joptionpane.plain_message); } }
sorry if code tag messy, had trouble white fields in between , such. i'm new here.
don't store numbers in array. use set<integer>
instead. , set#contains()
operation. it's o(1)
operation far better iterating on array search duplicates.
ok, if it's compulsion use array, should modify current approach, return true
find duplicate, instead of iterating on array again. in current approach, since setting boolean
variable false
in else
block, method return false
if last element of array not same checking. so, modify approach to:
// loop on array if (number == mynumbers[i]) return true; // outside loop, if reach, return false return false;
note current if
statement not compile. declaring int
variable there, can't do.
if (int == mynumbers[i]) // not valid java code.
Comments
Post a Comment