User input and finding multiples - java

I'm new to java and I have an assignment asking to prompt user for a number between 2 and 10 and it is supposed to print out multiples of that number. It is also supposed to use a for loop.
I think I have the general idea with the for loop I'm just trying to figure out how to do the multiples. Any help is greatly appreciated! This is where I am so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter a number between 2 and 10:");
for(int i = 2; i<= 100; i++){
System.out.println(+ i);
}

I suggest thinking about how you would go about doing the task mentally. When you're counting integers, you will add one each time (i++). When you're counting by, say threes, you will add three each time. You need to store your scanner's read value to a variable (don't try to read the scanner each time!) and adjust i++ in your loop to add the number you read from the scanner instead.
Begin with:
int step = in.nextInt();
if(step >= 2 && step <=10){
for(int i = 0; i <=100; ???){
System.out.println(+ i);
}
} else {
System.out.println("The step value was not between 2 and 10.");
}
I will leave you at this point as learning it for yourself is far more valuable than any Stack Overflow answer could ever be. If you are still stumped, I can guide you farther in the right direction.

You should ensure that the user can only enter numbers between 2 and 10, and you will need to store the input for use in your for loop. For example:
int num = 0;
Scanner in = new Scanner(System.in);
do
{
System.out.print("Please enter a number between 2 and 10:")
num = in.nextInt();
System.out.println();
} while((num < 2) || (num > 10));
Followed by your for loop.

A multiple of a number is that number times something.
So one multiple of i would be i * 13 (for example).
of course you need to get number from the Scanner "in" object
for (int i=2; i < 13; i++) {
System.out.println(" Multiple (" + i + ") = " + i*number;
}

Related

Need Java to loop only one time and create a single column/row

This is for an assignment, and is specifically requested. I know it seems somewhat pointless to create a nested for loop that only executes once, so wanted to clarify that.
The assignment question is a bit confusing to me, but states:
"Write a Java program that uses two nested FOR loops. The values used in the outer loop will be a user input value. The inner loop will use the input value divided by 2. Print a simple statement showing the values using the range of 1 to the user input number in the outer loop. The inner loop will print 1 to the divided result." However, the rubric states, "Student properly uses Java and creates a nested FOR loop and prints proper row and column number."
I initially thought I only needed to divide the input value by two and print that value, but now I feel like I'm supposed to print the input value in a simple row and column format? (If anyone else has clarity on this, please don't hesitate to drop a comment)
Basing my code on this, I'm having a really difficult time getting it to execute only once, and also having an issue printing a proper row and column. I'm attaching my attempt at the code below (this is an into-level course, fyi). Any feedback/help would be greatly appreciated!
import java.util.Scanner;
class rowCol {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
sc.close();
System.out.println(" \t1");
for (n = 0; n < 1; n++) {
for (n = 0; n < 1; n++) {
System.out.println("1 \t" + n);
}
System.out.println();
}
}
}
I think he meant that the outer for loop should run till n ( value entered by user ) and inner for loop will run till n/2 ( divided value )
class rowCol {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
sc.close();
// System.out.println(" \t1");
int val = n/2;
for (int i = 1;i<=n; i++) {
// printing from range 1 to n in the outer loop
System.out.print(i);
for (int j = 1; j<=val; j++) {
// printing from 1 to divided value in the inner loop
System.out.print(" \t" +j);
}
System.out.println();
}
}
}
When you run it , it gives output in this format .
Right now you are accepting the value from the user in the variable n and then later changing it to 0 in the loop. Doing this you are loosing the input you took from the user. You won't be able to calculate the n/2 if you loose what you accepted from the user in the first place.
You'll have to define different variables/counters for your two loops. Your outer loop will go from 1 to the number you accepted and the inner one will go from 1 to the half of the number you accepted from the user.
Your final code should look something like this (for illustration purposes only):
import java.util.Scanner;
class rowCol {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
sc.close();
for (int row = 1; row <= n; row++) {
// Print Row Number
System.out.print("Row: " + row + "\t");
for (int col = 1; col <= n/2; col++) {
// Print Column Number
System.out.print("Column: " + col + "\t");
}
// Print New Line
System.out.println();
}
}
}

How do I create a program that calculates the sum of a set of numbers (Java)?

I'm learning Java from a MOOC and am stuck on this one exercise:
Really having trouble with this one. I'm able to create a program that counts up to the user's chosen number (below) but stuck on how to add all the numbers up to variable n.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int start = 0;
System.out.println("Until which number? ");
int n = Integer.parseInt(reader.nextLine());
System.out.println("Counting begins now...");
while (start <= (n - 1)) {
System.out.println(start += 1);
}
}
Any help is appreciated.
You on the right track, firstly to get input on the same line (like in the expected output of your task) use print rather than println.
Then basically just keep track of two "helper" variables count and sum and only print the value of the variable sum once outside the while loop:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Until what?");
int n = scanner.nextInt();
int count = 0;
int sum = 0;
while(count <= n) {
sum += count; // increment the sum variable by the value of count
count++; // increment the count variable by 1
}
System.out.println("Sum is " + sum);
}
}
N.B. Also above I have made use of the Scanner method nextInt() rather than your Integer.parseInt solution, in the future you may want to look into pairing this with hasNextInt() that returns a boolean to ensure your program does not crash if the user inputs something other than an Integer.
Example Usage 1:
Until what? 3
Sum is 6
Example Usage 2:
Until what? 7
Sum is 28
Try it here!
int sum = 0;
while (start <= n) {
sum += start;
++start;
}
System.out.println(sum);
According to your guidelines you need to keep a record of the number of iterations start and you need to calculate the sum stored in its own variable sum.
start needs to increment every iteration
sum needs to be its previous value plus the current value of start

Subtraction using while loop Java

So i'm trying to write a programme whereby the user enters two integers .
The programm is supposed to subtract 5 from the second integer entered in a loop depending on the first number entered. (so the first number should dictate how many times it will loop.
public int getScheme1() {
while (Mark >= 20) {
System.out.printf((Mark = Mark - 5) + Mark + " ");
}
for (int Day = 1; Day <= 20; Day++) {
System.out.printf("( " + Day + "):" + Mark + " ");
}
return Mark;
}
All my code does is print the user's second input integer 20 times.
Also im sorry im totally new to java
you must call this function in your main program.
public int getScheme1 (int num1, int num2){
for(int i = 1 ; i >= num1 ; i++ ){
num2 -= 5;
}
return num2;
}
to call it simply use getScheme1(num1,num2);
Based on what you described, you are looking for something like this:
Scanner input = new Scanner(System.in); //create a scanner to get user input
int a1 = input.nextInt(); //get 2 ints from the user
int a2 = input.nextInt();
for(int i = 0; i < a1; i++) { //loop as many times as a1 specifies
a2-=5; //subtract 5 from a2 each time it loops
}
System.out.println(a2);
The key part of this is the for loop, which works in the following:
for(variable; condition; increment),
basically, what the for loop I wrote is saying:
Set i = 0 at the start. If i is meeting the condition (in this case being less then a1), then loop. The increment part is called when it finishes running the code block, it now makes i bigger (in this case 1 bigger using ++) Another important thing to note is that the first time the loop runs, i = 0.
So for example, if I wanted to loop 10 times, with a starting variable of 3 and incremented 5 each time, I'd do:
for(int i = 3; i <= 53; i+=5) {}
Also, one last thing: please look at variable naming conventions, variables shouldn't start with caps like that, they should be camelCase

Read in 5 numbers from a user and compute the frequency of positive numbers entered

Having difficulty trying to write code for this problem above. Please find the code below. Have to read in 5 numbers and compute the frequency of positive numbers entered.
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive integer");
int number = input.nextInt();
for(int i = -2 ; i < 4 ; i++)
System.out.println("Positive Count is: " + i);
}
}
Your problem is that you have a task that needs to be repeated (about the user entering a value); but your loop (the perfect mean to do things repeatedly) ... doesn't cover that part!
for(int i=-2 ; i<4 ; i++)
System.out.println("Positive Count is: " +i);
Instead, do something like:
for (int loops = 0; loops < 5; loops++) {
int number = input.nextInt();
Then of course, you need to remember those 5 values, the easiest way there: use an array; Turning your code into:
int loopCount = 5;
int numbers[] = new[loopCount];
for (int loops = 0; loops < loopCount; loops++) {
numbers[loops] = input.nextInt();
And then, finally, when you asked for all numbers, then you check the data you got in your array to compute frequencies. A simple approach would work like this:
for (int number : numbers) {
if (number > 0) {
System.out.println("Frequency for " + number + " is: " + computeFrequency(number, numbers));
}
with a little helper method:
private int computeFrequency(int number, int allNumbers[]) {
...
Please note: this is meant to get you going - I don't intend to do all your homework for you. You should still sit down yourself and figure what "computing the frequency" actually means; and how to do that.
Try this one, Remember if you only want to know the frequency(not storing)
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
int i = 1;// is a counter for the loop
int positive =0;// counts positive numbers
while(i<=5){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a whole positive number");
int number = input.nextInt();
if(number > 0){
positive ++;
}
i++;
}
System.out.println("Positive Count is: "+ positive);

not a statement error, illegal start of type

import java.util.*;
public class ulang {
public static void main(final String[] args) {
int a;
int b;
int sum;
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
a = in.nextLine();
System.out.println("Enter num 2: ");
b = in.nextLine();
{
sum = a + b;
}
for (i = 0; i < 5; i++) {
(sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}
}
}
I'm weak on looping especially in Java. So I need some corrections on my coding, but I have no idea how to fix it.
The coding should run like this: User need to insert 2 numbers and the program will calculate the sum of both number. After that, the program will determine if the total of sum is >=10 or <10. If the sum >=10, "Congratulations" will appear but if it is <10, then "The sum of number less than 10" will appear. How to fix it?
This is the immediate problem:
(sum>=10)
I believe you meant that to be an if statement:
if (sum>=10)
Additionally:
You're trying to use an in variable, but the Scanner variable is called scan
Scanner.nextLine() returns a String - I suspect you wanted Scanner.nextInt()
Your for loop uses a variable that hasn't been declared. You probably meant:
for (int i = 0; i < 5; i++)
A few other suggestions though:
The sum isn't going to change between the loop iterations... why are you looping at all?
You've got a new block in which you're calculating the sum, but for no obvious reason. Why?
It's generally a good idea to declare variables at the point of initialization, e.g.
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
int a = scan.nextInt();
System.out.println("Enter num 2: ");
int b = scan.nextInt();
int sum = a + b;
Given that you want to take the same basic action (writing a message to the screen) whether or not the user was successful, you might consider using the conditional operator like this:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
System.out.println(message);
That would then allow you to refactor the loop to only evaluate the condition once:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
for (int i = 0; i < 5; i++)
{
System.out.println(message);
}
(sum>=10)
This line needs an if at the beginning, or it won't be read as a branch.
if (sum >= 10)
You also should name your main-class Ulang, because java class identifiers should start with an upper case letter, for readability.
The loop should look like the following:
for (int i = 0; i < 5; i++) {
The first part defines the counter and assigns zero to it. The second is your condition and the last counts for you.
for (int i = 0; i < 5; i++) {
if (sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}

Categories

Resources