How do I count an array until a certain integer(Java)? - java

I have a program where I have an array where the values are inputted by the user using Scanner, and then I need to add the value of all of the integers together. How would I go about doing this, as there isn't a set length for the array.

You can either prompt the user for the length of the array or define a certain value, e.g. -1, to signify the end of the input.
Option 1 (Demo):
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers do you want to sum?");
int len = sc.nextInt();
sc.nextLine();
int sum = 0;
for(int i = 0; i < len; i++){
sum += sc.nextInt();
sc.nextLine();
}
System.out.println("The sum is " + sum);
Option 2 (Demo):
Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers to sum. Enter -1 to stop.");
int sum = 0;
int num;
while((num = sc.nextInt()) != -1){
sc.nextLine();
sum += num;
}
System.out.println("The sum is " + sum);

Best approach would be storing integer values in list structure.
final List<Integer> values = new ArrayList();
The list structure dynamically expands after add new element:
values.add(newUserValue);
If you use Java in version 8 and above, you can use sum() method from Stream API:
final Integer sum = values.stream().mapToInt(Integer::intValue).sum();
If you use Java in version below 8 you can write function which iterates through every list element and sum them:
int sum(final List<Integer> values) {
int sum = 0;
for(final Integer value : values) {
sum += value;
}
return sum;
}

Related

Input inside Arrays (java)?

So, I have a very messy code. The purpose of the code is to find the minimum and maximum values of a set of numbers that the user entered using arrays. The problem is I don't know how to put the Array elements (Elements) into my array (numbersArray). Here's what I have so far :
package com.company;
import java.util.*;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner elements = new Scanner(System.in);
System.out.println("Enter in number of numbers:");
String num = elements.nextLine();
int numArrayElements = Integer.parseInt(num);
System.out.println("Enter in numbers please: ");
Scanner console = new Scanner(System.in);
String userInput = console.nextLine();
int Elements = Integer.parseInt(userInput);
int [] numbersArray = new int[numArrayElements];
int sum = 0;
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
numbersArray[i] = temp;
sum += temp;
}
Arrays.sort(numbersArray);
System.out.println((sum - numbersArray[numbersArray.length-1])
+ " " + (sum - numbersArray[0]));
}
}
How can I make it so that I can put Elements into numbersArray?
Your major problem is the part where you try to read values entered by the user:
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
...
}
The variable numArrayElements is of type int, you can't call a method nextInt on it, it does not exist.
The method, however, exists for objects of type Scanner, like your elements variable.
After that your code probably compiles and does something useful. At least you set the array items correctly by using
numbersArray[i] = temp;
I'm not that sure about the min/max part though. I don't get why you need the sum if you sort the array. After sorting you can just take the first (min) and last element (max) given by numbersArray[0] and numbersArray[numbersArray.length - 1].
And I'm not sure why you do the parsing stuff in between, does not seem necessary. Same holds for the second scanner, not needed since you already have one.
Let me show you a cleaner approach.
Scanner scanner = new Scanner(System.in);
// Amount of values
System.out.println("Enter amount of values:");
int amount = scanner.nextInt();
// Read values
System.out.println("Enter " + amount + " values:");
int[] values = new int[amount];
for (int i = 0; i < values.length; i++) {
values[i] = scanner.nextInt();
}
// Compute max and min
...
For the last part you have several options. The most efficient would probably be to remember it already at the moment where you read the values. Your sorting approach works too, but is much more work than needed since you don't need the order of all elements, you only need the min and max element.
Let's first do a manual approach
// Compute max and min
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int value : values) {
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
}
The second approach uses a built-in method which essentially does the same. However, it is less efficient since we will first need to built a Collection on top of the array and then do two iterations instead of only one (one for max, one for min). Also, due to the conversion we need wrapper objects Integer instead of primitive values int.
// Compute max and min
Collection<Integer> valuesAsColl = Arrays.asList(values);
int max = Collections.max(valuesAsColl);
int min = Collections.min(valuesAsColl);
The third approach uses the Java Stream API (since Java 8), looks elegant and does not need to convert stuff to Integer or Collection. But the two iterations instead of one remain.
// Compute max and min
int max = Arrays.stream(values).max();
int min = Arrays.stream(values).min();
I not understand your ask .. however this code for set array size from user and numbers of array by user..
public class JavaApplication2 {
public static int[] numbers() {
Scanner element = new Scanner(System.in);
System.out.print("please insert array long : ");
int count = element.nextInt();
System.out.print("enter numers : ");
element.nextLine(); // throw away the newline.
int [] numbers = new int[count];
Scanner numScanner = new Scanner(element.nextLine());
for (int i = 0; i < count; i++) {
if (numScanner.hasNextInt()) {
numbers[i] = numScanner.nextInt();
} else {
System.out.println("You didn't provide enough numbers");
break;
}
}
return numbers;
}
public static void main(String[] args) {
int[] numbersa = numbers();
System.out.println(Arrays.toString(numbersa));
}
}

How can I take multiple integer input from scanner and store each integer in separate arrays?

I'm trying to create a program which allows the user to addition as many pairs of numbers as they would like, by first taking user input to ask them how many sums they would like to complete (additions of 2 numbers), thereafter creating 2 arrays of whatever size the user has input, and then asking the user to input each pair of numbers on a single line that they would like to addition and storing the first value in one array and the second value in a second array from each input. This is where I am stuck, I don't know how I can take the user input as two int values on each line and store them in the respective indexes of each array to be added later. Please take a look at my code below:
import java.util.Scanner;
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
String[] input = new String[2];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
input = sc.nextLine().split(" ");
int[] intinput = Arrays.asList(input).stream().mapToInt(Integer::parseInt).toArray();
a = intinput[0];
b = intinput[1];
}
}
I think you need to change 2 lines this way:
a[i] = intinput[0];
b[i] = intinput[1];
You're using nextLine() method, which is useful for string input, but it's not the best solution for integer or other primitive data.
In addition, this line of code is wrong :
a = intinput[0];
because you're storing an integer value as integer array.
You must store that value inside a[i] in order to respect the variables type.
I'd do it this way:
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < a.length; i++) {
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
// Read pair and store it inside i-th position of a and b arrays
System.out.println("Enter first number: ");
a[i] = sc.nextInt();
System.out.println("Enter second number: ");
b[i] = sc.nextInt();
}
// Close scanner
sc.close();
// Prints every sum
for(int i = 0; i < a.length; i++){
System.out.println(i + "-th sum is: " + (a[i] + b[i]));
}
}
}
Here you read every pair with nextInt() which is specific for integer data.
Every time you store items in i-th position of arrays, so finally you can sum a[i] and b[i].
Result example:
Enter the amount of sums you would like to calculate:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
2
Enter second number:
1
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
3
Enter second number:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
5
Enter second number:
6
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
7
Enter second number:
8
0-th sum is: 3
1-th sum is: 7
2-th sum is: 11
3-th sum is: 15
Just read pairs with nextInt() method of scanner, it's use all space symbols like separator (not only end of line):
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
}
}

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

How to generate all numbers randomly between two given integers without duplication in Java?

I found answers on how to generate random numbers but nowhere how to generate all the numbers in the range without duplication in Java. Please share if you have a solution. Below is what I did but it simply generates randomly the numbers. I need to print out all numbers in the range without duplication!
package com.company;
import java.util.*;
public class RandomizeNumbers {
public static void main(String[] args) {
//Create Scanner
Scanner userInput = new Scanner(System.in);
//Ask for numbers N and M
System.out.println("Please enter two numbers and the program will randomize the numbers between them. " +
"The first number N must be bigger or equal to the second number M");
System.out.println("Please enter the first number N");
int n = userInput.nextInt();
System.out.println("Please enter the second number M");
int m = userInput.nextInt();
Random randomGenerator = new Random();
int difference = n - m;
//Randomize the numbers
if (m<=n){
for(int i = 0; i<= difference; i++ ) {
int randomInt = randomGenerator.nextInt(n - m + 1) + m;
System.out.println(randomInt);
}
}
else{
System.out.println("Please enter M less or equal to N");
}
}
}
What you need maybe generating a random permutation, pls see this link How to generate a random permutation in Java?
You can store generated number in a array.then after generate the next number check is there this number in array or no.
There are many ways to achieve this, lets suppose you want 50 numbers between A and B, then use a java.util.Set, since this collection does "ignore" duplicated values: following snippet describe it better:
Set<Integer> setA = new HashSet<Integer>();
Random r = new Random(System.currentTimeMillis());
int low = 10;
int high = 100;
int rnd = r.nextInt(high - low + 1) + low;
int maxCount = 50;
while (setA.size() < maxCount ) { //<--how many random numbers do you need?
rnd = r.nextInt(high - low + 1) + low;
setA.add(rnd);
}
and be careful, not to get in an infinite loop.
(there are only "B-A" possible integer options between A and B, so MaxCount<= B-A)
What I suggest you to do is to create a List and then shuffle it.
ArrayList<Integer> list = new ArrayList();
int high = 20;
int low = 10;
for(int i = low; i <= high; ++i)
list.add(i);
Collections.shuffle(list);
And then create a function to get a random Unique number each time.
static int index = 0;
public int roll(ArrayList<Integer> list)
{
return list.get(index ++);
}
You can put all the numbers between n & m into a list and then use Collections.shuffle(list) to make the numbers ordered randomly in the list.
if (difference > 0) {
List<Integer> integers = new ArrayList<>();
for (int i = 0; i <= difference; ++i) {
integers.add(m + i);
}
Collections.shuffle(integers);
for (Integer randNum : integers) {
System.out.print(randNum + "\t");
}
System.out.println();
} else {
System.out.println("Please enter M less or equal to N");
}

I am creating a small program in java which asks for 5 integers to inputted by the user and put into an array

This is the code that I have attempted, I can get the 5 integers into the array but my problem is validating that input and giving an error message when it is not. If I put in the 5 integers and they are in the required range it works and when I input a number that is not in the required the range I get an error message which is what I want but if I enter a symbol or letter my program crashes.
import java.util.Scanner;
public class QuestionNr1 {
public static void main(String[] args) {
//Keyboard Initialization
Scanner scanner = new Scanner(System.in);
//Declare an array to hold 5 integers values
int list[] = new int[5];
int i = 0;
int sum = 0;
System.out.println("Please enter 5 numbers within the range 1 - 20, with 1 being the lowest and 20 being the highest.");
while (i < 5) {
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = scanner.nextInt();
if (value >= 0 && value <= 20) {
list[i] = value;
i++;
} else {
System.out.println("Invalid input, please enter a number with the required range of 1 - 20.");
}
}
for (int j = 0; j < list.length; j++) {
int value = list[j];
}
double average = 0;
for (int i1 = 0; i1 < list.length; i1++) {
sum = sum + list[i1];
}
System.out.print("The sum total of your five entered numbers = " + sum);
}
}
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = Integer.MIN_VALUE;
if (scanner.hasNextInt()) int value = scanner.nextInt();
else System.out.println("Please make sure the value you entered is an integer.");
You should check that the user inserts an int before assuming so (scanner.nextInt();).
You are using scanner.nextInt(); so it is expected that the text entered will be int and if you enter other then int it will throw exception
I would use scanner.nextLine() and then try to convert String into int with NumberFormatException check:
int value;
String input = scanner.nextLine();
try {
value = Integer.valueOf(input);
} catch (NumberFormatException ex) {
System.out.println("Number format exception");
continue;
}
if (value >= 0 && value <= 20)
...
If you are doing Q1 for C2 paper in DCU than its the Sum total you display at the end not the average. I was going to do add another While loop after the scanner.nextint() to test the input is a valid integer. The 3 validations would be is number an integer and is it in range and the number of integers to be entered to the array is 5. I am thinking very similar to you, its adding the extra check and where is goes in the sequence.

Categories

Resources