How to write Java statement to display integers between 2 numbers? - java

I am new to java coding. I have written the code below to the problem: How can I write a statement that can be used in a Java program to read two integers and display the number of integers that lie between them, including the integers themselves?
I couldn't run it in Eclipse. When I try to run it through Eclipse, it tells me "The selection cannot be launched, and there are no recent launches. Anyway, can someone please tell me if this code correct? Are there any errors in it?
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:10");
int first = s.nextInt();
System.out.print("Enter the second integer:20");
int second = s.nextInt();
System.out.println("How many integers are between "+first+" and "+second+"???");
}
}

Please put some more effort on your query, for sure you can come up with your answers by yourself and you will learn faster. For now You can refer to below answer.
package com.barnwal.jeetendra.learn;
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:");
int first = s.nextInt();
System.out.print("Enter the second integer:");
int second = s.nextInt();
System.out.println("How many integers are between " + first + " and "
+ second + "???");
// To print number of integer between entered number
if (second > first) {
System.out.println("Answer : " + (second - first - 1));
// To print the numbers
for (int i = first + 1; i < second; i++)
System.out.print(i + " ");
} else {
// To print number of integer between entered number
System.out.println("Answer : " + (first - second - 1));
// To print the numbers
for (int i = second + 1; i < first; i++)
System.out.print(i + " ");
}
}
}

To avoid the unnecessary if-else statement to look which value is bigger, you can also use the functionality of the class java.lang.Math like this
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:");
int first = s.nextInt();
System.out.print("Enter the second integer:");
int second = s.nextInt();
int small = Math.min(first, second) ;
int big = Math.max(first, second);
System.out.println("How many integers are between " + small + " and " + big + "???");
System.out.println("Answer : " + (big - small + 1));
// To print the numbers
for (int i = small; i <= big; i++)
System.out.print(i + " ");

You can use looping like this:
if (first > second){
big = first;
small = second;
}
else if (second > first){
big = second;
small = first;
}
for (int i = small; i <= big; i++)
System.out.print(i + " ");

first of all, when you use resources (System.in) you should close them. You can do it with try-finally or you can use try-with-resources.
Here is your code:
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
try (Scanner s = new Scanner(System.in)){
System.out.print("Enter the first integer:10");
int first = s.nextInt();
System.out.print("Enter the second integer:20");
int second = s.nextInt();
System.out.println("How many integers are between "+first+" and "+second+"???");
if (first != second)
System.out.println("Answer: " + Math.abs(first-second - 1));
else
System.out.println("Answer: 0");
}
}
}

How about this:
int diff = second - first - 1;
let secont = 25 and first = 23 so the output will be:
25-23-1 = 1;
which is 24

Related

I'm having issue with the output with this particular code

This is the code:
import java.util.Scanner;
public class javapractice {
public static void main(String[] Args) {
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number :");
int number = input.nextInt();
boolean nextint = input.hasNextInt();
if (nextint) {
count++;
XX += number;
} else {
break;
}
input.nextLine();
}
int YY = XX/count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();
}
}
I want the output to print the sum of the numbers entered and when I enter let's say a word like "Hello", it breaks out of the loop and prints Sum 0 0 and AVG = 0.
The issue I'm having is that whenever I enter the number, it asks me for it two times and doesn't take the next number in the row after that and whenever I enter a string variable lets say "I", it outputs Inputmismatch. What would be the fix to this?
Don't mix nextLine() and all the other next methods; pick one. If you want to read a line's worth of text, just call next(), but if you want the input to flow as 'everytime a user hits enter, read another token', which you usually do, update the definition of 'what defines a token?': scanner.useDelimiter("\r?\n");.
Try this code:
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number: ");
if (input.hasNextInt()) {
count++;
XX += input.nextInt();
} else {
break;
}
}
int YY = XX / count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();

Counting occurrences of integers in an array program java

I am trying to find the occurrences of all integers submitted by the user into the program and so far here's what I got. It works but I don't think it's a legit way to do it, is there any way I can try to do this without using the list[10]=9999;? Because if I don't do it, it'll show out of boundary error.
import java.util.*;
public class OccurrencesCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[11];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++){
list[i] = scan.nextInt();
list[10] = 9999;
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<11;i++){
if(list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
Personally, I think this is a perfectly good solution. It means that you can deal with the last group in the same way as all others. The only change I would make is putting the line list[10] = 9999; outside the for loop (there's no reason to do it 10 times).
However, if you want to use an array of length 10, you can change the line
if(list[i-1]==list[i])
to
if(i < 10 && list[i-1]==list[i])
If you do this, you won't get an ArrayIndexOutOfBoundsException from list[i] because the expression after the && is not evaluated when i == 10.
import java.util.*;
class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] list = new int[101];
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++) {
int x = scan.nextInt();
list[x]++;
}
for(int i = 1; i <= 100; i++)
if(list[i] != 0)
System.out.println(i + " occurs " + list[i] + " times ");
}
}
To store count of numbers from 1 to 100 you need to use a list of 100 integers each one storing the number of occurrences of itself. Better approach would be to use a Map.
I have made use of ArrayList and Collections package instead of regular arrays as a different flavor if it interests you check it out.
import java.util.*;
public class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for (int i = 0; i < 10; i++) {
list.add(scan.nextInt());
}
Collections.sort(list);
Integer prevNumber = null;
for (int number : list) {
if (prevNumber == null || prevNumber != number) {
int count = Collections.frequency(list, number);
System.out.println(number + " occurs " + count + (count > 1 ? " times." : " time."));
}
prevNumber = number;
}
}
}
I got it figured out guys, only changed a couple of small things inside the conditions and everything went smoothly! Thanks for the help! Now I just need to find a way to restrict the inputs from going above 100.
import java.util.*;
public class CountOccurrences
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[10];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<=9;i++){
list[i] = scan.nextInt();
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<=10;i++){
if(i<=9 && list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}

Printing out elements at certain indexes in vectors in Java

This is probably very basic stuff, but I am not too sure how I should ask questions because I am very new to this, so here goes.
I am practicing vectors and what we can do to them. I have prompted the user for the elements of the vectors (per my directions) among other things successfully. For my next step, I have to "print out the element at index i in each of the two vectors." I was given the methods which I am supposed to use, but the explanations I saw of them were very unclear. Here they are:
Object get (int which)
Object remove (int which)
set (int index, object element)
How would I get the system output to be the element at the index i?
package vectorusage;
import java.util.*;
public class VectorUsage {
public static void main(String[] args) {
Vector a = new Vector ();
Vector b = new Vector ();
System.out.println (a);
System.out.println (b);
Scanner input = new Scanner(System.in);
String first;
System.out.print("Please enter 4 strings.");
first = input.next();
a.add (first);
String second;
second = input.next();
a.add (second);
String third;
third = input.next();
a.add (third);
String fourth;
fourth = input.next();
a.add (fourth);
String fifth;
System.out.print("Please enter 4 more strings.");
fifth = input.next();
b.add (fifth);
String sixth;
sixth = input.next();
b.add (sixth);
String seventh;
seventh = input.next();
b.add (seventh);
String eighth;
eighth = input.next();
b.add (eighth);
System.out.println("Vector a is size " + (a.size()) + " and contains: " + (a));
System.out.println("Vector b is size " + (b.size()) + " and contains: " + (b));
int i;
System.out.println("Please enter an integer.");
i = input.nextInt();
System.out.println("Element at index " + i + " in Vector a is: " + ;
Avoid using vectors, they are deprishiated. Use ArrayList instead.
Using a for loop you can simplify your code like below,
(Please note, this code does not validate user input or do error handling)
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Please enter 8 strings.");
for(int i = 1; i <= 8; i++) {
System.out.print("Please enter strings #" + i + ": ");
numbers.add(input.nextInt());
}
for(int j = 0; j < numbers.size(); j++) {
System.out.println("Number at index " + j + " is " + numbers.get(j));
}
}
}
I usually use a mix of while and for loop. The while loop is used to add the user input into the vector. The for loop prints out the elements of the vector using index i. I've set it to print all the elements of the vector but you can modify it by using if conditions. Here's my code, hope it helps!
import java.util.*;
import java.io.*;
public class VectorUsage {
public static void main(String[]args) {
Scanner input=new Scanner(System.in);
Vector a=new Vector();
int count =0;
while(count<4)
{
System.out.print("Enter a string: ");
a.addElement(input.nextLine());
count++;
}
for(int i=0;i<a.size();i++)
{
System.out.println(a.elementAt(i));
}
Vector b=new Vector();
int count1=0;
while(count1<4)
{
System.out.print("Enter a string: ");
b.addElement(input.nextLine());
count1++;
}
for(int i=0;i<b.size();i++)
{
System.out.println(b.elementAt(i));
}
}
}

sum the second to the last on java

How can I print the sum of the 2nd to the last digit of each integer on java?
(so, 8 would be printed since 1 + 3 + 4 is 8 , and 35 would be printed since 3453 + 65324 + 354) in the following Program: * without using if statements *
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumSecToLast;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
sumSecToLast = (num1/10) % 10 + (num2/10) % 10 + (num3/10) % 10;
System.out.print((num1/10) % 10 + " + " + (num2/10) % 10 + " + " + (num3/10) % 10 + " = " + sumSecToLast);
}//main
}//Pr6
Once you've scanned all the integers:
//In main method:
int secLast1 = Pr6.getSecLastDigit(num1);
int secLast2 = Pr6.getSecLastDigit(num2);
int secLast3 = Pr6.getSecLastDigit(num3);
int sum = secLast1 + secLast2 + secLast3;
System.out.println(secLast1 + " + " + secLast2 + " + " + secLast3 + " = " + sum);
You also want to create the additional method:
private static int getSecLastDigit(int num) {
return (num / 10) % 10;
}
Here is how I would do it. Depending on your definition of an if statement this might not work for you (spoiler).
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int total = 0;
String num1, num2, num3;
System.out.print("Please write an integer: ");
num1 = scan.nextLine(); // rather than taking an integer this takes a String because it is easier to extract a single element.
... // get the other numbers
for (int i = 1; i < num1.length(); i++){
total += Character.getNumericValue(num1.charAt(i)); // adds each number to the total
}
... // do this for the other Strings (or use another loop for with a String[])
System.out.println(total);
}//main
}//Pr6
To make this more concise I would highly recommend using a String[] rather than 3 different variables. Also I am assuming a for loop doesn't count as an if statement. However I realize that because of the boolean check they may be considered too similar for your current situation. I hope this helps! :)
Sorry for inconvenience. My question was misunderstood. I meant that I want to write a code to find the sum of the 2nd to the last digit of a three different integers. For ex: if the user entered 15, 34, and 941, which in this case the 2nd to the last digit will be 1, 3, and 4. Therefore, the subtotal of them will be 1+3+4 = 8.
I found out the answer and I wanted to share it with everyone, and also I would like to thank all of those who tried to help.
thank you..
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumSecToLast;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
sumSecToLast = ((num1/10) % 10) + ((num2/10) % 10) + ((num3/10) % 10);
System.out.println("The subtotal of the 2nd to the last digit = " + sumSecToLast);
System.out.println();
}//main
}//Pr6

Changing the variable assigned everytime a loop iterates

I am trying to build a program that allows the user to enter length and width of an object however many times I choose (I would build more code to choose how many times the loop goes). I am having some problems figuring out how to get input and construct an object every time the loop iterates. Thanks!
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
for (int i = 1; i <= 2; i++)
{
System.out.println("Enter length" + i + ": ");
int length i = console.nextInt();
System.out.println("Enter length" + i + ": ");
int width i = console.nextInt();
OBJECT instance1 = new OBJECT(length1, width1);
}
}
You can use ArrayList/LinkList, if your entries are big then only go for LinkList.
Scanner console = new Scanner(System.in);
System.out.println("Enter how many records you want: ");
int j = console.nextInt(); //"Loop will run "+ j +" times"
List<ObjectName> objectList = new ArrayList<ObjectName>();
int length = 0;
int width = 0;
for (int i = 1; i <= j; i++)
{
System.out.println("Enter length" + i + ": ");
length = console.nextInt();
System.out.println("Enter width" + i + ": ");
width = console.nextInt();
ObjectName instance1 = new ObjectName(length, width);
objectList.add(instance1);
}
You need to understand how to use the Collections API, in particular List, LinkedList and ArrayList. So your code would become:
public static void main(String[] args) {
final Scanner console = new Scanner(System.in);
final List<Area> objectList = new ArrayList<Area>();
for (int i = 0; i < 2; i++) {
System.out.println("Enter length" + (i + 1) + ": ");
final int length = console.nextInt();
System.out.println("Enter width" + (i + 1) + ": ");
final int width = console.nextInt();
final Area instance = new Area(length, width);
objectList.add(instance);
}
}
I've choosen ArrayList here because it is normally the better performing one of the two (but for relatively small lists that do not require the functionality of either one, both will do).

Categories