I am building an array that ask how many different inputs you have, then allowing you to enter each input. At the end I want to sum them up, but I keep getting an error.
Also when I go above 5 inputs, I lose one..... For example when I respond to the first question: Enter "10". When I start adding different numbers in it stops at nine. Please help.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int[] numArr = new int[size];
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i<numArr.length; i++)
{
numArr[i] = input.nextInt();
}
int totalSum = numArr + totalSum;
System.out.print("The sum of the numbers is: " + totalSum);
Change your logic and code to the following:
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
System.out.println("Enter the number of CUs for each course: ");
int totalSum = 0;
for (int i = 0; i < size; i++) {
totalSum+=input.nextInt();
}
System.out.print("The sum of the numbers is: " + totalSum);
try
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int totalSum = 0;
for (int i=0; i< size; i++)
{
System.out.println("Enter the number of CUs for each course: ");
int cuNum = input.nextInt();
totalSum += cuNum ;
}
System.out.print("The sum of the numbers is: " + totalSum);
Pretty sure your intended result is
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int[] numArr = new int[size];
int totalSum = 0;
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i<numArr.length; i++)
{
numArr[i] = input.nextInt();
totalSum += numArr[i];
}
System.out.print("The sum of the numbers is: " + totalSum);
}
Your other code didn't work mainly because of
int totalSum = numArr + totalSum;
You can't define totalSum to defines itself! And you can't just use numArr... numArr is an array - you have to access indexes, not the array as a whole!
Related
import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
line = in.nextLine();
System.out.print("Input Number 1: " );
line = in.nextLine();
System.out.print("Input Number 2: ");
line = in.nextLine();
System.out.print("Input Number 3: " );
line = in.nextLine();
System.out.print("Input Number 4: ");
line = in.nextLine();
System.out.print("Input Number 5: " );
line = in.nextLine();
}
public static void sortAscending (double[]arr)
{
Arrays.sort(arr);
System.out.printf("Sorted arr[] = %s",
Arrays.toString(arr));
}}
I am stuck on what the code is for putting the what the user inputs in ascending order. I have looked up and tried multiple resources on ascending order but nothing seems to work. I tried:
System.out.print("Input number 1: "+(i+1+":");
to try and add the inputs instead of writing all of them out but i was an unknown variable.
You should use an array to store input and a loop to read input.
System.out.print("How many numbers you want to input?: ");
int num = in.nextInt();
double[] arr = new double[num];
for(int i = 0; i < num; i++){
arr[i] = in.nextDouble();
}
sortAscending(arr);
You have to create an array. Then put the stuff you are reading into the array and after that call your method.
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
sortAscending(values);
Note that the name sortAscending is not accurate, it is not just sorting (and then returning the result or in-place), but also printing. So maybe you should rename it to sortAndPrintAscending. Or just sort it and let your main method to the printing.
Or drop it completely, the method does not really serve any purpose as it is just calling Arrays.sort, might as well do that in main:
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
Arrays.sort(values);
System.out.println("Sorted: " + Arrays.toString(values));
i wrote a code using array and method that allow the user to enter any number of numbers and
display the numbers sorted from the smallest number to the largest number however the program works but it doesn't show the numbers here is the code that i wrote
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers you want to enter? ");
int size = s.nextInt();
int i;
double[] numbers1 = new double[size];
System.out.println("Enter " + numbers1.length + " numbers: ");
getNumbers(numbers1);
double[] numbers2 = new double[numbers1.length];
for (i = 0; i < numbers1.length; i++) {
numbers2[i] = numbers1[i];
}
displayNumbers(numbers1);
System.out.println("The numbers after sorting are: ");
sortNumbers(numbers2);
displayNumbers(numbers2);
}
public static void getNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
}
}
public static void sortNumbers(double[] numbers) {
double temp;
double pass;
for (pass = 0; pass < numbers.length; pass++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
}
}
}
}
public static void displayNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
System.out.print(numbers + " ");
}
System.out.println();
}
}
Your displayNumbers() method is wrong. In the loop you wrote:
numbers[i] = s.nextDouble();
System.out.print(numbers + " " );
You're trying to read again 4 doubles (everytime you call that method) and you're printing the whole array (which doesn't do what you'd expect). What you probably want is this:
System.out.print(numbers[i] + " " );
Your code is inefficient and unclear.
You don't need to create a new Scanner everytime and also why instead of println the array with Arrays.toString(double[]).
You should also make more cleaner instructions and variable names.
Here is an example of how the code should be
public static void main(String[] args)
{
//create a new Scanner with a name that defines it
Scanner scanner = new Scanner(System.in);
//print your instructions
System.out.println("How many numbers would you like to sort?");
//print "> " to let the user to know he should be entering values
System.out.print("> ");
//read the number the user has entered which we will define as how many numbers he would enter next
int totalNumbers = scanner.nextInt();
//create a new array the size of the total numbers
double[] unsortedNumbers = new double[totalNumbers];
//tell the user to enter his unsorted numbers
System.out.println("Enter your unsorted numbers: ");
//loop totalNumbers times until the whole unsortedNumbers is full
for(int index = 0; index < totalNumbers; index++)
{
System.out.print("> ");
unsortedNumbers[index] = scanner.nextDouble();
}
//Print the numbers he entered
System.out.println("You entered: ");
//Arrays.toString prints the array in format [number, number, ...]
System.out.println(Arrays.toString(unsortedNumbers));
//sort the arrays with Arrays.sort which sorts in ascending numerical order
Arrays.sort(unsortedNumbers);
//Print the final result - sorted numbers
System.out.println("Sorted: " + Arrays.toString(unsortedNumbers));
}
I am trying to create a simple program that asks you 10 integers and the program will automatically add them all. I always get an error from Java which is this
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 55
at Sum2.main(Sum2.java:29)
How can I add those multiple array values once?
I tried using
integerArray[0]+[1].....
But it is still not working, please help.
import java.util.Scanner;
public class Sum2 {
private static Scanner sc;
public static void main(String[] args) {
int totalsum;
int[] integerArray = new int[11];
sc = new Scanner(System.in);
System.out.println("Please enter your 10 integers : ");
integerArray[0] = sc.nextInt();
integerArray[1] = sc.nextInt();
integerArray[2] = sc.nextInt();
integerArray[3] = sc.nextInt();
integerArray[4] = sc.nextInt();
integerArray[5] = sc.nextInt();
integerArray[6] = sc.nextInt();
integerArray[7] = sc.nextInt();
integerArray[8] = sc.nextInt();
integerArray[9] = sc.nextInt();
integerArray[10] = sc.nextInt();
totalsum = integerArray[0+1+2+3+4+5+6+7+8+9+10];
System.out.println("The sum of the first 10 integers is: " +totalsum);
}
}
> totalsum = integerArray[0]
+ integerArray[1]
+ integerArray[2]
+ integerArray[3]
+ integerArray[4]
+ integerArray[5]
+ integerArray[6]
+ integerArray[7]
+ integerArray[8]
+ integerArray[9];
Or
totalsum = 0;
for(int i = 0; i < 10; i++) {
totalsum += integerArray[i];
}
By the way, your array contains 11 Integers, not 10.
EDIT: (reply on your comment)
About making code cleaner, this is a lot better than 10 times the same line:
System.out.println("Please enter your 10 integers : ");
for(int i = 0; i < 10; i++) {
integerArray[i] = sc.nextInt();
}
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));
Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}