/*IMO I have completed most of the project, but I can't wrap my mind around part with the array. I am supposed to assign the values to it then have it show on screen, as it is doing now when program get run, but it isn't going through the array. Please help its driving me insane.
Assignment:
For this project, you will create a program that asks the user to enter a positive integer value less than 20. Note that the program will only collect one number from the user. All other numbers will be generated by the program.
If the user enters a number greater than 20, the user should get an error.
If the user enters a number equal to or less than 20, display the double of each value beginning with 1 up to the selected number (multiply each number by 2), then provide the total of all doubles.
For example, if the user entered the number 5, the following should display:
Double up 1 = 2
Double up 2 = 4
Double up 3 = 6
Double up 4 = 8
Double up 5 = 10
Total = 30
Minimum Requirements:
• Create a separate class that contains the following methods. Note: This class should be separate and apart from the public class that holds the main method. 1. A method that will accept two parameters: an integer array and a integer variable. 1. The integer variable should hold the value provided by the user. The array will be used to hold the double up results.
2. This method should perform the calculations, and store the double up results in the array. Additionally, the total of all double up values should be calculated using an accumulator variable that is also a private instance variable.
3. You must make sure the calling method gets the changes to the array. Remember, arrays are passed by reference by default. This method must use a loop.
A separate method that will return (not display) the value stored in the private instance variable called total.
• Create a main method that creates an array and integer variable, as well as an instance of your class. The main method should then use the instance to call each of the methods of the class, passing the data needed and handling any return data. Display the entire contents of the array and total variable.
*/
import java.util.Scanner;
public class project2 {
public static void main(String args[]){
scores output = new scores();
output.enterNum();
output.displayScores();
}
}
class scores
{
int total;
int stats[] = new int[20];
int num1;
void enterNum()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 1 and 20: ");
num1 = input.nextInt();
if(num1<=0 || num1>20)
{
System.out.println("You entered a wrong number. Try again.");
System.out.println("");
enterNum();
}
}
void displayScores()
{
int b=0;
int val2=0;
int total = 0;
val2=num1*2;
for(int i=1;b<val2;i++)
{
System.out.println(b=i*2);
total = total + b;
// this part.
// stats[i] = b;
// System.out.println(stats);
}
System.out.println(total);
}
}
Maljam is right, your for-loop is the issue here.
Your for-loop is messing around with some int b that doesn't need to be there. What you want is to add i*2 to total on each iteration of your loop. Also, you need to modify your for-loop header to check against i instead of b. I'm not really sure what you are trying to do with the array. It's not needed in this project at all.
Try changing it to something like this:
for (int i=1; i<=val1; i++){
//stats[i] = i;
System.out.println("Double up " + i + " = " + 2*i);
total = total + 2*i; //or total += 2*i;
}
System.out.println("Total: " + total);
public class scores {
int total;
int stats[];
int num1;
void enterNum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 1 and 20: ");
num1 = input.nextInt();
if (num1 <= 0 || num1 > 20) {
System.out.println("You entered a wrong number. Try again.");
System.out.println("");
enterNum();
}
}
void displayScores() {
stats = new int[num1];
int total = 0;
for (int i = 0; i < num1; i++) {
stats[i] = (i+1) * 2;
total += stats[i];
}
for (int i = 0; i < num1; i++) {
System.out.println((i+1) + " * 2 = " + stats[i]);
}
System.out.println("Total: " + total);
}
}
Related
I'm new to Java and I'm stuck on this problem:
"Create a second add() method which has a single parameter of an array of doubles and, inside the method, adds the values of the array, returning the result as a double. Sample test data:
double[] dblArr = {11.82,88.23,33};
I have a separate class file with the following so far:
public double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}
This is the method to add the array's and return the total sum.
And this is the code I have in my "main" document to call the method
double dblArr;
utils.print("Please enter an array of 5 numbers: ");
dblArr = input.nextDouble();
double sum = calc.add(dblArr);
System.out.println(dblArr);
I know I'm quite off scope so some advice would be really appreciated, thank you
"calc" is what I'm using to call the other document
Calculate calc = new Calculate();
You are most of the way there, you just need to use a double array to gather the inputs, and you need to use a loop to save all the inpets to the array:
//use an array instead of a single double
double[] dblArr = new double[5];
int inputs = 0;
//Use a loop to gather 5 inputs
while(inputs < 5){
utils.print("Please enter the next of 5 numbers: ");
dblArr[inputs] = input.nextDouble();
inputs++;
}
//We have changed the add method to static, so you can just use `add(dblArr)` instead of making an instance of the class with the add method
double sum = add(dblArr);
//Finally print out the sum result not the dblArr array
System.out.println("The total is " + sum);
Then just change the method to static so that you can call it directly:
//Add static to this line as shown, because we don't need an instance of this method
public static double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}
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));
}
}
When I try to run this program in java it will not work even though there are no errors in eclipse.
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter how many numbers: ");
int x = input.nextInt();
double[] numbers = new double[x];
double[] orderednumbers = new double[x];
double total = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print("Please enter number " + (i + 1) + ": ");
numbers[i] = input.nextDouble();
total += numbers[i];
}
double mean = (total / x);
System.out.println("Mean: " + mean);
orderednumbers[x] = 0;
for (int counter = 0; counter < numbers.length; counter++) {
if (numbers[counter] > orderednumbers[x]) {
orderednumbers[x] = numbers[counter];
orderednumbers[x] = orderednumbers[x];
}
}
System.out.println("Maximum: " + orderednumbers[x]);
}
}
This is what's called a runtime error. Sure, it compiles... but for this code you need to be careful with how you handle the array. Your code gave me an ArrayOutOfBoundsException.
Note that you set x early in the code to the length of the array, then go and set orderednumbers[x] to 0. This will give you an ArrayIndexOutOfBoundsException, as since Java array indices are zero-based (i.e. element #1 has index 0, and can be accessed with orderednumbers[0]), the length of an array isn't a valid index.
Also, your code for swapping the two numbers in the sort is incorrect; you'll need a temporary variable to store the result. Otherwise, you'll end up making the two places in the array hold the same value.
Try making it this:
int temp = orderednumbers[x];
orderednumbers[x] = numbers[counter];
orderednumbers[x] = temp;
Note that your statement at the end of the if block:
orderednumbers[x] = orderednumbers[x];
won't accomplish anything.
I'm writing a program that adds the first ten odd numbers, and gets the sum at the end.
Here is my code so far. My code reads the odd number in a list of 10 numbers. I want my code to be able to read 10 odd numbers even if there are more than 10 numbers entered. I know the problem is i < 10, which makes the program stop after the 10th number.
import java.util.Scanner;
public class question14
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i = 0;
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
}
}
Wrap it in a while loop instead.
While oddnumbers < 10 ask for a new number.
int i = 0
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
EDIT:FULL CODE
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author stevengreen22
*/
public class NewMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int input;
int inputCount = 0;
while (i < 10){
//Having this inside the while loop prompts the user every time.
System.out.println("New number?");
input = scan.nextInt();
inputCount++;
if(input % 2 == 1){
sum += input;
i++;
}
}
System.out.println("sum: "+sum);
System.out.println("Number of odds:" + i);
System.out.println("Numbe of inputs: " +inputCount);
System.out.println("Average cos I miss typing sout tab:" + (inputCount/sum));
}
}
The principle thing is that you don't know how many numbers the user is going to enter into the program, so you want to use a while loop instead of a for loop.
One chooses a for loop when they know how many elements they want to iterate over; one chooses a while loop when they don't know how many elements they'll need to iterate over.
You'll need to define another variable called counter outside of the loop, and use this as your loop variable constraint.
while(counter < 10) {
// loop
}
You'll also need to update counter whenever you encounter an odd value.
This should work
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i=0;
while (i<10){
odd=keyboard.nextInt();
if (odd%2!=0){
sum=sum+odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is "+sum);
}
Just replace your for loop with a while loop and track the number of odd numbers in an integer:
int oddNumberCount = 0;
int inputNumber;
while(oddNumberCount<10)
{
inputNumber = keyboard.nextInt();
if(inputNumber%2!=0)
{
sum = sum+inputNumber;
oddNumberCount++;
}
}
I"m trying to make a program that retrieves an endless amount of numbers that user inputs, and then it tells you how many numbers that you inputted, the sum of all the numbers, and then the average of the numbers. Here is the code I have so far. I don't know why it does not work. I get no errors, but it just does not get a valid sum or average.
import javax.swing.*;
public class SumAverage {
public static float sum;
public static float averageCalculator;
public static float average;
public static void main(String[]args) {
float numbers[] = null;
String userInput = JOptionPane.showInputDialog(null, "Ready to begin?");
if(userInput.equalsIgnoreCase("no"))
{
System.exit(0);
}
for(int i = 0; i != -2; i++)
{
numbers = new float[i + 1];
userInput = JOptionPane.showInputDialog(null, "Input any number. Input * to exit");
if(userInput.length() == 0 || userInput.equals("*") || userInput.equals(null))
{
break;
}
else
{
numbers[i] = Float.parseFloat(userInput);
}
}
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
average = sum / numbers.length;
JOptionPane.showMessageDialog(null, "The sum of all your numbers is " + sum + ". The average is " + average + ". You entered a total of " + numbers.length + " numbers.");
}
}
The problem is in this line:
numbers = new float[i + 1];
You are creating a new array, but you aren't copying the values from the previous array assigned to numbers into it.
You can fix this in two ways:
copy the values using System.arraycopy() (you'll need to use a new variable to make the call then assign it to numbers)
Don't use arrays! Use a List<Float> instead, which automatically grows in size
In general, arrays are to be avoided, especially for "application logic". Try to always use collections - they have many powerful and convenient methods.
If you wanted to store the numbers for later use, try making your code look like this:
List<Float> numbers = new ArrayList<Float>();
...
numbers.add(Float.parseFloat(userInput));
...
for (float n : numbers) {
sum += n;
}
average = sum / numbers.size(); // Note: Don't even need a count variable
And finally, if you don't need to store the numbers, just keep a running sum and count and avoid any kind of number storage.
Unrelated to the Q, but note also you can compute a running count/average without storing all the input data - or assuming you want to keep the input - without traversing over it each iteration. Pseudocode:
count = 0
sum = 0
while value = getUserInput():
count++
sum += value
print "average:" + (sum / count)
with
numbers = new float[i + 1];
you are creating a whole new array on every iteration. That means you are always creating a new array that will increase its size by 1 on each iteration but only having one field filled with the current user input and having all the other fields been empty.
Delete this line and initialize the array before.
If the size of the array should grow dynamically within the loop
do not use an array at all and use a dynamic data structure like a List or an ArrayList instead.
Further i would suggest to use
while (true) {
//...
}
to realize an infinite loop.