Output line repeats using while loop? - java

I am just beginning to learn Java and still getting used to while loops. I would like the output statement to only show once instead of multiple times. For example, the statement should say:
"Even integers between 1 and 5 are: 2 4"
instead of:
"Even integers between 1 and 5 are:
2
Even integers between 1 and 5 are:
Even integers between 1 and 5 are:
4"
If I could get some feedback on what I'm doing wrong here, it'd be appreciated. Thanks
//Declare variables
int n1, n2, sumOdd = 0;
int sum = 0;
int sumSquares = 0;
//Part B
int count = n1;
while (count < n2)
{
if (count % 2 ==0)
{
System.out.println(count);
}
count++;
System.out.println("Even integers between " + n1 + " and " + n2 + " are: ");
} //end loop

create an int array or Collection before your loop, when you find out the even number in while loop, append the number in the array/collection.
After the while loop, print output only once, of course with those found numbers.
I think it is straightforward, and I leave the implementation part to you.

You should take last part of the while loop out of it:
//Part B
System.out.println("Even integers between " + n1 + " and " + n2 + " are: ");
int count = n1;
while (count < n2) {
if (count % 2 ==0) {
System.out.print(" " + count);
}
count++;
}
As you didn't mention that you want a comma between even numbers, then replacing println with print should be enough

They are different ways to achieve your goal. A quick solution would be to put
System.out.println("Even integers between " + n1 + " and " + n2 + " are: ");
in front of your while-loop and and replace System.println() with System.print().

int n1, n2, sumOdd = 0;
int sum = 0;
int sumSquares = 0;
System.out.print("Even integers between " + n1 + " and " + n2 + " are: ");
//Part B
int count = n1;
while (count < n2)
{
if (count % 2 == 0)
{
System.out.print(count);
}
count++;
} //end loop

Related

Printing out multiple values assigned to a single variable

I have a for loop that will continue until i is not less than the maxnum as shown in the code. In the meantime it will do modulo operation and I am trying to accumulate as much values as possible to the variable that I can assign with. My problem is in the code is that it only does the single operation and will not continue to do the operation and have multiple values assign to it. Should I change my loop.
tried assigning an array list
having i++ below
for(int i =1; i < maxnum; i++ ) {
MulT = i % divisor;
}
if ( MulT==0 ) {
System.out.println("Multiples of " + dividend+ " between 1 and "+ maxnum +" is");
System.out.println(MulT);
}
else {
System.out.println("Multiples of " + dividend + " between 1 and " + maxnum+ "are:");
System.out.print("No numbers were found");
}
Multiples of 2 between 1 and 10 are:
2
4
6
8
10
If you want to get all the values stored in variables then you have to iterate that variable in for loop after that print that variable in console, check the below code.
int maxnum=10;
int divisor=2;
int val[] = new int[maxnum];
int j=0;
for(int i =1; i <= maxnum; i++ ) {
double MulT = i % divisor;
if(MulT==0){
val[j]=i;
j++;
}
}
if(val[0] > 0){
System.out.print("Multiples of " + divisor+ " between 1 and "+ maxnum +" is:");
for(int k=0;k < val.length;k++){
if(val[k]!=0){
System.out.print(" "+val[k]);
}
}
}else{
System.out.println("Multiples of " + divisor + " between 1 and " + maxnum+" are:");
System.out.print("No numbers were found");
}

How do I get the sum of the first two sequences when the user enters "2" as "n"?

The sequence is: sum = 1 + 1/2 + 1/4 + 1/9 + 1/16 + 1/25+...
When I enter "2" it just gives me the sum of 1.25. How do you get it so when "2" is entered, it is adding 1 + 1/2?
Oh and I'm in an entry level java course so I we cant use arrays or anything that advance yet.
Thanks in advance!
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
sum += 1.0 / (counter*counter);
}
System.out.println("The sum is: " + sum);
}
}
Since you say that 1/2 must be part of the sequence, so be it. (But that's a bizarre sequence and I strongly suggest that you double check this with your professor.) I'll assume that the remainder of the sequence is defined by 1/i2. Note that with these assumptions, the sequence terminates at 1/(n-1)2 rather than 1/n2.
You'll need special handling for the cases n == 1 and n > 1. One possibility is to initialize sum to 1 if n == 1; initialize it to 1.5 if n > 1; and otherwise initialize it to 0. Then start the loop at counter = 2 and change the loop termination condition to counter < n (instead of <=).
You need to manage "1" and "2" as special cases.
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
if (counter == 1)
sum = 1;
else if (counter == 2 )
sum += 1.0/((counter-1)+(counter-1));
else
sum += 1.0 / ((counter-1)*(counter-1));
}
System.out.println("The sum is: " + sum);
}
}
If that's your sequence then you should really start by setting the sum equal to 1.5 and then rest of it will work. Your sequence should be a geometric sequence 1/n^2 I think it's a mistake.
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
double sum = 1.5;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1)
System.out.println("The sum is: " + 1);
//process
for(int counter = 2; counter <n; counter++) {
double mul = counter*counter;
sum += 1.0/mul ;
}
System.out.println("The sum is: " + sum);
}
Output :
Enter n:
2
The sum is: 1.5
Enter n:
3
The sum is: 1.75
The following code will solve your problem, i have used Math.pow() to get the sequence running and not multiplying it twice.
public static void main(String[] args) throws UnknownHostException {
//declarations
Scanner scan = new Scanner(System.in);
//to generate this sequence we take the first two as constants and start generating from the third onwards
double first = 1;//first number in the sequence
double second = 0.5;//second number in the sequence
double sum = first+second;//adding first and second
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1){
System.out.println("The sum is: " + first);
return;
}
if(n==2){
System.out.println("The sum is: " + sum);
return;
}
//process
for(int counter = 2; counter <n; counter += 1)
{
sum += 1.0 / Math.pow(counter, 2);//will be computed when you enter values when n is more than 3
}
System.out.println("The sum is: " + sum);
}
As per your for loop, the sequence generated will be 1 + 1/(2*2) + 1/(3*3)+ ......
So, when you enter 2 => 1+1/(2*2) = 1+0.25=1.25.
Otherwise, your logic is Good. you can implement few exceptions, but as you mentioned that you re new to Java, you ll slowly encounter them.
Happy Learning Java :)

How to return a single print statement from a search() method in an array?

I'm having trouble with my search method. What I want to do is have my search method print the statement only once. So if my array contains "3" more than once, I only want to print "3 was found." once instead of checking each value and reporting that there is or is not a "3" at that point in the array. How would I do that?
To clarify, this is what I have:
`0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was found.
2 was not found.
2 was not found.`
And this is what I want:
0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was found.
2 was not found.
So this is my complete class. I created a method called initialize that will assign each element in my array a random integer between 0 and 10; a method called print to print out the contents of my array; a method called printStats to find and then print the average, maximum, and minimum value in my array; and a method called search that searches my array (and prints the result) for an integer parameter passed to my method.
Everything works correctly.
public class ArrayLab
{
private int[] array;
public ArrayLab(int numElements)
{
array = new int[numElements];
}
public void initialize()
{
array[0] = (int) (Math.random()*11);
array[1] = (int) (Math.random()*11);
array[2] = (int) (Math.random()*11);
array[3] = (int) (Math.random()*11);
array[4] = (int) (Math.random()*11);
array[5] = (int) (Math.random()*11);
array[6] = (int) (Math.random()*11);
array[7] = (int) (Math.random()*11);
array[8] = (int) (Math.random()*11);
array[9] = (int) (Math.random()*11);
}
public void print() {
System.out.println(array[0] + "," + array[1] + "," + array[2] + "," + array[3] + "," + array[4] + "," + array[5] + "," + array[6] + "," + array[7] + "," + array[8] + "," + array[9]);
System.out.println();
}
public void printStats()
{
double sum = 0;
int max = 0;
int min = 0;
min = array[0];
for (int i = 0; i < array.length; i++)
{
sum = sum + array[i];
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
double average = sum/array.length;
System.out.println("Average Value: " + average);
System.out.println("Maximum Value: " + max);
System.out.println("Minimum Value: " + min);
}
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
}
else
{
System.out.println(numChosen + " was not found.");
}
}
}
}
Start using return or break statement to break the loop after you hit the first successful search.
Also, you should not print the Was Not Found every time while iterating the array. You should print it only once in the end when your array gets exhausted completely and search query is not found.
Here is the modified code snippet:
boolean flag = false;
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
flag = true;
break;
}
}
if(!flag) {
System.out.println(numChosen + " was not found.");
}
Alternatively, you can also do the following:
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
Well, you don't need to keep iterating through the loop once you found the number. Also, you want to print "was not found" in a case it didn't find anything, meaning the loop finished without printing anything yet.
So this is how you should implement it:
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
}
In a case it found something, it will print the message and exit the method and never reach the printing of second message. It will only print the second message when the loop is over.
You are displaying results in your public void search(int numChosen) function. In your case, instead of printing every time you encounter a match, put a counter instead, then print once: that counter with the rest of you sentence.
Try this:
public void search(int numChosen)
{
int count = 0;
for (int i = 0; i < array.length; i++)
if (array[i] == numChosen)
count++;
if (count == 0)
System.out.println(numChosen + " was not found.");
else
System.out.println(numChosen + " was found " + count + " times.");
}

java get even or odd number

I have a assignment for school: I need to get even or odd numbers and I made something to work for numbers that are above zero, but I need to find out how a negative number is even or odd.
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i < 100; i++)
{
int x = i;
while (x > 1) x = x - 2;
System.out.println(i + evenodd[x]);
}
simply use module % operator
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i < 100; i++)
{
int x;
if(i%2==0){
x=0;/*pass 0 to print even number */
}else{
x=1;/*pass 1 to print odd number*/
}
System.out.println(i + evenodd[x]);
}
Even and Odd numbers:
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i < 100; i++)
{
System.out.println(i + evenodd[i % 2]);
}
OR
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i < 100; i++)
{
if(i % 2 == 0)
System.out.println(i + evenodd[i % 2]);
else
System.out.println(i + evenodd[i % 2]);
}
For negative numbers is even or odd?:
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i > -100; i--)
{
if(i % 2 == 0)
System.out.println(i + evenodd[0]);
else
System.out.println(i + evenodd[1]);
}
Try and use the % operator.
Usage : x % y -> This will give you the remainder when y is divided by x.
In your case use y = 2. Hence if the remainder = 0, the number is even else the number will be odd.
I am not giving you the exact code, since this is your assignment. Try it yourself based on the suggestion.
To find out odd and even number. Follow the logic
divide your number by 2 if the reminder is 0 then it is even
else it is odd
this similar for both positive and negative numbers
to find out reminder use modulo division operator (%). if your_number%2=0 your_number is even else your_number is odd.
Sample code:
for(int i=1;i<100;i++){
if(i%2==0){//for positive number
System.out.println(i+ " is Even Number");
}else{
System.out.println(i+ " is Odd Number");
}
if((-1)*i%2==0){//for negative number
System.out.println((-1)*i+" is Even Number");
}else{
System.out.println((-1)*i+" is Odd Number");
}
}

How to compare the given integer with possible roots

I could not name the question in the best way... My aim is to write a program that takes integer n from user. Then compare with the third power of two integers a and b.
If a^3 + b^3 is smaller than or equal to the given input, I want to print out every single possible calculation to the user.
My code is as follows:
System.out.println("Hi. Please insert an integer: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double root = Math.cbrt(n);
int rootInt = (int) root;
for (int i = 0; i < rootInt; i++){
for (int j = 0; j < rootInt; j++){
if ((Math.pow(i, 3)) + (Math.pow(j, 3)) <= n){
double t = (Math.pow(i, 3) + (Math.pow(j, 3)));
int totalInt = (int) t;
System.out.println(i + "^3" + " + " + j + "^3" + " = " + totalInt );
} else {
}
j++;
}
i++;
}
When I run this and give an input as 30, it prints
0^3 + 0^3 = 0
0^3 + 2^3 = 8
2^3 + 0^3 = 8
2^3 + 2^3 = 16
What am I doing wrong?
You increase j and i twice. That's why you test only the even values for i, j.
If you want to correct the code, remove the i++, j++ from the end and use only the increments from the 2 fors.

Categories