How do I break up my numbers into multiple lines? - java

Run the program with starting number=13, upper bound= 112, step_size=3
Continue printing numbers as long as number
I've tried to split it and use break without success for this task.
public class Bounds {
public static void main(String[] args) {
int startingNumber;
int upperBound = 112;
int stepSize =3;
int count =0;
Scanner input = new Scanner(System.in);
System.out.println("Enter starting number: ");
startingNumber=input.nextInt();
System.out.println("Enter upper bound number");
upperBound = input.nextInt();
System.out.print(startingNumber + " ");
System.out.print(" ");
while (startingNumber <= upperBound) {
System.out.print((startingNumber += stepSize) + " ");
if ((count%10) == 0)
count += 3;
System.out.print( " ");
input.close();
}
}
}

too complicated, what about using a for loop
public static void main(String[] args) {
int startingNumber;
int upperBound = 112;
int stepSize =3;
int count =0;
Scanner input = new Scanner(System.in);
System.out.println("Enter starting number: ");
startingNumber = input.nextInt();
System.out.println("Enter upper bound number");
upperBound = input.nextInt();
int range = upperBound - startingNumber;
for (int i = startingNumber; i < upperBound; i+=stepSize) {
System.out.println(i);
count++;
}
System.out.println("done: count value: "+count);
}

What did you have in mind for the following?
if ((count%10) == 0)
count += 3;
So you only increment count when the remainder is zero. That would only work once. But what other action do you take? Perhaps you meant do do something like this.
count += 3;
if ((count%10 == 0) {
System.out.println();
}

Related

How to initialize variable back to 0 in a while loop in java?

I want my code to loop, but reinitialize the variable back to 0. Every time I input a number, it add it to the previous result, but I want it to reset. I attached two images below. One is the actual output and the other is the expected output.
import java.util.Scanner;
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
int sum = 0;
int total = 1;
int n = 0;
while (true) {
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
Actual Output
Desired Output
You can use continue
if(n == 0) {
sum = 0;
total = 1;
continue;
}
You can initialize the variables inside the while loop
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
while (true) {
int sum = 0;
int total = 1;
int n = 0;
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
To zero a variable, simply assign 0 at the appropriate point.
sum = 0;
An appropriate place to insert this statement for your desired output is immediately before the first for loop. Likewise, reset total before the second for.
However, a much better way to write this is to declare the variable where it is needed, as you have done for x and y. This applies to am, sum, total and n
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("enter an integer number: ");
int n = input.nextInt();
if (n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
String am = input.nextLine();
if (am.equals("a")) {
int sum = 0;
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
int total = 1;
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
I don't know if I fully understand your question, but just do sum=0; and total=1; after you print out the final result. You should also consider doing a try/catch statement for robustness on the nextInt so that characters and strings don't break your program...
try {
n = input.nextInt();
}
catch (Exception e) {
System.out.println("Not a Number");
}

How to create array to ask user to enter a certain amount of numbers and then take the average

Program asks the user to enter amount of numbers to average
Creates a new array of the size as amount of numbers (max)
It stores each number in an array entry
Prints the numbers entered
5 numbers on a line (use print)
Put a println appropriately (use % check)
Print the average of all the numbers
This is what i need to do but I don't think I'm starting right as I am new to java
This is what I have so far:
import java.util.Scanner;
public class AnyAverageArr {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[] arr1 = new int[max];
for (int i = 0; 1<= max; i++) {
arr1[i] = input.nextInt();
}
System.out.println("Average of All is " + arr1[max]);
}
}
If I'm not mistaken, this is what you need (explanation comes in comments):
try (Scanner input = new Scanner(System.in)) {
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[] arr1 = new int[max];
for (int i = 0; i < max; i++) {
arr1[i] = input.nextInt();
}
for (int i = 1; i <= max; i++) {
System.out.print(arr1[i - 1] + " ");
if (i % 5 == 0) {
System.out.println();
}
}
System.out.println();
double sum = 0.0;
for (int i = 0; i < max; i++) {
sum += arr1[i];
}
System.out.println("Average: " + (sum / max));
} catch (Exception e) {
e.printStackTrace();
}
You should definitely read about the for loop in java. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
You should also read about what average means.
https://www.reference.com/math/average-mean-mathematics-b2fb5e4b69989ed8
Here is a simple quick fix to your code
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int sum = 0;
for (int i = 0; i< max; i++) {
sum += input.nextInt();
}
System.out.println("Average of All is " + sum / max);
You first need to save all the elements in an array.
Then you need to calculate the sum.
Divide the sum with the total number of elements.
Here is a fix for your code:
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int numberOfElements = input.nextInt();
int[] arr = new int[numberOfElements];
int sum = 0;
for (int i = 0; i< numberOfElements; i++) {
arr[i] = input.nextInt();
sum += arr[i];
}
System.out.println("Average of All is " + sum / numberOfElements);
I have used the same loop to save the elements in the array and compute the sum at the same time.
Hope this solves your problem
I understood your requirement and i updated little in your source code.
I believe below points you may follow.
User enters a max number
User want to enter numbers for avarage and that you need to store into an array.
Sum array elements and find the avarage of it.
Refer the below source code exactly what you want.
public class StackOverflow {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[] arr1 = new int[max];
for (int i = 0; i < max; i++) {
arr1[i] = input.nextInt();
}
int sum = 0;
for(int num : arr1){
sum = sum + num;
}
double avg = sum/max;
System.out.println(" Avarage : " + avg);
}
}
import java.util.Scanner;
//here is your edited code
public class AnyAverageArr {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[] arr1 = new int[max];
//since array starts from 0, we need to loop less than max
//i< max : so loop will terminate when we will have input equals to max numbers
for (int i = 0; i< max; i++) {
arr1[i] = input.nextInt();
}
int sum=0;
//loop again through array and calculate the sum of each number
for(int v:arr1) {
sum+=v;
}
//divide sum by total number of inputs to get the answer
System.out.println("Average of All is " + sum/max);
}
}
------------------------------------------------------------------------
You can try the following code:
public class StackOverflow {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.print("Please enter the max number: ");
int max = input.nextInt();
// Creates a new array of the size as amount of numbers (max)
int[] arr1 = new int[max];
double sum = 0.0;
// It stores each number in an array entry
for (int i = 0; i < max; i++) {
arr1[i] = input.nextInt();
sum += arr1[i];
}
// Prints the numbers entered
// 5 numbers on a line (use print)
// Put a println appropriately (use % check)
for (int i = 0; i < max; i++) {
System.out.print(arr1[i] + " ");
}
// Print the average of all the numbers
System.out.println();
System.out.println("Average of all is " + sum / max);
}
}
}

Create a java program to display multiples of a number

I'm trying to Write the main method of a Java program that has the user enter two integers, i and n. If either integer is less than 2, output “Please enter numbers above 1.” Otherwise, output the n positive multiples of i, separated by spaces.
I'm close but can't figure out how to do display the multiples.
Here's what a sample run should look like:
Enter i: 4
Enter n: 6
6 multiples of 4 are: 8 12 16 20 24 28
import java.util.*;
public class HW5Problem3 {
public static void main (String [] args) {
int i = 0;
int n = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter i: ");
i = input.nextInt();
System.out.print("Enter n: ");
n = input.nextInt();
if ((i <= 1) || (n <= 1)) {
System.out.println("Please enter numbers above 1");
System.exit(1);
}
System.out.print(n + " multiples of " + i + " are: ");
}
}
import java.util.Scanner;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int i = 0;
int n = 0;
//It's use to verify the inputs (i and n).
do{
System.out.print("Enter i :");
i = input.nextInt();
System.out.print("\nEnter n :");
n = input.nextInt();
if(i >= 1 || n <= 1){
System.out.println("Please enter numbers above 1 \n");
}
}while(i <= 1 || n <= 1);
System.out.print(n + " multiples of " + i + " are: ");
for (int counter = 0 ; counter < n ; counter++) {
System.out.print(i*(2 + counter) + " ");
}
}
You'll need to create a loop (for loop or while loop) to iterate from 2 to n+1, and multiply i by your loop variable, outputting each value inside the loop
U can use following method in that class
public static void mult(int i,int n){
int[] arr=new int[n];
int count=2;
for(int x=0;x<n;x++){
arr[x]=i*count++;
}
for(int y=0;y<arr.length;y++){
System.out.print(arr[y]+" ");
}
and now your final code looks like
import java.util.*;
public class HW5Problem3 {
private int i = 0;
private int n = 0;
public static void main(String[] args) {
int i = 0;
int n = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter i: ");
i = input.nextInt();
System.out.print("Enter n: ");
n = input.nextInt();
if ((i <= 1) || (n <= 1)) {
System.out.println("Please enter numbers above 1");
System.exit(1);
} else {
System.out.print(n + " multiples of " + i + " are: ");
mult(i, n);
}
}
public static void mult(int i, int n) {
int[] arr = new int[n];
int count = 2;
for (int x = 0; x < n; x++) {
arr[x] = i * count++;
}
for (int y = 0; y < arr.length; y++) {
System.out.print(arr[y] + " ");
}
}
}
n is the multiplier, i is the factor, right? In programming the multiplier is the loop maximum:
System.out.print(n + " multiples of " + i + " are: ");
for (int inc=1; inc<=n; inc++) {
System.out.print(" " + i*inc);
}
This prints out: 4 8 12 16 20 24
If you really want to have this as output: 8 12 16 20 24 28 copy/paste this line:
for (int inc=2; inc<=(n+1); inc++)

Not printing perfect numbers

Here is my code :-
package javaapplication;
import java.util.Scanner;
public class perfect02 {
public static void main(String args[]) {
int i = 1, sum = 0;
System.out.println("Enter maximum range : ");
Scanner kb = new Scanner(System.in);
int a = kb.nextInt();
System.out.println("Enter minimum range : ");
Scanner kb2 = new Scanner(System.in);
int b = kb2.nextInt();
System.out.println("perfect number in the given range are :");
for (int n = b; n <= a; n++) {
while (i < n) {
if (n % i == 0) {
sum = sum + i;
}
i++;
}
if (sum == n)
System.out.println(+n + " ");
}
}
}
Why program is not printing perfect numbers ?
I have checked code many times but i am unable to find the solution .Please tell me what is going wrong in my code .Thanks in advance
Any help would be appreciated ....
Here, I looked into the perfect number generation and fixed it for you!
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter minimum range : ");
int b = kb.nextInt();
System.out.println("Enter maximum range : ");
int a = kb.nextInt();
kb.close();
System.out.println("Perfect number in the given range are :");
for (int n = b; n <= a; n++) {
int sum = 0;
int i = 1;
while (i < n) {
if (n % i == 0)
sum = sum + i;
i++;
}
if (sum == n)
System.out.println(n + " is perfect");
}
}
You should've had the sum and i variables declared inside the for loop, so they would be reset for each number!

While loop even count

my problem is the following. If I input number 2, the code counts it as an odd number.
Remainder for 2 / 2 = 0 so the error doesn't make sense.
Below is the program:
import java.util.Scanner;
public class Ohjelma {
public static void main(String[] args) {
// Tänne voit kirjoittaa ohjelmakoodia. Ohjelmasi voit ajaa
// valitsemalla menusta Run->Run File tai painamalla Shift+F6
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int number = Integer.parseInt(reader.nextLine());
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
while (number != -1) {
System.out.println("Type numbers: ");
sum = sum + number;
number = Integer.parseInt(reader.nextLine());
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + many);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
The main problem is that for the critical part of your program it largely ignores the first input, apart from adding it to the running sum. You want to recast it like this:
Scanner reader = new Scanner(System.in);
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
do {
System.out.println("Type numbers: ");
number = Integer.parseInt(reader.nextLine());
if (number == -1)
break;
sum = sum + number;
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
} while (true);
This will certainly processes even and odd numbers correctly.
Your code reads the second line of input into number before it checks whether number is odd ... and -1 is odd.

Categories

Resources