Write the following methods:
13. A method named loadScores that will be passed the size of an array, prompt the user to enter the appropriate number of floating point grades, then return the loaded array.
I wrote the method, but the problem comes when I try to call it. Here's what I have:
public class ArrayHandout {
public static void main(String[] args) {
int size = loadScores(size);
double[] scoresArray = loadScores(size);
} // end main
public static double[] loadScores(int size) {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
} // end loadScores
} // end class
I have changed a few things in an attempt to correct some errors I was having when I wrote the original code, and unfortunately don't even remember what those changes were or if they fixed the problems since I can't get it to compile now. I do know that the problem I was having when I could get the original to compile was that it was only printing the first number in the array rather than printing the entire array. Like I said, I don't know if that problem has been corrected since now when I try to compile I receive the following error message:
1 error found:
File: C:\Users\HiTechRedneck\Desktop\Fall 2013\PlayingwithJava\ArrayHandout.java [line: 6]
Error: incompatible types
required: int
found: double[]
I know that size needs to be declared in main because previously I was getting the "cannot find variable size" error, but I think the fact that I'm trying to declare int size as loadScores(size) is throwing it off since the variable I'm declaring is also an argument in the method.
Any help would be greatly appreciated.
Your line int size = loadScores(size) is incorrect. loadScores has a return type of double[], so you need to assign that return value as such.
Just delete that one line and everything should work as expected.
int size = loadScores(size); is throwing an error because loadScores returns an array of type double.
Since the task just wants a code snippet you could probably give size an arbitrary value and pass that in. Or you could get rid of size in main and just pass a number in:
public static void main(String[] args) {
double[] scoresArray = loadScores(5);
}
Edit: Also worth noting that the print statement after the for loop will throw an ArrayIndexOutOfBoundsException since i is now greater than the length of the array. If you want to print the contents of the scoresArray you'll need another loop to traverse through each element.
Second edit: If you're prompting the user for a size you should run your prompt for that in the main method and then pass that to loadScores().
You don't need size at all before you call the function as you read it in the function
your declaration could be :
public static double[] loadScores()
and call
loadScores()
in main. Example:
public class ArrayHandout {
public static void main(String[] args) {
double[] scoresArray = loadScores();
//do whatever you want here or change declaration of
//the function to void and do not return anything
}
public static double[] loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
}
}
if you don't use the returned array it would be better to do it like this:
public class ArrayHandout {
public static void main(String[] args) {
loadScores();
}
public static void loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
}
}
(When a method doesn't return anything you have to specify it by using the void keyword in its signature)-You also need validation but I was only answering to the specific problem -without validation your program will still fail if incompatible values are given.
Related
My schoolwork is asking me to write a Java program. I'm not getting something quite right.
Basically I have to create a Java method that gets a user to enter x amount of grades (users choice), store the grades in an array and then add the grades in the array up to be called in the main method.
Here's my code:
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int [] storeGrades = new int[numberOfGrades];
}
public static int getTotalScore(int numberOfGrades[]) {
Scanner keyboard = new Scanner(System.in);
int getTotalScore;
int []storeGrades;
for (int i = 0; i < getTotalScore; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
int userGradeNumbers = keyboard.nextInt();
storeGrades[i] = userGradeNumbers;
sum += userGradeNumbers;
}
}
}
I'm getting an error at "sum" that it hasn't been resolved to a variable? It won't let me initialize sum within the for loop, nor the getTotalScore method. Why not?
First, get the grades. Then call the method to get the sum. Declare the sum and initialize it to 0 before your loop. Return it after. Like,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println(getTotalScore(storeGrades));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
Your code has the right intent about it, but some of the ordering of things is a little off and there are syntactical issues at the moment.
I would advocate splitting up your code into two methods (unless you're specifically prohibited from doing so based on the assignment). One method to get the grades from the user, and another to sum the grades. The reason for this, is that you end up trying to both store and sum the grades at the same time (which is technically more efficient), but that doesn't teach you how to calculate a running total by iterating over an array (which is likely the point of the lesson).
One other thing that I would call out (which may be beyond where you are in the course right now), is that when you're using a Scanner, you need to validate that the user has typed what you think they've typed. It's entirely plausible that you want the user to type a number, and they type "Avocado." Because Java is strongly typed, this will cause your program to throw an exception and crash. I've added in some basic input validations as an example of how you can do this; the general idea is:
1) Check that the Scanner has an int
2) If it doesn't have an int, ask the user to try again
3) Else, it has an int and you're good to proceed. Store the value.
One last thing about Scanners. Remember to close them! If you don't, you can end up with a memory leak as the Scanner continues to run.
Below is how I would have revised your code to do what you want. Shoot me a comment if something doesn't make sense, and I'll explain further. I left comments inline, as I figured that was easier to digest!
package executor;
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Initial prompt to the user
System.out.println("Hello Drews, how many total grades do you want to process?");
// This loop validates that the user has actually entered an integer, and prevents
// an InputMismatchException from being thrown and blowing up the program.
int numberOfGrades = 0;
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
// If the program makes it through the while loop, we know that the Scanner has an int, and can assign it.
numberOfGrades = keyboard.nextInt();
// Creating the array using the method getGrades().
int[] storedGrades = getGrades(numberOfGrades, keyboard);
// Calculating the total score using the method getTotalScore().
int totalScore = getTotalScore(storedGrades);
System.out.println("Total Score is: " + totalScore);
keyboard.close();
}
/**
* Asks the user to provide a number of grades they wish to sum.
* #param numberOfGrades the total number of grades that will be requested from the user.
* #param keyboard the scanner that the user will use to provide the grades.
* #return the summed grades as an int.
*/
public static int[] getGrades(int numberOfGrades, Scanner keyboard) {
int[] grades = new int[numberOfGrades];
// Asking the user i number of times, to enter a grade to store.
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ":");
// More input validation to ensure the user can't store "Cat."
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
int userEnteredGrade = keyboard.nextInt();
// Storing the user's entry.
grades[i] = userEnteredGrade;
}
return grades;
}
/**
* Sums all of the grades stored within an integer array.
* #param storedGrades the grades to be summed.
* #return the total value of summed grades.
*/
public static int getTotalScore(int[] storedGrades) {
int totalScore = 0;
for (int i = 0; i < storedGrades.length; i++) {
totalScore += storedGrades[i];
}
return totalScore;
}
}
I'm having a hard time with my second method, The method declaration is:
public static void displayOutput(int loopCount)
The method is called from the main() and is passed the valid input value which determines repetition. The method displays the output pattern only and returns nothing. Every 3rd line displays a space and 3 asterisks
I know I'm not calling each method right in the main() and I know that displayOutput(int loopCout) is wrong.
Could someone explain this to me or use an example that would help write the program?
public static void main(String[] args) {
int repeat;
Scanner goGet = new Scanner(System.in);
repeat = getValidValue(goGet); //Uncompilable source code -Erroneous sym type
displayOutput(repeat);
}
public static int getValidValue() {
int input;
do {
Scanner getInfo = new Scanner(System.in);
System.out.print("Enter an integer Greater than zero: --> ");
input = getInfo.nextInt();
} while (input <= 0);
return input;
}
public static int displayOutput(int loopCount) {
int i;
for (i = 0; i < loopCount; i++) {
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon.*** ");
}
return loopCount;
}
You are passing a value to method getValidValue which doesn’t take any value.
Also displayOutput is returning loopcount but you are not catching it anywhere so after asterisk it is not displaying anything.
I would like to know the best possible way to modify this code. Instead of adding the integers to an array in the code itself, I would like the user to input the different weights and the capacity via keyboard.
Now I am currently having compiling errors when inserting the data. I believe the problem lies within the for loop.
import java.util.*;
public class NN01276494 {
public static ArrayList <Double> sack = new ArrayList <Double> ();
public static void main(String [] args){
Scanner in = new Scanner (System.in);
int i =0;
for(i = 0; i<sack.length; i++){
System.out.println("Enter Capacity");
sack.size(in.nextDouble());
}
while (in.hasNextDouble()){
System.out.print("Enter weights");
sack.add(in.nextDouble());
i++;
}
}
public static Boolean knapsackproblem(double targetWeight, int index)
{
Boolean complete = false;
if(index == sack.size()) return false;
if(sack.get(index) == targetWeight)
{
System.out.print("Answer: " + sack.get(index) + " ");
complete = true;
}; //DONE
if(sack.get(index) < targetWeight)
{
complete = knapsackproblem(targetWeight-sack.get(index), index+1);
if(complete) System.out.print(sack.get(index) + " ");
for(int i = index+1; i < sack.size(); i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i);
}
}
if(sack.get(index) > targetWeight) complete =
knapsackproblem(targetWeight, index+1);
return complete;
}
}
The most common way to accept user input in java is the Scanner class. This allows your users to input into the console, and your program to use their input. Here is the javadoc that details scanners in detail, but here's all you need to do to accept integer inputs from your users:
First, import the scanner dictionary so you can use it.
import java.util.Scanner;
This will give you access to the Scanner library. To construct the scanner, you need to specify an input stream in the declaration. To make the console this input stream, declare it like so:
Scanner nameOfScanner = new Scanner(System.in);
Now, to get the integers for the array, use the method .nextInt() as many times as you want. Make sure to ask the user separately for each input, and if you want the user to be able to control the size of the array, you can also ask the user for that. Just in case you don't know, you can declare an array to have a certain size, but not specify what is going to be in each location until later like so:
int[] nameOfArray = new int[sizeOfArray];
On a separate note, I noticed that you had a semicolon after the closing bracket of your if statement in the middle of the knapsackproblem() method. I don't know if that's a typo in your question or actually in your code, but it really shouldn't be there.
I hope this helps, and good luck coding!
I've modified your code so user can input the array via an ArrayList :-using ArrayList user can input data without regard to length just enter as many values as you want then at the end type any letter for ex:[Out] then your method should start working :).
import java.util.*;
public class knapsack {
public static void main(String [] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter Capacity");
int y = in.nextInt();
double [] sack = new double [y];
System.out.println("enter values");
for (int i =0;i<y;i++){
sack[i]=in.nextDouble();
}
}
public static Boolean knapsackproblem(double targetWeight, int index ,
double [] sack)
{
Boolean complete = false;
if(index == sack.length) return false;
if(sack[index] == targetWeight)
{
System.out.print("Answer: " + sack[index] + " ");
complete = true;
}; //DONE
if(sack[index] < targetWeight)
{
complete = knapsackproblem(targetWeight-sack[index], index+1,sack);
//keep going
if(complete) System.out.print(sack[index] + " ");
for(int i = index+1; i < sack.length; i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i,sack);
}
}
if(sack[index] > targetWeight) complete = knapsackproblem(targetWeight,
index+1,sack);
return complete;
}
}
Hope it helps.Also I've fixed your recursion since you wrote knapsack( instead of knapsackproblem(.ArrayList comes from java,util package which also includes the Scanner class I just got them all using * ArrayList is a class that has its own methods like .size() and .add().
How to get an user input using scanner class and use it inside method to process, and obtain output?
Example : You get two numbers from the user and pass it to 4 methods to get its value after addition, subtraction, multiplication, division.
The scanner should be in main class and not inside every method.
Here is my code, it's in basic form. I want to get input from the user and process it inside the methods and get the result:
class Calc{
public static void main(String[] args){
add();
sub();
mul();
div();
{
void Add() {
int a=5,b=10;
sum=a+b;
System.out.println(sum);
}
void sub() {
int a=5,b=10;
sub=a=b;
System.out.println(sub);
}
void mul() {
int a=5,b=10;
mul=a*b;
System.out.println(mul);
}
void div() {
int a=5,b=10;
div=a/b;
System.out.println(div);
}
}
}
}
Simply use the array or nextInt() method to get the number of input and passed it to your method.
For e.g. If you are supposed two take two input at time
Scanner sc = new Scanner(System.in);
int[] integers = new int[2];
for(int i = 0; i < 2; i++)
{
integers[i] = sc.nextInt();
}
Now use the integers array to get the value from index and passed it to your method
You can get input by using new Scanner(System.in), as follows:
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
add(a,b);
sub(a,b);
multiply(a,b);
divide(a,b);
I am trying to do my java assignment. I am just struggling with some of the issues. I could not make the program calculates and outputs the information needed. When I try to run the program, and input the social security number, I get an error and a message saying
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Salaries.inputData(Salaries.java:34) at
Salaries.main(Salaries.java:18)
What am I doing wrong?
Thanks.
Here is a description of the program I am suppose to do.
Write a program that reads Social Security numbers and salaries from the keyboard (Test this by only reading 3 or 4 to start). After the data is read in, the program should add a 2% raise to everyone’s salary. After you give the raise, print out 3 nicely formatted columns of information (Social, salary before raise, salary after raise). You will need a 3rd array holding the new salaries. A separate method should be used for the input, raise, and output.
This is the code I got so far.
import java.util.Scanner;
public class Salaries {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int[] ssNumbers = new int [10];
double[] salaries = new double [10];
int c;
int rais;
c = inputData (ssNumbers, salaries);
raise (salaries, c, ssNumbers);
output (ssNumbers, salaries, nSalary);
}
public static int inputData (int[]ssn, double[]sals){
int c = 0;
Scanner input = new Scanner (System.in);
int ssNum;
System.out.print("Enter social security number");
ssNum = input.nextInt();
while (ssNum != -1) //using while loop.
{
ssn[c] = ssNum;
System.out.print("Enter salary");
sals[c] = input.nextDouble();
c++;
System.out.print("Please input next security numbers or -1 to quit");
ssn[c] = input.nextInt();
}
return c;
}
public static void raise ( double[] salaries, int c, int[] ssNumbers)
{
double salar;
double rais = 0.02;
for (int count = 0; count < c; count++ )
rais+= rais;
System.out.printf("the salary after raise is %f\n", rais);
return;
}
public static void output (int[] ssNumbers, double[] salaries, double[] nSalary )
{
System.out.printf("%10d%-20d%-20f%", ssNumbers, salaries, nSalary);
return;
These statements:
int[] ssNumbers = new int [0];
double[] salaries = new double [0];
double[] nSalary = new double[0];
create an array of size 0. So when you try to add an element to that array, you are adding to an index that is greater than the array size. I would use an ArrayList so you can grow your array dynamically behind the scenes if you do not know the length.
If you have to use arrays, make sure they are big enough for the data you want to put in, eg
int[] ssNumbers = new int [maxSize];
The value of c in the function inputData is exceeding the length of ssn[] (or maybe sals[], can't tell in your code). Your boundary checking is off, try making sure that c is never less than 0, or larger than the size of ssn[].
You are initializing your array to 0 in the below statement,
int[] ssNumbers = new int [0];
double[] salaries = new double [0];
And you are trying to read past 0 in the below statement (inside inputData function)
ssn[c] = ssNum;
That is the error
You are reading till user inputs -1 which means that you didn't know the number of data/user-inputs prehand. Use LinkedList instead of array.