Why does my code only execute once - java

I want to print all the even numbers, but it only gives me 0!!
public class DataType {
public static void main(String[] args){
int number=0;
int max=20;
do{
System.out.println("this is an even number"+ number);
number++;
}while(number<=max&&EvenNumber(number));
}
public static boolean EvenNumber(int a)
{
if((a%2)==0)
{
return true;
}else
return false;
}
}

that is what your condition states: do while both conditions meet!, afters doing number++ for the 1st time the left side of the condition returns false and your loop is done!
you mean for sure:
do {
if (isEvenNumber(number)) {
System.out.println("this is an even number" + number);
}
number++;
} while (number <= max);
remember, following code means
while(number <= max && EvenNumber(number))
while BOTH conditions meet...

After number++;, number becomes 1, and thus the condition becomes false, and the loop terminates.
I assume, you wanted to do
do {
if (isEvenNumber(number)) System.out.println(number);
number++;
} while(number<=max);

Because in your code, If number is equals to 1, while condition is false

If you intend to find all even number between [0, 20] you may change your code to this version:
public static void main(String[] args) {
int max=20;
for (int number = 0; number <= max; number++) {
if (number % 2 == 0) {
System.out.printf("%d is an even number.\n", number);
}
}
}
This reads like:
start with number 0
while number not past 20
if number is even print it
continue with next number

Because in the second iteration the loop will exit.
if you want to print even numbers then the code should be
do{
if(EvenNumber(number)) {
System.out.println("this is an even number"+ number);
}
number++;
}while(number<=max );

Related

While loop augments wanted result?

This method finds the smallest number which can be divided by all numbers 1-10 using a while loop. However, if I set the system to print +i, the output is the correct answer +1. What's wrong with this code?
public static void main(String[] args){
int i=11;
int counter=0;
while(counter<10){
for(int j=1;j<=10;j++){
if((i%j)!=0) {
counter=0;
break;
}
else counter++;
}
i++;
}
System.out.println("The number is: "+i);
}
It happens because 'i++' increments i by 1 before the loop is exited. So, if the answer is 10, then before the loop exits, 'i++' changes it to 11. So, you can either choose to print 'i-1' to get the correct answer or you can write the code in such a way that when the right answer is found, 'i++' does not get executed.
You can do this -
public static void main(String[] args){
int i=11;
int counter=0;
while(counter<10){
for(int j=1;j<=10;j++){
if((i%j)!=0) {
counter=0;
break;
}
else counter++;
}
if(counter!=10) //this change
{
i++;
}
}
System.out.println("The number is: "+i);
}
Or you can do this
System.out.println("The number is : " + (i-1));

N prime numbers in java

So I've written this code in java which should output numbers on the screen from 1 to n(given by the user) and it should write "-prime" near the ones that are prime.
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++)
for(j=2;j<=n/2;j++)
{
if(i%j==0)
System.out.println(i);
else System.out.println(i +"-prime");
}}
}
If I input 6 for example i get :
Dati n: 6
1-prime
1-prime
2
2-prime
3-prime
3
4
4-prime
5-prime
5-prime
6
6
I'm new to this, and i'm really struggling with my algorithmic, could you tell me how should i change my program so it outputs correct values, and explain to me what i did wrong ? Thank you
UPDATE:
I've done it, thank you everyone for helping me out : this is the outcome:
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
boolean gasit = false;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++) {
gasit=false;
for(j=2;j*j<=i;j++)
{
if(i%j==0) gasit=true;}
if(!gasit) {System.out.println(i+"-prime");}
else {
System.out.println(i);}
}
}
}
You print something on every iteration of the inner loop.
Instead, you should print something after all iterations have completed, e.g.
boolean found = false;
for(j=2;j<=n/2;j++) {
if(i%j==0) found = true;
}
if (!found) {
System.out.println(i + "-prime");
} else {
System.out.println(i);
}
Additionally, you shouldn't be going up to n/2: you perhaps mean i/2 (a number doesn't have any factors greater than itself); but you can make it even tighter, since you don't have to check for factors greater than sqrt(i). Or, stated another way, that j * j <= i.
So you can make your loop declaration:
for(j=2; j*j<=i; j++) {
The problem is that the second loop goes until n/2, it should go until i/2 to check if i is prime. A more optimzed version of the primality check algorithm goes until sqrt(i), as suggested in comments.
The next issue is that you are concluding, in a false way, that if in the first case if(i%j==0) you say not prime, otherwise you say it is prime, which is not true necessairly. You should iterate the whole interval of values between [2:i/2] to conclude that i is prime.

Trying to solve a palindrome using integer arrays

I am writing a program that would help me find whether the number entered is a palindrome or not but i am trying it using arrays. And i would like to know if that is even possible?? And if it is possible then what am i doing wrong.
I have marked the code where i think the problem lies but feel free to suggest anything.!!!!
Thanks!!!
import java.util.Scanner;
public class palindrome
{
public static void main(String args[])
{
int size = 10,i,j,flag=0;
int num[] = new int[size];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the number ");
size = sc.nextInt();
System.out.println("Enter the number ");
for(i=0;i<size;i++)
{
num[i]=sc.nextInt();
}
i=size-1;
for(j=0;j<(size/2);j++,i--)
{
if(i>(size/2))
{
if(num[i]==num[j])
{
flag = 1;
}
}
}
if(flag==1)
{
System.out.println("The number is a palindrome");
}
else
System.out.println("The number is not a palindrome ");
}
}
Edit: Guys the problem is actually solved because i was doing a blunder mistake i.e. i was asking the user to enter the number in the form of an arry but i was not actually entering the digits in the number one by one instead i was entering the whole number in the first iteration.
But still a lot of thanks for the replies. I would still try your ideas and let you guys know. Thanks
:)
Try
public boolean isPalindrome(int[] num){
for(int i = 0 ; i < num.length/2 ; i++) {
if(num[i]!=num[num.length-(i+1)]) return false;
}
return true;
}
Yes it's possible, moreover, it's possible by using ArrayList, String - whatever you like. In order to write down a correct implementation, first decompose your current solution:
// Extract a method, do not cram all code into main()
// note: all you need is array, to get size of the array, put value.length
private static boolean isPalindrome(int[] value) {
...
}
public static void main(String args[]) {
int userInput[];
...
if (isPalindrome(userInput)) {
System.out.println("The number is a palindrome");
}
else {
System.out.println("The number is not a palindrome");
}
}
Now, let's implement isPalindrome():
private static boolean isPalindrome(int[] value) {
if (null == value)
return true; //TODO: or false, or throw exception
for (int i = 0; i < value.length / 2; ++i)
if (value[i] != value[value.length - 1 - i])
return false;
return true;
}
The easiest and most intuitive way (imo) to check for palindromes is through recursion. The idea is simple:
Is the first and last char the same?
YES Remove first and last char and check first and last char of the new String
NO There is no palindrome.
When the input is only 1 char then it's trivial.
Have a look at this code:
private void isPalindrome(String number){
if(number.length() == 1){
System.out.println("yes");
}else if(number.charAt(0) == number.charAt(number.length()-1)){
isPalindrome(number.substring(1, number.length()-1));
}else{
System.out.println("no");
}
}
Testing with:
isPalindrome(String.valueOf(232)) Returns "yes"
isPalindrome(String.valueOf(23)) Return "no"
Of course this also works with Arrays just as easily. Replace the parameter with an array and search through the indices the same way. When cutting down the array just create a new smaller array without first and last index of the previous array.
Your class has several issues:
First you're not checking if a number is a palindrome or not. Your algorithm is flawed
Second, you're asking to enter a size but in the end, the user inputs it but you don't use it yourself. Instead, you're using that introduced value in the number array.
Here's how you should do it.
public class Palindrome {
private static boolean isPalindrome(int[] array) {
for (int i = 0, j = array.length-1; i < j; i++, j--) {
if (array[i] != array[j]) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many numbers do you want to enter? ");
int size = scanner.nextInt();
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
System.out.printf("Enter number %s: ", i+1);
numbers[i] = scanner.nextInt();
}
if (isPalindrome(numbers)) {
System.out.println("The number is a palindrome");
} else {
System.out.println("The number is not a palindrome");
}
}
}

Can someone please go through how this program works. Im new to java

Please explain how this converts decimal to binary:
import java.util.*;
public class decimalToBinaryTest {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive interger");
number = in.nextInt();
if (number < 0) {
System.out.println("Not a positive interger");
}
else {
System.out.print("Convert to binary is: ");
System.out.print(binaryform(number) + ".");
}
}
private static Object binaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return null;
}
remainder = number % 2;
binaryform(number >> 1);
System.out.print(remainder);
{
return " ";
}
}
}
I mainly don't get the bit in private static object. Or the return " ". I really don't see how it does but it works. If you enter 10 it displays: Convert to binary is: 1010.
Do I need the >> 1 or can it be *0.5
There are two important moments in this code:
binaryform(number >> 1);
first: recursion. Call function from this function (foo() {foo();}
second: bitwise. >>1 - shift number for 1 bit, it's the same to devide by 2.
every recursion iteration, code devide number by 2 and print reminder AFTER recursion function works (from last to first). It's like:
{
{
{
{
print inner (fourth iteration
}
print before inner (third iteration)
}
print before before inner (second iteration)
}
print outer (first iteration)
}

Implementing methods: search, load and print

Please see my comments in the code to better explain things. Basically having issues with the methods below. I can get the load method to run but I am unsure whether the numbers entered by the user are actually being stored in the array.
In addition, the search method has been throwing things off and i think its going in a loop.
See below for more. Thank you in advance.
import java.util.Scanner;
public class MyContainer {
private int[] values;
private int size;
public MyContainer(){
values=new int[50];
size=0;}
//Load Method - Display a message to the user
//and get positive intergers from user
public void load()
{
int input;
Scanner in = new Scanner(System.in);
System.out.println("Enter a series of positive integers (Negative to Terminate): ");
input=in.nextInt();
while (input >=0) {
values[size]=input;
size++;
input=in.nextInt();
}
}//End Load
//Compute Average from the above entered numbers
public double computeAverage() {
double avg= 0.0;
int count = 0;
while(values[size] >=0)
{avg = avg + values[size];
count++;
}
size = size + 1;
avg = avg / size;
return avg;
}
//Get user input to search for a number in the array
public boolean search(int myInt){
while(values[size] >=0) {
if (values[size] == myInt){
return true;}
else{
size++;}
}
return false;
}
//print the position of the number
public void print(){
for(int i=0;i>=size;i++) {
System.out.println("The number at position " + i + " is " + values[i]);
}
}
}
That is what I have so far. I also have created a tester class for the above container.
class Tester {
public static void main(String[] args) {
MyContainer in = new MyContainer();
in.load();
in.computeAverage();
in.search(); //i know for a fact this is wrong just stuck
in.print();
}
}
Any advise/help would be greatly appreciated. My professor is terrible at teaching and the book only partially explains things.
Your search() method has parameters that you aren't passing.
you declare it as...
public boolean search(int myInt) {
while (values[size] >= 0) {
if (values[size] == myInt) {
return true;
} else {
size++;
}
}
return false;
}
but call it with...
in.search();
This code won't even compile. For argument sake I set this to 5.
In your computeAverage() method, this is an infinite loop...
while (values[size] >= 0) {
avg = avg + values[size];
count++;
}
The main problem I believe you are running into is the reuse of your size variable. In the load function it will work as expected say for loading in 10 numbers size will be 10 and elements 0->9 in values will have numbers in them. However when you get to computeAverage size will still be 10. So you are in an infinite loop.
while(values[size] >= 0) {
avg = avg + values[size];
count++;
}
First iteration you will check values[10] (which is wrong remember valid elements are only in 0->9 if size is 10). Next iteration avg and count are increased but size remains the same so you will add the same number to avg and continue in the loop. You should use a different conditional for your while loops in computeAverage and search. The last negative number entered to quit will not be in the array; you will need to use something else. As a hint it will involve count and size.

Categories