Java Novice:
I am using a for loop to iterate an array and check it's values.
For example: If the array contains the number 100. Then do something,
However if it doesn't then get the current value of the current variable.
Is it possible to get the value of the current variable when the check was made?
Currently, when I print using the else I get everything printed out.
Like this:
1
2
3
Found Something!
Please forgive my ignorance. Just experimenting:
public class MyArrayExample {
private int[] intArray = new int[] {1, 2, 3, 100};
public int[] getArrayValues() {
return intArray;
}
public static void main(String[] args)
{
MyArrayExample example = new MyArrayExample();
int[] arrayValues = example.getArrayValues();
for(int counter=0; counter<arrayValues.length; counter++) {
int current = arrayValues[counter];
if(current == 100)
{
System.out.println("Found Something!");
}
else{
System.out.println(current);
}
}
}
}
To get the value of current when the check was made, declare it outside the for loop in order to have the access to the variable value and add a boolean flag isFound:
int current = 0;
boolean isFound = false;
for(int counter=0; counter<arrayValues.length; counter++) {
current = arrayValues[counter];
if(current == 100)
{
isFound = true;
// do something
}
}
Then once the check is made you can get the value of current or print that found something:
if (isFound) {
System.out.println("Found Something!");
} else {
System.out.println("current: " + current);
}
Note. If the value you are looking for is not present in the array, current is always assigned with the last value in the array.
As an addition - you don't even have to write a loop yourself, you can just use existing array/collection methods, for example:
Integer[] intArray = new Integer[] {1, 2, 3, 100};
List<Integer> myList = Arrays.asList(intArray);
System.out.println(myList.contains(100)); // checks if 100 exists in your array
System.out.println(myList.indexOf(100)); // shows the position of the element 100
Related
So I have this code:
public class SortedIntList extends IntList
{
private int[] newlist;
public SortedIntList(int size)
{
super(size);
newlist = new int[size];
}
public void add(int value)
{
for(int i = 0; i < list.length; i++)
{
int count = 0,
current = list[i];
if(current < value)
{
newlist[count] = current;
count++;
}
else
{
newlist[count] = value;
count++;
}
}
}
}
Yet, when I run the test, nothing prints out. I have the system.out.print in another class in the same source.
Where am I going wrong?
EDIT: Print code from comment:
public class ListTest
{
public static void main(String[] args)
{
SortedIntList myList = new SortedIntList(10);
myList.add(100);
myList.add(50);
myList.add(200);
myList.add(25);
System.out.println(myList);
}
}
EDIT2: Superclass from comment below
public class IntList
{
protected int[] list;
protected int numElements = 0;
public IntList(int size)
{
list = new int[size];
}
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else {
list[numElements] = value; numElements++;
}
}
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}
Let's walk through the logic of how you want it to work here:
first you make a new sorted list passing 10 to the constructor, which make an integer array of size 10.
now you call your add method passing 100 into it. the method sets position 0 to 100
now you add 50, the method sets 50 in position 0 and 100 in position 1
now you add 200, which gets placed at position 2
and you add 25. which gets set to position 0, and everything else gets shuffled on down
then your method will print out everything in this list.
So here are your problems:
For the first add, you compare current, which is initialized at 0, to 50. 0 will always be less than 50, so 50 never gets set into the array. This is true for all elements.
EDIT: Seeing the super class this is how you should look to fix your code:
public class SortedIntList extends IntList
{
private int[] newlist;
private int listSize;
public SortedIntList(int size)
{
super(size);
// I removed the newList bit becuase the superclass has a list we are using
listSize = 0; // this keeps track of the number of elements in the list
}
public void add(int value)
{
int placeholder;
if (listSize == 0)
{
list[0] = value; // sets first element eqal to the value
listSize++; // incriments the size, since we added a value
return; // breaks out of the method
}
for(int i = 0; i < listSize; i++)
{
if (list[i] > value) // checks if the current place is greater than value
{
placeholder = list[i]; // these three lines swap the value with the value in the array, and then sets up a comparison to continue
list[i] = value;
value = placeholder;
}
}
list[i] = value; // we are done checking the existing array, so the remaining value gets added to the end
listSize++; // we added an element so this needs to increase;
}
public String toString()
{
String returnString = "";
for (int i=0; i<listSize; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}
Now that I see the superclass, the reason why it never prints anything is clear. numElements is always zero. You never increment it because you never call the superclass version of the add method.
This means that the loop in the toString method is not iterated at all, and toString always just returns empty string.
Note
This is superseded by my later answer. I have left it here, rather than deleting it, in case the information in it is useful to you.
Two problems.
(1) You define list in the superclass, and presumably that's what you print out; but you add elements to newList, which is a different field.
(2) You only add as many elements to your new list as there are in your old list. So you'll always have one element too few. In particular, when you first try to add an element, your list has zero elements both before and after the add.
You should probably have just a single list, not two of them. Also, you should break that for loop into two separate loops - one loop to add the elements before the value that you're inserting, and a second loop to add the elements after it.
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 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.
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);
}
}