My assignment is to create a method that returns true if my set of integers has an un-even number in it. My problem is that even if I have un-even numbers in my set, it will return false. Where am i making a mistake?
import java.util.*;
public class Chapter_11_E9
{
public static boolean odd;
public static boolean hasOdd(Set<Integer> tSet1)
{
Iterator<Integer> itr = tSet1.iterator();
while (itr.hasNext())
{
int current = itr.next();
if ((current / 2) == 1)
{
odd = true;
}
else
{
odd = false;
}
}
return odd;
}
public static void main(String[] args)
{
Set<Integer> tSet1 = new HashSet<Integer>();
tSet1.add(6);
tSet1.add(2);
tSet1.add(5);
tSet1.add(4);
tSet1.add(12);
tSet1.add(6);
tSet1.add(14);
System.out.println(tSet1);
System.out.println(hasOdd(tSet1));
}
}
This line:
if ((current / 2) == 1)
Should be:
if ((current % 2) == 1)
/ is for diving and % is for getting the remainder. Also, your method logic is off. Say you have multiple odds and evens in the set, you could get wrong results. I'd recommend doing this:
public static boolean hasOdd(Set<Integer> tSet1)
{
Iterator<Integer> itr = tSet1.iterator();
while (itr.hasNext())
{
int current = itr.next();
if ((current % 2) == 1)
{
//odd = true;
return true;//once you find the odd, just return
}
//else
//{
// odd = false;
//}
}
//return odd;
//if you're done iterating, that means it never found an odd so return false
return false;
}
Once you've found one odd in the set, then your case is true. Once you've looped through the entire set, then you know there could haven't been any odds, so just return false.
Note: As user ZouZou mentioned, if you want to handle negatives, then use:
current%2 != 0
You need to return the first time you get an odd value (as is you'll only return true if the last item is odd).
public static boolean hasOdd(Set<Integer> tSet1)
{
Iterator<Integer> itr = tSet1.iterator();
while (itr.hasNext())
{
int current = itr.next();
if ((current % 2) != 0) // Check for odd, by computing the modulo 2 of the #.
{
return true; // stop, there is an odd value.
}
}
return false; // checked all the values... none are odd.
}
I would use for-each loop here
public static boolean hasOdd(Set<Integer> set) {
for (Integer current : set) {
// Check for odd, by computing the modulo 2 of the #.
if ((current % 2) != 0) {
// stop, there is an odd value.
return true;
}
}
// checked all the values... none are odd.
return false;
}
Related
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
}
(JAVA only)
P.s This is a function i have tried, in order to check the first argument, and if it contains a number that is larger than the second argument, it will then return true, and flase otherwise.
Note that it is using do while loop. I just don't know which part of this code i have done wrong, because the system keeps telling me that "java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0".
Thank u, any hint will be much appriciated.
your list of Integers is empty. you can't access an index of an empty list:
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
if (numbers.isEmpty()) return false;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
}
A do-while control block works as follows:
Execute the do block
Check the condition. If it holds, return to (1)
Notice the order of this flow. Unlike a standard while, do-while will always execute one iteration before checking the condition. Therefore, for an empty list you will always try to access the 0-index element of the table, which does not exist, hence the error. You can use a while loop to avoid this:
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
while (d < numbers.size()) {
if (numbers.get(d) > number){
return true;
}
d++;
}
return false;
}
You should check whether the collection is empty
like this
if(numbers == null || numbers.isEmpty()) {
return false;
}
int d = 0;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
The aim of this code is to confirm the letter A appears 4 times exactly but using a recursive function. I can get it to count correctly, but as soon as it begins to leave the recursive stacks, it then +1 instead of -1 (I think because it is leaving the stack).
Is there a better way to handle this, has me very stuck.
public class App {
public static boolean isPresentNTimes(String sequence, char marker, int count) {
System.out.println("This is the count: " + count);
if (sequence.isEmpty() != true){
if(sequence.charAt(0) == marker) {
isPresentNTimes(sequence.substring(1), marker, count-1);
System.out.println("The count is" + count);
}
else {
isPresentNTimes(sequence.substring(1), marker, count);
}
}
if (count == 4){
return true;
} else {
return false;
}
}
public static void main(String []args){
String seq1 = "ABBAACBA";
System.out.println(isPresentNTimes(seq1, 'A', 4));
}
}
This is what you actually want to implement:
public static boolean isPresentNTimes(String sequence, char marker, int count) {
if(count < 0)
return false;
else if(count == 0 && sequence.isEmpty())
return true;
else if (!sequence.isEmpty()){
if(sequence.charAt(0) == marker) {
System.out.println("The count is " + count );
count--;
}
return isPresentNTimes(sequence.substring(1), marker, count);
}
else
return false;
}
Start with count=4 and decrement every time you found one element equals to mark. Make sure to add return before each recursive call (i.e., return isPresentNTimes (...)):
In your code you were comparing
if (count == 4){
return true;
} else {
return false;
}
if count == 4, which does not make sense since you start already with count = 4.
Hope this will give you the answer ->
static boolean ispresnt(String word, char c, int count) {
if (word.length() == 0) {
if (count == 0) {
return true;
}
return false;
}
return word.charAt(0) == c ?
ispresnt(word.substring(1), c, count - 1) : ispresnt(word.substring(1), c, count);
}
I have to write a recursive method in Java that returns true if a row is descending and false it does not.
This is what I tried, but it doesn't work properly:
ArrayList<Integer> getallen = new ArrayList();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else if (getallen.size() > 0) {
getallen.remove(0);
return isDescending(getallen);
} else {
return true;
}
} else {
return false;
}
}
I think you have unnecessary cases if the size is less than 2 you can only assume true.
Try:
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else {
getallen.remove(0);
return isDescending(getallen);
}
} else {
return true;
}
}
If I had to grade this, it would get a big fat X for
Having been fraudulently asked on stackoverflow
Being quite inefficient (try running this test on a list of a million elements, then realise that removing element 0 in an ArrayList causes all elements to shift down)
Instead consider:
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0);
}
public static boolean isDescending(List<Integer> getallen, int from) {
return from >= getallen.size() - 1
|| getallen.get(from) < getallen.get(from + 1)
&& isDescending(getallen, from + 1);
}
How about little bit more efficient approach with logarithmic recursion depth? Just as an exercise.
public static void main(String[] args) {
List<Integer> getallen = new ArrayList<Integer>();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0, getallen.size());
}
private static boolean isDescending(List<Integer> getallen,
int start, int end) {
if (end - start <= 1)
return true;
if (end - start == 2) {
return getallen.get(start) > getallen.get(start + 1);
}
int middle = (start + end - 1) / 2 + 1;
return (getallen.get(middle - 1) > getallen.get(middle)) &&
isDescending(getallen, start, middle) &&
isDescending(getallen, middle, end);
}
I have a Prime class which extends JFrame and it has a simple JSpinner for displaying prime numbers.
I want to create a Model for displaying prime numbers infinitely (until long ends). Here is the model class I have written:
public class PrimeSpinnerModel extends AbstractSpinnerModel{
long current;
public PrimeSpinnerModel() {
this.current = 2;
}
#Override
public Object getValue() {
return current;
}
#Override
public Object getNextValue() {
long newLatest = current + 1;
if(isPrime(newLatest)){
current = newLatest;
}else{
System.out.println(newLatest + "no prime");
newLatest ++;
current = newLatest;
}
fireStateChanged();
return getValue();
}
#Override
public Object getPreviousValue() {
fireStateChanged();
return getValue(); // without this the component wouldn't know to update.
}
#Override
public void setValue(Object value) {
throw new IllegalArgumentException("Static spinner model Prime does not support editing.");
}
static boolean isPrime(long n) {
if (n == 1) return false;
for(long i = 2; i <= n/2; i++)
if(n % i == 0)
return false;
return true;
}
}
When I run the code, it displays prime numbers as 2,3,5,7,9,11,13 etc.
Why 9 is displayed?
Suppose current is 7 when getNextValue() is invoked. Then newLatest is set to 8. isPrime(8) is obviously false, so then you increment newLatest, making it 9. You assign it to current and return it. This makes 9 the next number after seven, regardless of whether it is prime or not.
To solve this, you should increment newLatest while it is not prime (in a loop). That way, you ensure you continue until you found a prime number. See below:
newLatest = current + 1;
while (!isPrime(newLatest)) {
newLatest++;
}
// newLatest now contains the new prime number.
current = newLatest;
// etc..
Try this :)
public static void showPrimeNumbers(int n){
for (int i=2; i<n; i++){
boolean istrue = true;
for (int x=2; x<i; x++){
if (i%x==0){
istrue = false;
}
}
if (istrue==true){
System.out.println(i);
}
}
}
I've come across a problem. I'm trying to make a class which takes the maximum number that a user puts in and adds the integer before it until it gets to 0, however, when I run it, the numbers get larger and larger until it crashes. What seems to be throwing this into an infinite loop?
public class Summation {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Debug? (Y/N): ");
char debug = console.readChar();
if ((debug!='Y')&&(debug!='N')){
System.out.println("Please enter Y or N");
main(null);
}
else{
System.out.print("Enter max range:");
int max = console.readInt();
int s = sum(max,debug);
System.out.print(s);
}
}
public static int sum(int m, char d){
int sm = 1;
boolean isRunning = true;
while ((isRunning == true)&&(d=='Y')){
if ((--m)==0) {
isRunning = false;
}
else{
sm = m+(--m);
System.out.println("sm is"+sm);
}
while ((isRunning == true)&&(d=='N')){
if ((--m)==0) {
isRunning = false;
}
else{
sm = m+(--m);
}
}
}return sm;
}
}
There's a scenario where your condition for exit
if ((--m)==0)
will never again be reached, because m is already less than 0, and it's never going back.
that scenario is whenever m is an even number.
while ((isRunning == true)&&(d=='Y'))
{
// this condition decriments `m` every time it runs, regardless of whether it evaluates to true
if ((--m)==0)
{
// if `m` was set to 0 on your last iteration, it will be set to -1
isRunning = false;
}
else
{
// if m is 1 before this line it will be 0 after it.
sm = m+(--m);
System.out.println("sm is"+sm);
}
while ((isRunning == true)&&(d=='N'))
{
// this code will never get executed
}
}
return sm;
Answer to your problem is very simple
Just modify the condition
if (m==0) {
isRunning = false;
}
When you are checking --m == 0, it is very much possible that m will be jumping over 0 and will enter negative territory without even setting this condition to be true.
Everything you are doing is wrong :).
First - FORMATTING. You maybe even dont know that, but the second while is INSIDE the first while cycle. If you use netbeans, its ALT+SHIFT+F.
The using of --m is not good for your example, cause it firsts decrease the "m" value and then it compares. So even when you asking at
(--m)==0
you decrease a value. And because you are using it again at
sm = m+(--m)
you can even skip the "0" value and get into negative numbers.
However if you want only "add numbers in reverse order from given number to 0 in while loop" it is not fibonacci and you can use this code (it could be done better, but this is using your code) :
public class Summation {
public static void main(String[] args) {
System.out.println(sum(10, 'Y'));
}
public static int sum(int m, char d) {
int sm = 0;
boolean isRunning = true;
while ((isRunning == true) && (d == 'Y')) {
sm += m;
if (m == 0) {
isRunning = false;
} else {
m--;
System.out.println("sm is" + sm);
}
while ((isRunning == true) && (d == 'N')) {
if ((--m) == 0) {
isRunning = false;
} else {
sm = m + (--m);
}
}
}
return sm;
}
}
Note that second while cycle couldnt be reached - it passes only when "d == Y" and then it starts only when "d == N"