I'm having some trouble getting the correct output format for my homework. Here it is:
Write a program that accepts an integer n and an integer m from user and that prints a
complete line of output reporting the first m multiples of n. For example, if user input is:
m = 5, n = 3;
It should produce this output:
The first 5 multiples of 3 are 3, 6, 9, 12, and 15.
This is what I have so far:
import java.util.*;
public class Assignment2Part3 {
public static void main (String[] args) {
//declaring the two variables being entered
int n = 0;
int m = 0;
//declaring answer variable
int a = 0;
//declaring scanner input
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number you want to find multiples of");
n = input.nextInt();
while(true) {
System.out.println("Please enter the amount of multiples you want to see");
m = input.nextInt();
if (m <= 0) {
System.out.println("Please enter an integer greater than zero");
}
if (m > 0) {
break;
}
}
System.out.println("The first "+n+ " multiples of "+m+" are: ");
for (int i=1; i<=m; i++) {
a =i*n;
System.out.println(a);
}
}
}
This is what the output looks like right now:
Please enter the number you want to find multiples of
3
Please enter the amount of multiples you want to see
5
The first 3 multiples of 5 are:
3
6
9
12
15
How do I get the output to look like "The first 5 multiples of 3 are 3, 6, 9, 12, and 15." ?
NOTE: This assignment is for an introductory course and we have just covered for loops.
Printing them out on one line.
By changing System.out.println to System.out.print you can make multiple prints display on the same line.You also need to print a separator (", ") before every number (except the first), so that the numbers don't just pile up on top of each other.
Before the last number, you want to print "and".
You can do by altering the behaviour when the loop is at the final step (which is when i==m).
This gives something like this:
System.out.println("The first "+m+ " multiples of "+n+" are: ");
for (int i = 1; i <= m; ++i) {
if (i > 1) {
System.out.print(", ");
if (i==m) {
System.out.print("and ");
}
}
System.out.print(i*n);
}
System.out.println(".");
Related
I'm currently working on a college Java project, and I'm stuck. Here's the assignment details for context:
Write a function that accepts integer num and displays all lower
numbers composed only with digits 1 and/or 3. (This program can accept
any integer value as an input and provide a proper output)
Test your function in a Java application program.
Sample run 1:
Enter an integer: 10
All the numbers lower than 10 and composed only with digits 1 and/or
3: 3, 1
Sample run 2:
Enter an integer: 20
All the numbers lower than 20 and composed only with digits 1 and/or
3: 13, 11, 3, 1
Note 1: This program should only accept positive integer values.
Note 2: All the outputs should be in the same line, separated with a
comma. You should not consider a comma after the last output.
So far, this is what I have made:
import java.util.Scanner;
public class IntManipulator
{
public static void main (String[]args)
{
//initialize new system.in scanner object named input
Scanner input = new Scanner(System.in);
//prompt user to input an integer and use scanner object to store the integer in myInt
System.out.print("Enter an integer: ");
int myInt = input.nextInt();
//function call
intMethod(myInt);
//close input scanner object
input.close();
}
static void intMethod(int myInt)
{
System.out.print("All the numbers lower than " + myInt + " and composed only with digits 1 and/or 3: ");
for(int i=myInt; i>0; i--)
{
if()
{
System.out.print(i+", ");
}
}
}
}
Where I'm stuck right now, is as to what to put in my if() statement in my intMethod function's for loop, so that I can only print the values of i that contain 1 and/or 3.
I would use an iterative approach here, starting with 1 up until, but not including, the input number. Then, loop over each number and ensure that every digit be 1 or 3, using the modulus:
public static void intMethod(int myInt) {
for (int i=1; i < myInt; ++i) {
int num = i;
while (num > 0) {
if (num % 10 != 1 && num % 10 != 3)
break;
num /= 10;
}
if (num == 0) {
System.out.println("MATCH: " + i);
}
}
}
For an input of intMethod(50), the following output was generated:
MATCH: 1
MATCH: 3
MATCH: 11
MATCH: 13
MATCH: 31
MATCH: 33
My project is to show lines with cardinals, from an initial number and
then varying this number to another number entered.
It starts by asking for a initial number of cardinals (the output must be "###" the number of times asked) and then ask for the final number of cardinals to add. So case, click here 5 initial cardinals and add 3, the program must show a line with 5, another with 6, another with 7 and another with 8 cardinals.
How do I add the cardinals? With if-else?
import java.util.Scanner;
public class P02Cardinais {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number inicial of cardinals: ");
int numCardinais = keyboard.nextInt();
System.out.println("Enter the number of cardinals to add: ");
int numCardinaisAdd = keyboard.nextInt();
int i;
for (i = 0; i < numCardinais; i++) {
System.out.print("#");
} System.out.print(" - " + numCardinais);
keyboard.close();
}
}
Example of the output
(number inicial - 2 ; number to add - 3)
## - 2
### - 3
#### - 4
##### - 5
You need 2 loops
one for the number of lines from initial to initial+add
one for the number of # which has to be the index of first loop (limo of j is i)
for (int i = numCardinais; i <= numCardinais+numCardinaisAdd; i++) {
for (int j = 0; j<i; j++) {
System.out.print("#");
}
System.out.println(" - " + i); // new line and index
}
I am trying to display numbers divisible by two user-input integers using a 'for' loop statement. For example, if I were to input 5 and 30, I would get an output of "5 10 15 30". I've got the very basic setup so far, but I'm stuck right here. How can I use the variables to divide by each other within the loop statement?
import java.util.Scanner;
public class practice4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N_small= 0, N_big = 0;
System.out.printf("Enter the first number: ");
N_small = in.nextInt();
System.out.printf("Enter the second number: ");
N_big = in.nextInt();
if (N_small < N_big) {
for (int i = N_small; i == N_big; i++){
//Issue here! ***
System.out.printf("The numbers are: %d\n", i);
}
}
}
}
An example output in-case I'm not clear enough:
----------- Sample run 1:
Enter the first number: 5
Enter the second number: 30
The numbers are: 5 10 15 30
Bye
and
----------- Sample run 3:
Enter the first number: 7
Enter the second number: 25
The numbers are:
Bye.
Any help is greatly appreciated, thanks!
well if the first input is 5 and the second is 30
and the output is 5 10 15 30 (you are incrementing by (the first input)5 )
so if you input 10 and 25 the output should be 10 20 25 incrementing by (the first input).
if this is what you are trying to explain then your code should look like this
Scanner in = new Scanner(System.in);
int N_small= 0, N_big = 0 ,i;
System.out.printf("Enter the first number: ");
N_small = in.nextInt();
System.out.printf("Enter the second number: ");
N_big = in.nextInt();
if (N_small < N_big) {
System.out.printf("The numbers are:");
for (i = N_small; i < N_big+1 ; i=i+N_small){
if(i > N_big) System.out.println(N_big); else System.out.println(i);
}
}
}
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
NOTE: (I do not need anyone to write the whole program for me, I only need the algorithm!)
I need to create a program that prompts the user to enter two integers. The program then needs to list all the even numbers in between the two inputed integers and output the sum. And then the same for the odd numbers. (using While loops)
I will then need to rewrite the code to use a do-while loop, and then rewrite it AGAIN using a for loop.
Here is an example of what the result should look like:
Enter an integer: 3
Enter another integer larger than the first: 10
Even Numbers: 4, 6, 8, 10
Sum of even numbers = 28
Odd Numbers: 3, 5, 7, 9
Sum of odd numbers = 24}
I tried starting off with the even numbers with something like this, but it just gets stuck at the first number, even if the first number is even.
import java.util.Scanner;
public class EvenOddSum_While {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num1 = keyboard.nextInt();
System.out.println("And another: ");
int num2 = keyboard.nextInt();
while (num1 < num2){
while (num1 %2 == 0){
System.out.print(num1 + ", ");
num1++;
}
}
}
}
The inner while has no end criteria, you need if there instead. Also, your num1++ Statement must be in the outer while loop, not the inner one.
Also, there is no real algorithm here, you're struggling with the language itself ;)
General advice: either run through your code with a step-by-step debugger, virtually every IDE has one OR place excessive log /System.out.println statements in your code to understand what it's doing
When you said 'in between' did you mean including the two integers? Because you did include them. Okay. So do this.
int x = 0;
int y = 0;
int even = 0;
int odd = 0;
int evenx = 0;
int oddx = 0;
int evena = 0;
int odda = 0;
Scanner scan = new Scanner(System.in);
//Prompts the user to input the first number
x = scan.nextInt();
//Prompts the user to input the second number
y = scan.nextInt();
for(int i = x;i<y;i++,x++;){
if(x%2 = 0){
even = even + x;
evenx++;
}
if(x%2 = 1){
odd = odd + x;
oddx++;
}
}
evena = even/evenx;
odda = odd/oddx;
//print it out. There. The algorithm.
God. Do this site have auto-format?