Having some issues with my java program - java

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.

Related

Solved!: the for loop in my code won't repeatedly repeat, gather input, and put it into an array

I am suppose to ask the user for how many integers they want to enter, and then use a loop to create a prompt message for each integer, so that the numbers can be entered. Each integer that is entered is stored in an array.
However, every time I run the code, an error appears. The code doesn't repeat during the loop, and it looks like this:
Please enter the number of values you would like to enter:
1
Please enter for index value of 0:
-Error-
I can't figure out why the loop and array aren't working, thank you!
```public static void main(String[] args) {
//create and label variables
int intCount, n, x;
//create a scanner that will accept the user's input and figure out how many
numbers the user wants to enter
Scanner Inputnumber = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to
enter:");
n = Inputnumber.nextInt();
Inputnumber.close();
//create a integer array to store the numbers
int [] integers;
integers = new int [n];
//create a while loop to continuously ask the user for what numbers they
want to enter
for (intCount = 0; intCount < n; intCount++){
Scanner InputInt = new Scanner(System.in);
System.out.println("Please enter for index value of "+intCount+": ");
x = InputInt.nextInt();
integers [intCount] = x;
InputInt.close();
}```
Refer this
You don't need to use two separate Scanner Objects.
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
// create and label variables
int intCount, n, x;
// create a scanner that will accept the user's input and figure out how many
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to enter:");
n = input.nextInt();
// create a integer array to store the numbers
int[] integers;
integers = new int[n];
// create a while loop to continuously ask the user for what numbers they
for (intCount = 0; intCount < n; intCount++) {
System.out.println("Please enter for index value of " + intCount + ": ");
x = input.nextInt();
integers[intCount] = x;
}
input.close();
}
}

How do I check if a input (integer) matches another value (integer) that exits within my array?

I just learned about array and wanted to build a simple program where I use do-while loops to only accept numbers entered that exist in the array but I'm having some trouble see the problem
Scanner input = new Scanner(System.in);
int[] values;
values = new int[5];
values[0] = 16;
values[1] = 10;
values[2] = 11;
values[3] = 14;
values[4] = 17;
int value;
do {
System.out.println("Enter a number:");
value = input.nextInt();
}
while(value != values[]);
the rest was going to be "if" statements that contained some out going text based on the which numbers from the array are entered. The "while" condition comes up in an error in the way I entered it as
EDIT: Since this isn't possible in java could I just write !=16,10,11,14,17 without getting an error? The array won't work in the condition so I'm still stuck in figuring a way to including multiple numbers in the condition
The termination condition of your do loop:
while(value != values[])
is not legal Java. You cannot compare an int value to an array and you cannot reference an array using values[]. I don't know what you're trying to accomplish, but you need to put in a specific subscript in the termination condition or modify it in some other way.
As you see it's not possible to just write while(value != values[]) but you can search a value in an array or check if the value is contained in a List:
--- First way
Using a List of integers:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class InArrayWithAsListContains {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value=0;
List<Integer> values = new ArrayList<Integer>();
values.add(16);
values.add(10);
values.add(11);
values.add(14);
values.add(17);
do {
System.out.println("Enter a number:");
value = input.nextInt();
} while(!values.contains(value));
}
}
A variation to work with a List starting with int[]:
int[] arr = new int[] {16,10,11,14,17};
// int[] into List<Integer> conversion
for (int i : arr) values.add(i);
--- Second way
Just using arrays and Arrays.binarySearch(values, key)
import java.util.Scanner;
import java.util.Arrays;
public class Program {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value=0;
int[] values = {16,10,11,14,17};
Arrays.sort(values);
do {
System.out.println("Enter a number:");
value = input.nextInt();
} while(Arrays.binarySearch(values, value) < 0);
}
}
An int is not the same thing as an int[]

How to read in a value into an array using Scanner

I don't have any code to show what I am trying to do, because I honestly have no idea how to approach this.
What I am trying to do is have the user input how many numbers will be into an array. So basically, this is what I would like to be the output:
How many students in the class? 3
Enter the marks:
76
68
83
The class average is 75.67 %
I can program everything else, except for the first line. I have no idea how to read in a number into an array, so that the array will be as big as that number.
Thank you.
To start you will need to set up your scanner to read console input:
Scanner scanner = new Scanner(System.in);
You can then use function such as scanner.next() or scanner.nextInt() to get the input from the console. Hopefully this gives you some idea of where to start. If you need to look up more Scanner functions check the Scanner Documentation
As far as arrays go you simply need to save the first int input to the console and use this for size:
int size = Integer.parseInt(scanner.next());
int[] array = new int[size];
Then you should be able to use a loop to save each individual score.
import java.util.Scanner;
public class TestArrayInputViaConsole {
public static void main(String args[]) {
double sum = 0;
double avg = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many students are in the class? ");
int ArraySize = sc.nextInt();
int[] marks = new int[ArraySize];
System.out.println("Enter the marks:");
for(int i = 0; i < ArraySize; i++) {
marks[i] = sc.nextInt();
sum = sum + marks[i];
}
avg = (sum / ArraySize);
System.out.println("Average of the class : " + avg);
}
}

Adding Raise to Salary

I got the program running the way I want it.I am trying to make the program adds 2% raise to every employee's salary. My issue is that the program's output does not display the 2% raise.
Here is the output I get when I run the program..
Enter social security number:12345678
Enter salary2000
Please input next security numbers or -1 to quit:12345677
Enter salary3000
Please input next security numbers or -1 to quit:-1
Social Security Number Salaries Salary After Raise
12345678 2000.000000 0.000000
12345677 3000.000000 0.000000
The code..
import java.util.Scanner;
public class Salaries {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
//Declaring variables
int[] ssNumbers = new int [10];
double[] salaries = new double [10];
double[] nSalaries = new double [10];
int c;
c = inputData (ssNumbers, salaries); //calling input data method
raise (salaries, c); // calling raise method
output (ssNumbers, salaries, nSalaries); //calling output method
}
public static int inputData (int[]ssn, double[]sals){ // input method
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(); //prompting user for input
c++;
System.out.print("Please input next security numbers or -1 to quit:");
ssNum = input.nextInt(); //prompting user for input
}
return c;
}
public static void raise (double[] salaries, int c) // raise method
{
double[] salaryraise = new double [10];
for (int i = 0; i < c; i++ )
salaryraise[i] = salaries[i]*.02;
}
public static void output (int[] ssNumbers, double[] salaries, double[] salaryraise ) //output method
{
System.out.printf("%30s %30s %30s\n", "Social Security Number", "Salaries", "Salary After Raise");
for (int i = 0; i < salaries.length; i++)
//output
System.out.printf("%30d %30f %30f\n", ssNumbers[i], salaries[i], salaryraise[i]);
return;
}
}
In your raise method, you create a local array called salaryraise, and you assign the new numbers to it, but you do nothing with it, and it goes out of scope.
The array you do send to output, nSalaries, is declared, but it is never modified before it's sent to output.
Pass nSalaries as a second parameter to raise, and have raise assign values to that array instead of declaring a local array and assigning values to it.
See the comments in the code :
public static void raise (double[] salaries, int c) // raise method {
double[] salaryraise = new double [10];
// Here, you write to a new array and the original array isn't modified at all.
for (int i = 0; i < c; i++ ) {
salaryraise[i] = salaries[i]*.02;
}
// Change it for
for (int i = 0; i < c; i++ ) {
salaries[i] *= 1.02;
}
}

Calling Methods with Arguments

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.

Categories

Resources