How do I combine these two while statements into one? - java

I have two while loops where one is taking the odd numbers between 50 to 100 and the other is taking the even numbers from the same between 50 to 100. It is printing out well and it works but my professor wants me to transform it into one while loop instead of two. I am having trouble with it because I am using the print statement before in order so it fits into when the numbers go in.
int e = 50;
int o = 51;
System.out.print("Even numbers between 50 and 100: 50,");
while (e <= 98){
e += 2;
if (e%2 == 0){
System.out.print(e + ",");
}
}
System.out.print("\nOdd numbers between 50 and 100: 51,");
while (o <= 97){
o+= 2;
if (e%1 == 0) {
System.out.print(o + ",");
}
}
Even numbers between 50 and 100: 50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,
Odd numbers between 50 and 100: 51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,
The output looks like this right now, but I need to be able to do it with just one loop instead

If you only want one while loop, and separate lines, you should build your strings and print them afterwards.
Something like:
StringBuilder odds = new StringBuilder();
StringBuilder evens = new StringBuilder();
i = 50;
while(i<100) {
if(i%2 == 1) {
odds.append(i).append(",");
}
else {
evens.append(i).append(",");
}
i++;
}
// remember that odds and evens now probably ends with a ','which you should remove
odds.removeCharAt(odds.size());
evens.removeCharAt(evens.size());
// or do something like the following:
//odds.append(" and nothing more!");
//evens.append(" and nothing more!");
System.out.println("Odd numbers are: ");
System.out.println(odds);
System.out.println("Even numbers are" ");
System.out.println(evens)

Try to increment a counter variable by 1 in each step and use an if statement to check the modulus (%). If it equals 0, then the number is even; if it equals 1, then the number is odd. For printing the separately, you can use two lists or arrays.
int count=50;
StringBuilder odds = new StringBuilder();
StringBuilder evens = new StringBuilder();
while(count<=100)
{
if(count%2==0) // here, the number is even, append this number to even string
evens.append(count).append(",");
else // here, the number is odd, append this number to odds string
odds.append(count).append(",");
count++;
}
// when everything is done, print the strings
// before doing that, you should remove the last comma at the end of these Strings.
// Otherwise, you will have something like this: 93,95,97,
evens.setLength(evens.length() - 1); // to remove the comma at the end
odds.setLength(odds.length() - 1); // to remove the comma at the end
System.out.println("The even numbers are: " + evens.toString());
System.out.println("The odd numbers are: " + odds.toString());
It is much more efficient to use a StringBuilder rather than using += kind of appending for Strings. Take a look at this link:
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

You can use single while loop like this for printing odd and even number.
int e = 50;
while (e <= 98)
{
if (e%2 == 0)
{
System.out.println("even :"+e);
}
else
{
System.out.println("odd :"+e);
}
e++;
}

Just create 2 string output variables and fill them in the loop based on condition
if (i%2==1)
odd_output = odd_output + "," + i.toString
else
even_output = even_output + "," + i.toString
(I might be wrong in Java syntax)
And then just print both resulting strings with any additional info you like

I know it doesn't answer directly the question (although the output is the same) but in 2016 when one want to print a sequence of numbers we do something like that:
public static void main(String[] args) {
int[] evenNumbers = IntStream.rangeClosed(50, 100).filter(i -> i % 2 == 0).toArray();
int[] oddNumbers = IntStream.rangeClosed(50, 100).filter(i -> i % 2 != 0).toArray();
System.out.println("Even numbers between 50 and 100: " + Arrays.toString(evenNumbers));
System.out.println("Odd numbers between 50 and 100: " + Arrays.toString(oddNumbers));
}
If the goal of your exercice is to learn how to use a while loop, my solution is useless. However if your goal is to practice Java as it should be nowadays, I think if reaches the goal.

Here You don't need to maintain Any separate Arrays Or Strings, but a complex conditions
public class EvenOddTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num = 50;
System.out.println("Even numbers between 50 and 100: ");
while (num < 100){
if (num%2 == 0){
System.out.print(num + ",");
} else {
System.out.print(num + ",");
}
if( num == 98 ) {
num = 49;
System.out.println();
System.out.println("Odd numbers between 50 and 100: ");
}
num += 2;
}
}
}

Related

How to remove last comma [duplicate]

This question already has answers here:
How to remove the last comma from the output in java? [duplicate]
(4 answers)
Closed 3 months ago.
public class Main {
public static void main(String[] args) {
// positive number
int number = 6;
System.out.print("Factors of " + number + " are: ");
// loop runs from 1 to 60
for (int i = 1; i <= number; ++i) {
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + ",");
}
}
}
}
And my output is "1,2,3,6," but i want it like "1,2,3,6"
How can i do that?
No matter what i do it did not worked.
The simple and robust solution is to store the values in a list, and only then display them. This way you'll easily know when you're printing the last element. Besides, then you could just do something like:
List<String> divisors = new ArrayList<>();
// loop runs from 1 to 60
for (int i = 1; i <= number; ++i) {
// if number is divided by i
// i is the factor
if (number % i == 0) {
divisors.add(String.valueOf(i));
}
}
System.out.println(String.join(",", divisors));
Solution written by #abel1502 is the simplest if you want to display the values and keep them to use elsewhere. If you just want to display them, then there are more modern ways to do it (if you use a recent version of Java) :
var number = 60;
System.out.println(
IntStream.rangeClosed(1, number)
.filter(i -> number % i == 0)
.mapToObj(String::valueOf)
.collect(Collectors.joining(","))
);
There are multiple ways to solve it. In your case since the last 'i' in the loop is always number itself, and it should be on the list since (number%number==0), you can simply do something like this:
public class Main {
public static void main(String[] args) {
// positive number
int number = 6;
System.out.print("Factors of " + number + " are: ");
// loop runs from 1 to 60
for (int i = 1; i < number; ++i) { //< instead of <=, to exclude i==number
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + ",");
}
}
//in your case
System.out.print(number);
}
}

Formatting returned Strings?

I'm really new to coding and just got assigned my first coding homework involving methods and returns. I managed to struggle through and end up with this, which I'm pretty proud of, but I'm not quite sure it's right. Along with that, my return statements are all on the same lines instead of formatted how my teacher says they should be ("n is a perfect number", then the line below says "factors: x y z", repeated for each perfect number. Below are the exact instructions plus what it outputs. Anything will help!
Write a method (also known as functions in C++) named isPerfect that takes in one parameter named number, and return a String containing the factors for the number that totals up to the number if the number is a perfect number. If the number is not a perfect number, have the method return a null string (do this with a simple: return null; statement).
Utilize this isPerfect method in a program that prompts the user for a maximum integer, so the program can display all perfect numbers from 2 to the maximum integer
286 is perfect.Factors: 1 2 3 1 2 4 7 14
It should be
6 is perfect
Factors: 1 2 3
28 is perfect
Factors: 1 2 4 7 14
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in) ;
System.out.print("Enter max number: ") ;
int max = input.nextInt() ;
String result = isPerfect(max) ;
System.out.print(result) ;
}
public static String isPerfect(int number) {
String factors = "Factors: " ;
String perfect = " is perfect." ;
for (int test = 1; number >= test; test++) {
int sum = 0 ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
sum += counter ;
}
}
if (sum == test) {
perfect = test + perfect ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
factors += counter + " " ;
}
}
}
}
return perfect + factors ;
}
}
Couple of things you could do:
Firstly, you do not need two loops to do this. You can run one loop till number and keep checking if it's divisible by the iterating variable. If it is, then add it to a variable called sum.
Example:
.
factors = []; //this can be a new array or string, choice is yours
sum=0;
for(int i=1; i<number; i++){
if(number % i == 0){
sum += i;
add the value i to factors variable.
}
}
after this loop completes, check if sum == number, the if block to return the output with factors, and else block to return the output without factors or factors = null(like in the problem statement)
In your return answer add a newline character between perfect and the factors to make it look like the teacher's output.
You can try the solution below:
public String isPerfect(int number) {
StringBuilder factors = new StringBuilder("Factors: ");
StringBuilder perfect = new StringBuilder(" is perfect.");
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
factors.append(" " + i);
}
}
if (sum == number) {
return number + "" + perfect.append(" \n" + factors);
}
return number + " is not perfect";
}
Keep separate variables for your template bits for the output and the actual output that you are constructing. So I suggest that you don’t alter factors and perfect and instead declare one more variable:
String result = "";
Now when you’ve found a perfect number, add to the result like this:
result += test + perfect + '\n' + factors;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
result += counter + " ";
}
}
result += '\n';
I have also inserted some line breaks, '\n'. Then of course return the result from your method:
return result;
With these changes your method returns:
6 is perfect.
Factors: 1 2 3
28 is perfect.
Factors: 1 2 4 7 14
Other tips
While your program gives the correct output, your method doesn’t follow the specs in the assignment. It was supposed to check only one number for perfectness. Only your main program should iterate over numbers to find all perfect numbers up to the max.
You’ve got your condition turned in an unusual way here, which makes it hard for me to read:
for (int test = 1; number >= test; test++) {
Prefer
for (int test = 1; test <= number; test++) {
For building strings piecewise learn to use a StringBuffer or StringBuilder.
Link
Java StringBuilder class on Javapoint Tutorials, with examples.

Processing numbers program

Firstly, I'm taking AP Computer Science this year, and this question is related to an exercise we were assigned in class. I have written the code, and verified that it meets the requirements to my knowledge, so this is not a topic searching for homework answers.
What I'm looking for is to see if there's a much simpler way to do this, or if there's anything I could improve on in writing my code. Any tips would be greatly appreciated, specific questions asked below the code.
The exercise is as follows: Write a program called ProcessingNumbers that does:
Accepts a user input as a string of numbers
Prints the smallest and largest of all the numbers supplied by the user
Print the sum of all the even numbers the user typed, along with the largest even number typed.
Here is the code:
import java.util.*;
public class ProcessingNumbers {
public static void main(String[] args) {
// Initialize variables and objects
Scanner sc = new Scanner(System.in);
ArrayList<Integer> al = new ArrayList();
int sumOfEven = 0;
// Initial input
System.out.print("Please input 10 integers, separated by spaces.");
// Stores 10 values from the scanner in the ArrayList
for(int i = 0; i < 10; i++) {
al.add(sc.nextInt());
}
// Sorts in ascending order
Collections.sort(al);
// Smallest and largest values section
int smallest = al.get(0);
int largest = al.get(al.size() - 1);
System.out.println("Your smallest value is " + smallest + " and your largest value is " + largest);
// Sum of Even numbers
int arrayLength = al.size();
for (int i = 0; i < al.size(); i++) {
if (al.get(i) % 2 == 0) {
sumOfEven += al.get(i);
}
}
System.out.println("The sum of all even numbers is " + sumOfEven);
// Last section, greatest even number
if (al.get(arrayLength - 1) % 2 == 0) {
System.out.println("The greatest even number typed is " + al.get(arrayLength - 1));
} else {
System.out.println("The greatest even number typed is " + al.get(arrayLength - 2));
}
sc.close();
}
}
Here are specific questions I'd like answered, if possible:
Did I overthink this? Was there a much simpler, more streamlined way to solve the problem?
Was the use of an ArrayList mostly necessary? We haven't learned about them yet, I did get approval from my teacher to use them though.
How could I possibly code it so that there is no 10 integer limit?
This is my first time on Stackoverflow in quite some time, so let me know if anything's out of order.
Any advice is appreciated. Thanks!
Usage of the ArrayList wasn't necessary, however it does make it much simpler due to Collections.sort().
To remove the 10 integer limit you can ask the user how many numbers they want to enter:
int numbersToEnter = sc.nextInt();
for(int i = 0; i < numbersToEnter; i++) {
al.add(sc.nextInt());
}
Another note is that your last if-else to get the highest even integer doesn't work, you want to use a for loop, something like this:
for (int i = al.size() - 1; i >= 0; i--) {
if (al.get(i) % 2 == 0) {
System.out.println("The greatest even number typed is " + al.get(i));
break;
}
I wouldn't say so. Your code is pretty straightforward and simple. You could break it up into separate methods to make it cleaner and more organized, though that isn't necessary unless you have sections of code that have to be run repeatedly or if you have long sections of code cluttering up your main method. You also could have just used al.size() instead of creating arrayLength.
It wasn't entirely necessary, though it is convenient. Now, regarding your next question, you definitely do want to use an ArrayList rather than a regular array if you want it to have a variable size, since arrays are created with a fixed size which can't be changed.
Here's an example:
int number;
System.out.print("Please input some integers, separated by spaces, followed by -1.");
number = sc.nextInt();
while (number != -1) {
al.add(number);
number = sc.nextInt();
}
Here is a solution that:
Doesn't use Scanner (it's a heavyweight when all you need is a line of text)
Doesn't have a strict limit to the number of numbers
Doesn't need to ask how many numbers
Doesn't waste space/time on a List
Handles the case when no numbers are entered
Handles the case when no even numbers are entered
Fails with NumberFormatException if non-integer is entered
Moved actual logic to separate method, so it can be mass tested
public static void main(String[] args) throws Exception {
System.out.println("Enter numbers, separated by spaces:");
processNumbers(new BufferedReader(new InputStreamReader(System.in)).readLine());
}
public static void processNumbers(String numbers) {
int min = 0, max = 0, sumOfEven = 0, maxEven = 1, count = 0;
if (! numbers.trim().isEmpty())
for (String value : numbers.trim().split("\\s+")) {
int number = Integer.parseInt(value);
if (count++ == 0)
min = max = number;
else if (number < min)
min = number;
else if (number > max)
max = number;
if ((number & 1) == 0) {
sumOfEven += number;
if (maxEven == 1 || number > maxEven)
maxEven = number;
}
}
if (count == 0)
System.out.println("No numbers entered");
else {
System.out.println("Smallest number: " + min);
System.out.println("Largest number: " + max);
if (maxEven == 1)
System.out.println("No even numbers entered");
else {
System.out.println("Sum of even numbers: " + sumOfEven);
System.out.println("Largest even number: " + maxEven);
}
}
}
Tests
Enter numbers, separated by spaces:
1 2 3 4 5 6 7 8 9 9
Smallest number: 1
Largest number: 9
Sum of even numbers: 20
Largest even number: 8
Enter numbers, separated by spaces:
1 3 5 7 9
Smallest number: 1
Largest number: 9
No even numbers entered
Enter numbers, separated by spaces:
-9 -8 -7 -6 -5 -4
Smallest number: -9
Largest number: -4
Sum of even numbers: -18
Largest even number: -4
Enter numbers, separated by spaces:
No numbers entered

Need Assistance counting even and odd integers

Ok so I am reviewing for an exam in Java, and one of the problems asks us:
We wish to develop a program that will count the number of even and odd integers in a set ("even" meaning divisible by 2, "odd" meaning not divisible by 2). We will use zero as an indicator that the set has been completely entered, and this zero should not be counted as part of the set. Ask the user for a sequence of integers, terminated by zero. Output the number even integers and the number of odd integers.
When I run my code, for some reason the first variable is ALWAYS counted as even, regardless what the integer is. I can't for the life of me figure out why. Example: I type 23, 22, 25. It says 2 even 1 odd. However, if I type it 22, 23, 25 it says 1 even 2 odd.
Here is my Code:
public class Problem4_Exam1Practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Numbers");
int x = IO.readInt();
int even = 0;
int odd = 0;
while(x != 0) {
x = IO.readInt();
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
}
System.out.println(even + " even " + odd + " odd ");
}
}
The issue is that you always ignore the first number and count the terminating 0 as even which gives an impression that first number is always counted as even.
You can fix this by reordering your while loop as
while(x != 0) {
// check odd-even first
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
// then read next int
x = IO.readInt();
}
You are overwriting the first input inside the while. It's better if you use a do while for this.
System.out.println("Enter Numbers");
// x = IO.readInt(); => remove this line
int even = 0;
int odd = 0;
while ((x = IO.readInt()) != 0) {
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
}
EDIT: code edited to fix what #jschultz410 point out.
I think your issue might stem from the fact that the first number seems to be being skipped. You are putting it into x and then overwriting it immediately without looking at it. Try using a do-while loop instead, and putting the x = IO.readInt() at the end.
The first number entered is never evaluated:
int x = IO.readInt();
Then when the loop is entered it is overridden before evaluated:
while(x != 0) {
x = IO.readInt();
...
}
One solution is to move the reading to the end of the loop:
while(x != 0) {
...
x = IO.readInt();
}
There are a couple issues here. First, your very first value is being consumed, but it is not being used in your while loop. Also, you count your last value, which is 0. Reading the value last helps to solve that problem.
public class Problem4_Exam1Practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Numbers");
int x = IO.readInt();
int even = 0;
int odd = 0;
while (x != 0) {
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
x = IO.readInt();
}
System.out.println(even + " even " + odd + " odd ");
}
}
Thanks everyone for the help! As for scanners we use an IO module provided to us, so we can't use scanners "YET".
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("Enter Numbers");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
int even = 0;
int odd = 0;
while(true) {
String s1 = bufferRead.readLine();
int x = Integer.parseInt(s1);
if(x==0)
break;
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
}
System.out.println(even + " even " + odd + " odd ");
}

To produce an random output: 100 numbers from 901 to 999

I'm trying to create two separate outputs of 10 columns and 10 rows of numbers. I know I can do the first output using numbers 4 through 7 and the second output using numbers 10 through 90. But I have in trouble to do the third output using numbers 901 through 999. Below is the Java code I have:
import java.util.Random;
public class LabRandom
{
private static final Random rand = new Random();
public static void main(String[] args)
{
int number;
int i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(4) + 4);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
System.out.println();
i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(9)*10+10);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
System.out.println();
i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(100)*10);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
}
}
I'm having trouble understanding what you want. If you want to create an output of 100 randomly chosen number in the range 900 to 999, with line breaks after every 10 such numbers, try adding this loop to your code:
i = 1;
while (i <= 100)
{
// generate a random number from 0 to 100-1,
// then add 900 to transform the range to 900 to 999
System.out.printf("%-5d", rand.nextInt(100) + 900);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
By the way, if you really want to print numbers 10 to 90, your second loop is incorrect.
Right now you print multiples of 10, from 10 to 90, eg 10,20,30.....90
For every number between, you would want:
rand.nextInt(80)+10
// difference between the highest and the lowest value you want to have in your result
int range = 99;
// the lowest possible value you want to see in your result
int lowestValue = 901;
//note that you will never get the numbers 900 and 1000 this way, only between
int result = rand.nextInt(range) + lowestValue;
You might want to read what exactly nextInt(value) does (easy to do inside a proper IDE since it will provide JavaDoc tooltip, which is of course available and well detailed in such general Java classes).

Categories