Java loops- display every integer between two integers - java

I am new to coding and have been trying to understand loops. I am working on a sample project that says to Write an application that prompts a user for two integers and displays every integer between them. Display a message if there are no integers between the entered values. Make sure the program works regardless of which entered value is larger. I for the most part have it but am having an issue with the output.
import java.util.Scanner;
public class Practice2 {
public static void main(String[] args) {
int num1;
int num2;
Scanner input= new Scanner(System.in);
System.out.println("Input one integer");
num1= input.nextInt();
System.out.println("Enter another integer");
num2= input.nextInt();
while(num1<num2) {
num1 += 1;
System.out.println(num1);
}
while(num2<num1){
num2+=1;
System.out.println(num2);
}
}
}
A sample output would be
Input one integer
1
Enter another integer
9
Then this is the output
2
3
4
5
6
7
8
9

As you are incrementing value first so you can try this approach
import java.util.Scanner;
public class Practice2 {
public static void main(String[] args) {
int num1;
int num2;
Scanner input= new Scanner(System.in);
System.out.println("Input one integer");
num1= input.nextInt();
System.out.println("Enter another integer");
num2= input.nextInt();
while(num1<num2-1) {
num1 += 1;
System.out.println(num1);
}
while(num2<num1-1){
num2+=1;
System.out.println(num2);
}
}
}

You can use a for-loop for this purpose. Though you would need to include some logic to ensure that num1 is the smaller of the two numbers.
Note the num1 + 1 is there to make the first number non-inclusive.
A for-loop is broken down into 3 components
start: i = num1 + 1
condition: i <= num2
ensure i is less than or equal to num2
action: i++
after each iteration, i will be incremented by 1
import java.util.Scanner;
public class Practice2 {
public static void main(String[] args) {
int num1;
int num2;
Scanner input= new Scanner(System.in);
System.out.println("Input one integer");
num1 = input.nextInt();
System.out.println("Enter another integer");
num2 = input.nextInt();
for (int i = num1 + 1; i <= num2; i++) {
System.out.println(num2);
}
}
}

I used this method to get a perfect score.
import java.util.Scanner;
public class Inbetween {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
int x, y, X, Y;
X = input.nextInt();
Y = input.nextInt();
if (Y+1 == X || X+1 == Y ){
System.out.print("There are no integers between " + X + " and " + Y);
}else if (Y>X){
for(x=X+1; x<Y; ++x)
System.out.print(x+" ");
}else if (X>Y){
for(y=Y+1; y<X; ++y)
System.out.print(y+" ");
}
}
}

Related

Average of numbers program outputting incorrect result

Am trying to write simple program to find average of 3 int values, but it always seems to get the average wrong
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num1 + num3)/3));
}
}
Help is greatly appreciate
Besides having num1 twice and missing num2, as already mentioned above, you will always get integer-results only, e.g. for num1 = 1, num2 = 2 and num3 = 2 your code will plot 1 as result instead of 1.667. You might enforce double-results in your output by writing
System.out.println("The average is:"+ ((num1 + num2 + num3) / 3.0));
It's supposed to be:
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num2 + num3)/3));
}
}
You accidentally added num1 twice, and forgot num2.

Unsure what to use for a sentinel controlled while loop - Java

I'm currently a beginner in Java Programming.
I'm having a little bit of trouble with my while loop that has a sentinel value.
Everything works until I add the while loop, however it's required so I can exit when the value '999' is entered.
I'm also not sure what to add for the 'if' values.
Any help would be appreciated!
import java.util.Scanner;
public class SumAverage {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.printf("Please Enter the first number%n");
int num1 = keyboard.nextInt();
System.out.printf("Please enter the second number%n");
int num2 = keyboard.nextInt();
System.out.printf("Please enter the third number%n");
int num3 = keyboard.nextInt();
int sum = num1 + num2 + num3; //calculates sum
int average = (num1 + num2 + num3) / 3; //calculates average
while (num1 != ) {
if (sum > 1)
System.out.printf("Sum: %s %nAverage: %s", sum, average);
else if (sum < 1)
System.out.printf("Sum: %s %nAverage: %.2f", sum, average);
}
}
}
You can do it in the following manner:
import java.util.Scanner;
public class SumAverage {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
int input,sum,avg,count;
do{
System.out.printf("Please enter number" + (count+1) + "%n");
input = keyboard.nextInt()
sum += input;
count += 1;
avg = sum/count;
}while(input != 999);
//Do whatever is to be done once sentinel is input.
}
You can modify the while loop as follows
while(num1 !=999 || num2 !=999 || num3 !=999)
|| is used as OR operator. So whenever any input value is 999 the loop wont execute.

Using a for loop to read ONLY 5 numbers and average them. JAVA

Really having issues with this program I'm making. I've searched this site and a few others, although have yet to find a solution. It may look like I'm just soliciting help but I truly am stuck. I am to make a program that reads in 5 numbers from the user and average those numbers. My extent of knowledge of Java is the Scanner class and for loops, yet haven't used while loops yet. Here is the very poorly written code:
public class Average5
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int num;
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
num = sc.nextInt();
}
I honestly have no clue what to do. More or less self taught.
public class Average5 {
public static void main(String args[]) {
int numlenngth = 5;
double total = 0;
Scanner sc = new Scanner(System.in);
for (int num1 = 0; num1 < numlenngth; num1++) {
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : " + (total / numlenngth));
}
}
output >>
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 2
Average : 1.2
For calculating exact average, you need to take double(sum) instead of int and add(sum) everytime with the user value.
public class Average5
{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to enter for calculating average: ");
int totalCount = sc.nextInt();
double sum=0;
for(int i= 0; i<totalCount; i++)
{
System.out.print("Please enter a number: ");
sum += sc.nextDouble();
}
System.out.println("Average of number is"+(sum/totalCount));
}
This is almost the same as the others posted, but it is limited to entering only 5 numbers and it takes care of possibly resulting floating number in the final division:
import java.util.Scanner;
public class Average5 {
private static final int TOTAL = 5;
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
double sum = 0;
System.out.format("You have to enter %d numbers now.\n", TOTAL);
for (int cnt = 1; cnt <= TOTAL; cnt++) {
System.out.format("Please enter number %d of %d: ", cnt, TOTAL);
sum += scanner.nextInt();
}
System.out.format("The average is %f.\n", sum / TOTAL);
scanner.close();
}
}
Here you can use the array to store the numbers:
public class Average5 {
private static final int MAX = 5;
public static void main(String[] args) {
int[] numbers = new int[MAX];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < MAX; i++) {
System.out.println("Please type the number");
numbers[i] = sc.nextInt();
}
float average = getAverage(numbers);
System.out.println("The average of the five numbers: " + average);
}
public static float getAverage(int[] arg0) {
int sum = 0;
float Ret = 0.0f;
if(arg0 != null) {
for(int i = 0; i < MAX; i++) {
sum += arg0[i];
Ret = sum / MAX;
}
return Ret;
}
}
This is not the only way to slove this problem.
int num = 0;
float total = 0f;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : "+(total/num));

Program that reads num and prints from 1 to num

i need help in logic, i need the program to read an integer from user and then prints all the integers from 1 to num1. here's what i got :
import java.util.Scanner;
public class test
{
public static void main(String []args)
{
Scanner scan = new Scanner(System.in);
int num1;
int num2;
System.out.println("Enter any number:");
num1 = scan.nextInt();
while (num1<=num2) {
System.out.println(num+1);
}
}
}
Try this out:
import java.util.Scanner;
class test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Enter any number:");
// Note : The below statement will fail if user does not enter integer value
number = scan.nextInt();
// You can use while loop as well but for loop provides cleaner approach for iteration
for (int i = 1; i <= number; i++) {
// Print numbers sequentially from 1 to number
System.out.println(i);
}
}
}
Program that reads num and prints from 1 to num
Try,
System.out.println("Enter any number:");
num1 = scan.nextInt();
int i=1;
while (i<=num1) {
System.out.println(i);
i++;
}
do like this
int num1=0;
int num2=0;
System.out.println("Enter any number:");
num1 = scan.nextInt();
while (num2 <= num1) {
System.out.println(num2);
num2++;
}
thanks alot guys! its been couple of years since last i coded a java program so im a little rusty! here's my final code :
import java.util.Scanner;
public class test
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int num;
int a=1;
System.out.println("Enter any number:");
num=scan.nextInt();
while (a<=num)
{
System.out.println(a);
a++;}
}}

Add Problems In java

I want to take input of two variable as integer and than do addition with the two variables.
The ans will stored in another variable. The program will repeat after every addition end and will ask for user input of varibles and will do addition again.
My qus is taht how can i add all aditions ans again:
Exm:
Input a= 5
Input b=5
ans=10
Agin program will ask for
Input a= 6
Input b= 6
ans=12
now how can i take all " ans " value with program and do additions of all "ans"
Final Ans=10+12=22
code:
import java.io.*;
import java.util.Scanner;
public class math{
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
System.out.println("\nans is :"+c);
math ob_m=new math();
ob_m.add();
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
}
}
The code just do addition one after another but i want that it will do one more task that ....
It all add all aditions reasuts also. how can i do it?
import java.io.*;
import java.util.Scanner;
public class Test {
int a;
int b;
int sum = 0;
public void add() {
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
sum = sum + (a + b);
System.out.println("\nans is :" + (a + b));
}
public static void main(String args[]) {
Test ob_main = new Test();
while (true) {
ob_main.add();
}
}
}
Just keep adding the intermediate sums to another variable, so at the end you get the final total.
Another alternative (though not preferable when simple solution is available) is to put these sums in a list and at the end iterate through the list and calculate the final total.
Also, do not use ob_m.add(); - just call add();
Store every answer in an additional variable. Then when you're done, sum all the answer variables
You can use a loop for repeating your action, and store each addition in a total sum?
Change
public void add() {
Scanner keyboard = new Scanner(System.in);
int a;
int b;
int total = 0;
for(int i = 0; i < 2; i++) {
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c = a+b;
total += c;
}
System.out.println("\nans is :"+total);
}
Have a total variable which you just keep adding c to.
I also changed your unneeded recursion into a while-loop.
public class math
{
public static void main(String args[])
{
int total = 0;
Scanner keyboard = new Scanner(System.in);
while (true)
{
System.out.print("\nEnter a (-999 to quit): ");
int a = keyboard.nextInt();
// terminating condition, modify appropriately
if (a == -999)
break; // break out of the while-loop
System.out.print("Enter b: ");
int b = keyboard.nextInt();
int c = a + b;
total += c;
System.out.println("\nans is: " + c);
}
System.out.println("total is: " + total);
}
}
have a field GrandSUM,
GrandSum = 0;
and after every addition, add ans to it.
GrandSum += ans;
at the end , GrandSum will have result you want.
Edit:
import java.io.*;
import java.util.Scanner;
public class math{
int GrandSum = 0;//added
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
GrandSum += c;//added
System.out.println("\nans is :"+c);
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
//.....repeat as many times you want
ob_main.add();
System.out.println("grandsum: " + ob_main.GrandSum);
}
}
package farzi;
import java.util.ArrayList;
import java.util.Scanner;
public class dummy {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> sum = new ArrayList<Integer>();
String choice = "";
do{
System.out.println("enter the first number");
int a = keyboard.nextInt();
System.out.println("enter the second number");
int b = keyboard.nextInt();
int tempSum = a+b;
list1.add(a);
list2.add(b);
sum.add(tempSum);
System.out.println("Do you want to continue : type yes or no");
choice = keyboard.next();
}while(choice.toLowerCase().charAt(0)=='y');
System.out.println("here are the inputs with theri sum");
System.out.println("num1\t num2\t sum");
for(int i=0;i<list1.size();i++)
{
System.out.println(list1.get(i)+"\t"+list2.get(i)+"\t"+sum.get(i));
}
}
}

Categories

Resources