How to divide a variable multiple times - java

I would appreciate any help.
So the prompt was to create a program with integers userNum and x as inputs and have the output be userNum divided by x a certain amount of times(in my case, let's say 4).
This is the code I have so far which works finely for dividing userNum by X but it only does it once when I need it be done however many times is specified. Any advice?
public class LabProgram
{
public static void main(String[] args)
{
int userNum;
int x;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
x = scnr.nextInt();
System.out.println(userNum / x);
}
}
If my input 2000 2, I only get 1000 as an output when my required output is 1000 500 250 125.

You will need to use some form of loop such as a for loop.
public static void main(String[] args)
{
int userNum;
int x;
int times;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
x = scnr.nextInt();
times = scnr.nextInt();
for(int i = 0; i < times; i++){
userNum /= x;
}
System.out.println(userNum);
}
You may want to make userNum a double as integer division will result in truncation of decimal values by removing the decimal portion.

I think it's time for you to use something called a 'loop'.
Something like:
for (int i = 0; i < 4; i++) {
}
Put some parts of your code inside this loop and magic will appear.

Here, You can use loops here if you want to divide number 4 times then you can use for loop and if you want to divide UserNum until value of UserNum is not equals to 0 then you can use while loop.

Related

How to write a program which can continuously ask users for inputs until the inputs meet a specific requirement to run the code?

I have to write a program that starts by requesting an integer in the range 0 < N < 20. Numbers outside this range are rejected and a new request is made. Output the sum of the sequence of numbers starting at 1 and ending with N.
I have got most of the codes but I can not continuously ask users for inputs until an input meets the requirement. I tried to use "return" in line 11, however, it does not go back into the loop after getting another input. What should I do now?
import java.util.*;
class ExamTesterNine{
public static void main(String args[]){
Scanner kbReader= new Scanner(System.in);
int num=kbReader.nextInt();
System.out.println("Enter an integer smaller than 20 and larger than 0");
int result;
int sum=0;
if (!(num>0&&num<20)){
return;
}else{
for(int i=1; i<=num; i++)
sum=sum+i;
int [] number= new int [num];
for (int a=0; a<(number.length-1); a++ ){
number[a]=a+1;
System.out.print(number[a]+"+");}
System.out.print(num+"="+sum);
}
}
}
IT should be easy with do-while. I am not on my compiler right now however this you should add in your code if you are using scanner
import java.util.*;
class ExamTesterNine{
public static void main(String args[]){
Scanner kbReader= new Scanner(System.in);
int num = 0;
System.out.println("Enter an integer smaller than 20 and larger than 0");
do{
num=kbReader.nextInt();
} while(num<0 && num <20);
int result;
int sum=0;
for(int i=1; i<=num; i++)
sum=sum+i;
int [] number= new int [num];
for (int a=0; a<(number.length-1); a++ ){
number[a]=a+1;
System.out.print(number[a]+"+");}
System.out.print(num+"="+sum);
}
}
}
Let me know if it don't I can get on the compiler quickly however do-while is solution for you.
you will need a while loop as you do not know how many times the wrong input will be entered
while (true) {
System.out.println("Enter an integer smaller than 20 and larger than 0");
int num=kbReader.nextInt(); // get input
// test
if (goodInput (num)) {
break;
}
}
There are many different ways to approach this. However, as a start to become familiar with while loops, I recommend this simple method:
System.out.println("Enter an integer smaller than 20 and larger than 0");
int num = kbReader.nextInt();
while(num > 20 || num < 0)
{
System.out.println("That value does not meet the criteria. Please try again:");
num = kbReader.nextInt();
}
Until the correct value is entered, the user will be asked to retry their input.
To get a number, try using a check like this
int number=0;
boolean flag;
while{
flag=false;
System.out.println("Enter a number smaller than 20 and greater than 0 : ");
try{
number=kbReader.nextInt();
flag=true;
}catch(Exception e){ //catching the exception that occurs when an input other than integer is entered
System.out.println("OOPS!!!only Integer is allowed :-(");
}
if(flag==true && number>0 && number<20){
break;
}else{
if(flag){
System.out.println("Oops!!!only numbers in the range 0<number<20 is allowed...Re-enter again");
}
}
import java.util.*;
class ExamTesterNine{
static int num;
public static void readInput() {
System.out.println("Enter an integer smaller than 20 and larger than 0");
Scanner kbReader= new Scanner(System.in);
num=kbReader.nextInt();
if (!(num>0&&num<20)){
ExamTesterNine.readInput();
}else {
calculate(num);
}
}
public static void calculate(int sum) {
for(int i=1; i<=num; i++)
sum=sum+i;
int [] number= new int [num];
for (int a=0; a<(number.length-1); a++ ){
number[a]=a+1;
System.out.print(number[a]+"+");}
System.out.print(num+"="+sum);
}
public static void main(String args[]){
int result;
int sum=0;
ExamTesterNine.readInput();
}
}
Are you expecting this?
Out put:Enter an integer smaller than 20 and larger than 0
23
Enter an integer smaller than 20 and larger than 0
34
Enter an integer smaller than 20 and larger than 0
56
Enter an integer smaller than 20 and larger than 0
45
Enter an integer smaller than 20 and larger than 0
15
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15=135

Finding the sum of the odds in between two numbers inclusive

I am writing a simple program to find the sum of the odd numbers in between two inputted numbers, and I would appreciate any feedback. I've been working at this problem for a long time, and I could use some expertise.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = s.nextInt();
System.out.print("#2: ");
int num2 = s.nextInt();
int sum = 0;
for(int i= num1; i<(num2-num1); i++){
if (i%2 != 0){
sum+=i;
}
}
System.out.print();
}
}
There are a few simple errors that you can fix in your code here. First, it should not be (num2-num1), but rather just num1. Also, make sure you print your result in the last statement. In contrast, there are many other ways to attack this problem, but if you fix these few issues, your simple method will work just fine.
I would test if num1 is even first, if it is add one to make it odd (otherwise, it's already odd). Then increment by 2, so you know every i is odd. Next, your loop test should be <= num2 (not < num2 - num1), because you want the range from num1 to num2 inclusive. Finally, don't forget to actually print the result. Like,
if (num1 % 2 == 0) {
num1++;
}
int sum = 0;
for (int i = num1; i <= num2; i+=2) {
sum += i;
}
System.out.println(sum);
Alternatively, in Java 8+, you might do it with an IntStream like
System.out.println(IntStream.rangeClosed(num1, num2).filter(x -> x % 2 != 0).sum());
You can also apply some math instead of looping through all the numbers, which is much more efficient and becomes a constant time algorithm instead of linear time.
To get the sum of the numbers you can multiply the average between both numbers by the count of elements in the range.
If any of both numbers is odd, you can add one, or substract one to reach the first even number in the range, so you calculate from an even to an even number.
Example: from 3 to 12, you will use 4 and 12. Average is 8. And you have (12-4)/2 + 1 = 5 even numbers in the range (the +1 is because it's inclusive range). The sum will be 8*5=40.
Which is true: 4+6+8+10+12 = 40
import java.util.Scanner;
class SumOfOdds
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = s.nextInt();
System.out.print("#2: ");
int num2 = s.nextInt();
if (num1 % 2 == 0)
{
num1++;
}
int sum = 0;
for (int i = num1; i <= num2; i+=2)
{
sum += i;
}
System.out.println(sum);
}
}

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);

Calling a scanner the number of times the user inputted in java

This is one of my very first java projects and I'm trying to make a mini calculator and right now I'm working on addition.
What I want it to do is like it will ask the user how many numbers they want to add and then after you type all the numbers, and the java code has to get all the numbers that inputted.
Here's the addition part that doesn't work so far:
private static void Addition() { //I already added the Scanner plugin
System.out.println("How many numbers would you like to add?");
Scanner adds = new Scanner(System.in);
int addsput = adds.nextInt();
Scanner numa = new Scanner(System.in);
for(int addloop=1; addloop>addsput; addloop++) {
int numaput = adds.nextInt();
//somehow I want to get all the numbers
}
//Here I want to add all the numbers they typed
}
So I hope you get the idea. Any help would be great, because I've been searching for about an hour to get this figured out. Thanks.
You have two options, either read the values into an array, or find the sum as you read the values.
You only need one Scanner object, and your for loop had some issues:
private static void addition() {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to add?");
int amountNumbers = input.nextInt();
int sum = 0;
for (int counter = 0; counter < amountNumbers; counter++) {
sum += input.nextInt();
}
System.out.println("Sum: " + sum);
}
Using an array:
private static void addition() {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to add?");
int[] numbers = new int[input.nextInt()];
for (int index = 0; index < numbers.length; index++) {
numbers[index] = input.nextInt();
}
int sum = 0;
for (int index = 0; index < numbers.length; index++) {
sum += numbers[index];
}
System.out.println("Sum: " + sum);
}
Here is a more advanced way to do it using IntStream from Java 8:
private static void addition() {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to add?");
int amountNumbers = input.nextInt();
int sum = IntStream.generate(input::nextInt)
.limit(amountNumbers)
.sum();
System.out.println("Sum: " + sum);
}
Here are a few things I would recommend changing:
You only need 1 scanner. And as for adding to a sum, if you make the variable before the loop, you can just add to the sum in the same line you take input.
You also had the < sign mixed up with a > sign. You want the loop to go until the variable addloop has been incremented the amount of times the user wants to input a number to add. Therefore, the loop should continue until it reaches the number the user entered, rather than the other way around.
System.out.println("How many numbers would you like to add?");
Scanner adds = new Scanner(System.in);
int addsput = adds.nextInt();
int sum = 0;
for(int i = 0; i < addsput; i++){
sum += adds.nextInt();
}
System.out.println(sum);

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