I have to make an array of 10 numbers then copy that array into a new array without the duplicates. I got it to the point where it will weed out dups but for some reason after I determine that a number is not already in the new array it wont let me put it in there. This is what I have so far. Thanks.
import java.util.*;
import java.io.*;
public class PrintingDistinctNumbers
{
public static void main(String[] args)
{
int[] array=new int[10];
int[] array2=new int[10];
int num1;
int count = 0;
boolean results;
//let the user input 10 numbers
for(int i=0;i<array.length;i++)
{
Scanner input=new Scanner(System.in);
System.out.println("please enter 10 numbers");
num1=input.nextInt();
array[i]=num1;
}
for (int j=0;j<array.length;j++)
{
results=search(array2 ,array[j],count);
if(results=false);
{
array[j]=array2[count];
count++;
break;
}
}
// just a test to make sure the numbers copied over to the new array
System.out.println(array2[0]);
}
//search the second array to see if the int is allready in it
public static boolean search(int[] array2,int value,int count2)
{
//create variables
boolean found;
//set the variables
found= false;
//search the array
for(int index=0;index<count2;index++)
{
if(array2[index]==value)
{
found=true;
break;
}
}
return found;
}
}
Without looking at the rest of your logic, this
if(results=false);
doesn't look right
is that a typo ? You need if (results == false), or more concisely, if (!results)
note the trailing semicolon, which means the following block will execute regardless of what your if clause evaluates to. The ; is creating an empty block, which is entierely valid.
Besides if (results=false) already mentioned by Brian Agnew, I see this:
array[j]=array2[count];
You overwrite the values in the array, in which you stored your input with the values of an uninitialized second array. You probably meant to do
array2[count] = array[j];
here.
There are two bugs:
The break; statement in the if block should not be there: That would break you out of the loop, but you need the loop to keep iterating over the array until all the elements have been copied.
The test is assigning false to result, not comparing it, so change to if (!result)
There are a few style issues too:
Your search method is waaaay to long; you don't need the found variable
Name your parameters with what makes sense within the method: you have array2 when there's no array or array1 in scope. Same for count2
Prefer i to index for the loop var - it's just less to type and less to read
This is more like what it should look like:
public static boolean search(int[] array, int value, int count) {
for(int i = 0; i < count; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
In your main method, why do you have one loop with i and the next with j? Make them both i - the loop variable only has scope within the loop, so there's no clash.
Related
Why is this insertion sort giving me the wrong answer, whereas i'm getting the right answer when I do it the way the comment lines specify?What is the difference?
public class Solution
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int i,j,n,sk=0; //consider another variable k
int a[]=new int[20];
n=s.nextInt();
for(i=0;i<n;i++)
a[i]=s.nextInt();
for(i=1;i<n;i++)
{ j=i-1;
//adding k=a[i]
while((j>=0)&&a[j]>a[i]) //a[j]>k instead of the condition a[j]>a[i]
{ sk++;
a[j+1]=a[j];
j--;
}
a[j+1]=a[i];
//a[j+1]=k instead of the previous line.
}
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}
this line a[j+1]=a[j];
Consider the array = {5,2,3} when i = 1, j = 0,
while((j>=0)&&a[j]>a[i]) //a[j]>k instead of the condition a[j]>a[i]
{ sk++;
a[j+1]=a[j]; // a[1] = a[0]
j--; // j becomes -1 out of the loop
}
// Array becomes {5,5,3} after while loop, we lost 2
a[j+1]=a[i]; // again a[0] is just getting initialized to a[1]
//which are same
//a[j+1]=k instead of the previous line. **// K will have previous
a[1]**
}
You already updated a[1] when you did a[j+1]=a[j] and then outside the while loop you are again assigning a[1] = a[1], however, k will store previous a[1] value, not the updated one
To make it simple, in your solution, you are editing your variables by reference whereas the correct solution is to pass them by value.
When you pass your variables by reference, editing one value would be the same as editing the second.
Here is a simple code which should help you to understand:
public class Main {
public static void main(String[] args) {
Foo foo = new Foo();
int valueToAdd = 5;
// foo.a will not be modified because we set the parameter by value
editTestByValue(foo.a, valueToAdd);
System.out.println(foo.a); // prints 1
editTestByReference(foo, valueToAdd);
// foo.a will be modified because we set the parameter by reference
System.out.println(foo.a); // prints 6
}
public static void editTestByValue(int a, int valueToAdd){
a += valueToAdd;
}
public static void editTestByReference(Foo foo, int valueToAdd){
foo.a += valueToAdd;
}
}
class Foo {
public int a = 1;
}
You use the same thing by using an array instead of a class.
For more information, you can check this
What's the difference between passing by reference vs. passing by value?
Hope it helped !
Edit: Uh well now that I pasted code into here and looked at it.. I have 2 .. "duplicate methods" .. Eclipse for some god awful reason hid the first "boolean checkforDupes()" from me. It seems to be fixed now, still poking it to make sure, should I just like.. delete the post or something?
I have a class assignment, which I've done essentially everything for, but I'm having issues with generating some random numbers to put into an array, and if they number has already been "drawn" then the number is re-generated so that there are no duplicates.
I've looked through several articles and have seen various ways to accomplish what I'm trying to do, but I'm really just trying to locate the flaw in my method/reasoning/etc.
(Pulling numbers from a fully populated array randomly, or shuffling an array and picking a handful, using a Set for unique numbers etc)
Essentially the program is just supposed to generate 5 lotto numbers, player(or computer player in this case) also selects 5 numbers. Each number set is to be unique, and then you compare the Array/List/whatever and pull out matches for assumed points or notoriety.
Somewhere between my generateNumbers() and checkForDupes() methods my logic has failed me and I've been stumped for a few hours. Sometimes the generator works and recognizes that it has rolled a duplicate and will reroll, but other times it will say reroll the first number but numbers 3 & 4 are duplicates which it ignores.
Any insight into this would be much appreciated.
package lottery;
import java.util.*;
public class Lottery {
final int chance = 5; //holds the number of lottery numbers to be picked
private int lotteryNumbers[] = new int[chance]; //array to hold the lottery numbers
private int playerNumbers[] = new int[chance]; //array to hold player's numbers
//Maybe rewrite with a Set instead of Array.
//Or generate random numbers and put them in array and "draw" lotto numbers from the array. Well now that I'm looking at my post, this comment is more of my I give up, next step stuff !
public Lottery(){
generateNumbers(lotteryNumbers);
System.out.println("Lottery numbers");
generateNumbers(playerNumbers);
System.out.println("Player numbers");
}
public String returnDate(){
Date date = new Date();
// display time and date using toString()
return date.toString();
}
public int[] getLotteryNumbers() {
return lotteryNumbers;
}
public int[] getPlayerNumbers() {
return playerNumbers;
}
private int[] generateNumbers(int[] numbers){
int check;//variable to pass for checking dupes
int count = 0;
Boolean DoIt=null;
Random rng = new Random(); //Used to pick lottery numbers
while (count<chance)
{
check = rng.nextInt(5)+1;//assigns random number to check
DoIt = checkforDupes(check, numbers);//passes check and the array to be checked for dupes
if (DoIt == true) //to execute if dupe checker says its ok
{
numbers[count] = check;
System.out.print(numbers[count]+" in ["+count+"], ");
count++;
}
else //supposed to restart the loop without incrementing for a new number if dupe
{
System.out.println(" Dupe rerolling "+check+" ["+count+"], ");
}
}
return numbers;
}
private boolean checkforDupes(int check, int[] array){
//pass in the generated variable and the array, check array if duplicates then return true or false to add the number
for(int i=0; i<chance; i++)
if (check == array[i])
return false;
else
return true;
return false;
}
private Boolean checkForDupes(int check, int[] array){
Boolean doIt = false;
for (int i=0; i<array.length; i++)
{
if (check == array[i])
{
doIt = false;
System.out.println("DON'T!"); //not printing anything to console
break;
}
else
doIt = true;
}
System.out.println("Am I even being called"); //also not printing to console...
return doIt;
}
public void checkMatches(int[] array1, int[] array2){
for (int index = 0; index<array1.length; index++)
if (array1[index] == array2[index])
System.out.print(array1[index]+" ");
System.out.println();
System.out.println("**** Possible Matches listed above ****");
}
}
if (check == array[i])
return false;
else
return true;
This is in a for loop, so it runs once for each array element (with i being the index of that element).
If check equals this array element, you return false. Otherwise, you return true.
And it never gets to go around the loop again, because returning exits the method immediately.
Here i have implemented with c# you can convert it into java if needed. I have used dictionary for faster searching.
Here is the code, You can modify it accordingly:
static Dictionary<int, int> randomNoArray = new Dictionary<int, int>();
static int[] arrayHavingManyNo= new int[] { 3, 4, 5,........... };
static void Main(string[] args)
{
while (true)
{
int randomNo = 0;
Console.WriteLine("press 1 to generate random and insert.");
Console.WriteLine("Press 2 to display No in Array");
if (Console.Read() == 1)
{
randomNo = GenerateRandom(1, 100);
if (!checkInArray(randomNo))
{
InsertInArray(Full[randomNo], Full[randomNo]);
}
}
else
{
foreach (KeyValuePair<int, int> pair in randomNoArray)
{
Console.WriteLine(pair.Value);
}
}
}
}
static int GenerateRandom(int start,int end)
{
return Convert.ToInt32(new Random().Next(start, end));
}
static bool checkInArray(int no)
{
return (randomNoArray.ContainsKey(Full[no]));
}
static void InsertInArray(int key , int value)
{
randomNoArray.Add(key,value);
}
}
I'm doing a program where user input five numbers and in the end the numbers are printed out which is working fine. What I can't get to work is a boolean function to check for duplicates. It should check for duplicates as the user write them in, so e.g. if number one is 5 and the second numbers is also 5, you should get an error until you write in a different number. Meaning if the user input a duplicate it should NOT be saved in the array. This is obviously an assignment, so I'm just asking for a hint or two.
This program is written based on pseudo-code given to me, and therefore I have to use a boolean to check for duplicates with the public boolean duplicate( int number ) class.
I've tried getting my head around it and tried something by myself, but obviously I'm doing a stupid mistake. E.g.:
if(int i != 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 i = 0; i < amount; i++ ) {
int input = Integer.parseInt(JOptionPane.showInputDialog("Input 5 numbers"));
myNumbers[i] = input;
}
}
public boolean duplicate( int number ) {
<BOOLEAN TO CHECK FOR DUPLICATES, RETURN FALSE OR TRUE>
}
public void printInputNumbers() {
JTextArea output = new JTextArea();
output.setText("Your numbers are:" + "\n");
for(int i = 0; i < 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 the code tag is messy, I had some trouble with white fields in between and such. I'm new here.
Don't store the numbers in an array. Use a Set<Integer> instead. And then do a Set#contains() operation. It's O(1) operation which is actually far better than iterating over the array to search for duplicates.
Ok, if it's a compulsion to use an array, then you should modify your current approach, to return true as soon as you find a duplicate, instead of iterating over the array again. In your current approach, since you are setting the boolean variable to false in the else block, your method will return false if the last element of the array is not the same as what you are checking. So, just modify your approach to:
// loop over the array
if (number == myNumbers[i])
return true;
// outside the loop, if you reach, return false
return false;
Note that your current if statement will not compile. You are declaring an int variable there, which you can't do.
if (int i == myNumbers[i]) // this is not a valid Java code.
int nums[] = new int[5];
int count = 0;
public boolean duplicate(int number)
{
boolean isDup = false;
for (int i = 0; i <= count; i++)
{
if (number == nums[i])
{
isDup = true;
break;
}
}
if (!isDup)
{
count++;
nums[count] = number;
}
return isDup;
}
I am trying to use the summer to practice more Java to get better by learning how to code algorithms. I have this problem where I add elements to my ArrayList but somehow the first number I add also sets the number of positions in my list which I want to avoid. I only want the 0th index to contain the number 5. I seem to not catch a clue on how to solve this.
public class Algorithms {
private ArrayList<Integer> numbers;
public Algorithms() {
numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(4);
bubblesort();
}
public static void main(String args[]) {
new Algorithms();
}
public void bubblesort() {
System.out.println(numbers);
for (int a = 0; a < numbers.size();) {
for (int b = 1; b < numbers.size();) {
int currentNumber = numbers.get(a);
if (currentNumber > numbers.get(b)) {
//Collections.swap(numbers, currentNumber, numbers.get(b));
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
a++;
b++;
} else if (currentNumber < numbers.get(b)) {
a++;
b++;
}
System.out.println(numbers);
}
}
}
}
You are not swapping elements correctly. Instead of
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
it should be
int temp = numbers.get(a);
numbers.set(a, numbers.get(b));
numbers.set(b, temp);
The below two statements:
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
is not performing swapping. The first argument to the List#set(int, E) method is the index in the list, where you want to set the value passed as 2nd argument. You need to use a temp variable for swapping.
Also, the swapping didn't work for your commented line for the same reason. Collections#swap method take indices for swapping. So, just change:
Collections.swap(numbers, currentNumber, numbers.get(b));
to:
Collections.swap(numbers, a, b);
And please for the love of all that is holy, don't call method from inside a constructor. Remove the method invocation from inside the constructor, and move it to main method like this:
Algorithms algo = new Algorithms();
algo.bubbleSort()
public class ApiClass{
//The below method prints only the user entered values
public void printArray(int[] a){
for(int element : a){
//ignore because this is the default value when array is created not user entered
if(element != 0)
{
System.out.print(element+"\t");
}
}
}
}
public class Client{
public static void main(String... args){
ApiClass api = new ApiClass();
int[] input = new int[5];
input[0]= 3;
input[2]= 2;
input[3] = 1;
api.printArray(input);
}
}
This is working fine but failing for the 3,2,0 or 0,0,0 or 3,0,1 any input user enters with zero
default value for primitive int type is 0 so the uninitilized elements in array will hold 0 value,
now if you check if element is not 0 then print and if you give input 3,2,0 then it will skip 0
Better to use List
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(0);
numbers.add(3);
and now iterate the numbers
for(Integer num: numbers){
//print num, no need to check for `0` any more
}
That is not a good approach. If you have three user entries, you should make an array of length three (and not one of length five with two trailing un-used entries). There is no way to distinguish between the "default" 0 and a 0 assigned later.
Another option would be to use an Integer[], where the "default" is null, not 0 (but then you cannot distinguish between the "default" null and a null assigned later).
If you don't know the length of the array in advance, use a List<Integer> instead.
Satya:
If your problem is simply to distuingish the default 0-values from user-entered 0-values, why dont you initialize the array with a value that you know a user can never enter? (You need to make sure that this is the case).
One way is to iterate the array before and initialize, another one is to use
Arrays.fill()
Your for loop is wrong.
Should be
for(int element: a) {
if(element !=0){
System.out.println(element + "\t");
}
}
Your initial implementation never incremented the value of i.
Try with this one:
public void printArray(Integer[] a){
for(Integer element : a){
//Ignore because this is the default value when array is created not user entered
if (element != null) {
System.out.print(element.toString() + "\t");
}
}
}
public class Client{
public static void main(String... args){
ApiClass api = new ApiClass();
Integer[] input = new Integer[5];
input[0]= 3;
input[2]= 2;
input[3] = 1;
api.printArray(input);
}
}