Calling a scanner the number of times the user inputted in java - 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);

Related

How do I count an array until a certain integer(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;
}

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

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

Java Random Utility Generating Too Many 0's And Static Numbers

The line birthdays[j] = rnd.nextInt(365); seems to generate extra 0's in the int[] birthdays array. It also seems to add an EXTRA 0 into the array and generate static values depending on how many simulations I run and how many birthdays I generate. For instance, if I do 5 simulations and enter a 3 for the number of people in each simulation's "birthday pool" I always get an array of [0, 0, 289, 362].
Any help understanding the problem would be greatly appreciated.
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn);
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// Prompt user to provide the number of simulations and number of people and return them as an array
public static int[] promptAndRead(Scanner stdIn) {
int numberOfSimulations = 0;
while(numberOfSimulations < 1 || numberOfSimulations > 50000) {
System.out.println("Please Enter the number of simulations to do. (1 - 50000) ");
numberOfSimulations = stdIn.nextInt();
}
int sizeOfGroup = 0;
while(sizeOfGroup < 2 || sizeOfGroup > 365) {
System.out.println("Please Enter the size of the group of people. (2 - 365) ");
sizeOfGroup = stdIn.nextInt();
}
int[] simulationVariables = {numberOfSimulations, sizeOfGroup};
return simulationVariables;
}
// This is the method that actually does the calculations.
public static double compute(int numOfSims, int numOfPeeps) {
double numberOfSims = 0.0;
double simsWithCollisions = 0.0;
int matchingBirthdays = 0;
int[] birthdays = new int[numOfPeeps + 1];
int randomSeed = 0;
for(int i = 0; i < numOfSims; i++)
{
randomSeed++;
Random rnd = new Random(randomSeed);
birthdays = new int[numOfPeeps + 1];
matchingBirthdays = 0;
for(int j = 0; j < numOfPeeps; j++) {
birthdays[j] = rnd.nextInt(365);
Arrays.sort(birthdays);
}
for(int k = 0; k < numOfPeeps; k++) {
if(birthdays[k] == birthdays[k+1]) {
matchingBirthdays++;
}
}
if(matchingBirthdays > 0) {
simsWithCollisions = simsWithCollisions + 1;
}
}
numberOfSims = numOfSims;
double chance = (simsWithCollisions / numberOfSims);
return chance;
}
}
The line "birthdays[j] = rnd.nextInt(365);" seems to generate extra 0's in the int[] birthdays array.
Well, it doesn't. The array elements where zero to start with.
What that statement actually does is to generate a single random number (from 0 to 364) and assign it to one element of the array; i.e. the jth element. That is not what is required for your problem.
Now, we could fix your code for you, but that defeats the purpose of your homework. Instead I will give you a HINT:
The birthdays array is supposed to contain a COUNT of the number of people with a birthday on each day of the year. You have to COUNT them. One at a time.
Think about it ...
int arrays are by default initialized to 0 unless explicitly specified. Please see this Oracle tutorial about Arrays.
I found the problem myself. The issue was that having the "Arrays.sort(birthdays);" statement inside of a loop. That generated extra 0's.

ForLoop/Array Issue

I am having a little trouble figuring out what to do when it comes down to this project (generally the same for all my projects). I just want to know if I'm headed in the right direction also, I am not sure how to store the float number in the int double array. Thanks
Question & SampleOutput
Write a Java program that prompts the user to enter an integer. Use the integer as the  size for a new double array. Use a ​for loop to prompt the user to enter a floating point number for each element in the 
array, and store the number in the array.  Use a  second ​for loop to, calculate the average of all of the numbers and print it.  
Your  output should look something like the following: 
How many numbers will you enter: 5 
Enter a decimal value: 21.2 
Enter a decimal value: 3.7 
Enter a decimal value: 10.5 
Enter a decimal value: 2.6 
Enter a decimal value: 101.123 
The average is 27.824599999999997
My current code:
import java.util.*;
public class Loops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
int[][] Array = new int[numberOfTimes][];
for(int i = 0; i < Array.length; i--)
{
System.out.print("Enter a decimal value: ");
float value = input.nextInt();
Array[i][
{
}
}
}
}
PS: My apologies for bad formatting. New to Stack.
Sir,
The major mistake you're committing is considering double as two. 'Double' is also a data type just like integers and float. So you need only a one dimensional array to store the values which are of type 'double'.
Secondly, i would suggest you to try to completing the code yourself once. If you're having issues in compiling it or getting wrong output, feel free to post the code online.
The desired result could have been achieved with only one 'for' loop, but I've provided the code 2 'for' loops only for the clarity.
Here's the code-
import java.util.Scanner;
public class AverageNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
double AverageMean = 0;
double[] Array = new double[numberOfTimes];
// Doing the first loop as suggested
for(int i = 0; i < numberOfTimes; i++)
{
System.out.print("Enter a decimal value: ");
Array[i] = input.nextDouble();
}
// Doing the second loop as suggested
for(int i = 0; i < numberOfTimes; i++)
{
AverageMean = AverageMean + Array[i];
}
System.out.println("The average is " + AverageMean/5);
}
}
And the desired output will be-
How many numbers will you enter: 5
Enter a decimal value: 21.2
Enter a decimal value: 3.7
Enter a decimal value: 10.5
Enter a decimal value: 2.6
Enter a decimal value: 101.123
The average is 27.824599999999997
Hope it helps..
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
float[] input = new int[numberOfTimes];
for(int i = 0; i < numberOfTimes; i++) {
System.out.print("Enter a decimal value: ");
float value = input.nextInt();
Array[i] = value;
}
}
1) You need a double array instead of a two dimensional int array to store double.
2) Use input.nextDouble(); to take a double input.
3) for(int i = 0; i < Array.length; i--) will cause i to decrease negative which will next create ArrayIndexOutofBound exception at Array[i].
4) There are some other errors, better try the following code.
Try this:
import java.util.*;
public class Loops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
double[] Array = new double[numberOfTimes];
double sum = 0;
double average = 0;
for (int i = 0; i < numberOfTimes; i++) {
System.out.print("Enter a decimal value: ");
double value = input.nextDouble();
Array[i] = value;
sum += value;
}
average = sum / numberOfTimes;
System.out.print("The average is: " + average);
}
}
Output:
How many numbers will you enter: 5
Enter a decimal value: 21.7
Enter a decimal value: 3.7
Enter a decimal value: 10.5
Enter a decimal value: 2.6
Enter a decimal value: 101.123
The average is: 27.924599999999998

Categories

Resources