IndexOutOfBoundsException while accessing List - java

I'm working on a project for a class, and I think I've got it mostly figured out, but it keeps giving me different Exception errors and now I'm stumped.
The instructions can be found here: http://www.cse.ohio-state.edu/cse1223/currentsem/projects/CSE1223Project11.html
Here is the code I have thus far, currently giving me and IndexOutOfBounds exception in the getMaximum method.
Any help would be much appreciated.
import java.io.*;
import java.util.*;
public class Project11a {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an input file name: ");
String fileName = keyboard.nextLine();
Scanner in = new Scanner(new File(fileName));
System.out.print("Enter an output file name: ");
String outFile = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(outFile);
while (in.hasNextLine()) {
String name = in.nextLine();
List<Integer> series = readNextSeries(in);
int mean = getAverage(series);
int median = getMedian(series);
int max = getMaximum(series);
int min = getMinimum(series);
outputFile.printf("%-22s%6d%n", name, mean, median, max, min);
}
in.close();
outputFile.close();
}
// Given a Scanner as input read in a list of integers one at a time until a
// negative
// value is read from the Scanner. Store these integers in an
// ArrayList<Integer> and
// return the ArrayList<Integer> to the calling program.
private static List<Integer> readNextSeries(Scanner inScanner) {
List<Integer> nextSeries = new ArrayList<Integer>();
while (inScanner.hasNextInt()) {
int currentLine = inScanner.nextInt();
if (currentLine != -1) {
nextSeries.add(currentLine);
} else {
break;
}
}
return nextSeries;
}
// Given a List<Integer> of integers, compute the median of the list and
// return it to
// the calling program.
private static int getMedian(List<Integer> inList) {
Collections.sort(inList);
int middle = inList.size() / 2;
int median = -1;
if (inList.size() % 2 == 1) {
median = inList.get(middle);
} else {
try {
median = (inList.get(middle - 1) + inList.get(middle)) / 2;
} catch (Exception e) {
}
}
return median;
}
// Given a List<Integer> of integers, compute the average of the list and
// return it to
// the calling program.
private static int getAverage(List<Integer> inList) {
int average = 0;
if (inList.size() == 0) {
return 0;
}
for (int i = 0; i < inList.size(); i++) {
average += inList.get(i);
}
return (average / inList.size());
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMaximum(List<Integer> inList) {
int max = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) > max) {
max = inList.get(i);
}
}
return max;
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMinimum(List<Integer> inList) {
int min = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) < min) {
min = inList.get(i);
}
}
return min;
}
}

Seemed like that your list is empty.
What can triggered the exception is the statement:
int max = inList.get(0);
So your inList do not have the value in the first index,which means the inList is empty.

Related

how to return in a recurssive fn in java

Actually my aim is to find the super no for eg i will be given 2 values n,k where n=148 and k =3 so i have to form p = 148148148 then add digits of p until i get a single no (ans = 3) this is what i have tried.......
import java.util.*;
public class RecurrsiveDigitSum {
public int check(int n) {
int s = 0;
int d;
while(n>0) {
d = n%10;
s = s+d;
n = n/10;
System.out.println(s);
}
if(s/10 !=0){
check(s);
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int sum;
RecurrsiveDigitSum obj = new RecurrsiveDigitSum();
sum = obj.check(n);
System.out.println(sum);
sum = sum * k;
System.out.println(sum);
int s1 = obj.check(sum);
System.out.println(s1);
}
}
but the problem here is that even if my s = 4 finally its just returning the first value of s that has been found so pls help me friends
you must put return before recursive calling.
if(s/10 !=0){
return check(s);
}
If you don't put it, the result of calling function will be loss and the result of s will be returned instead of check(s).
I've improved your solution little bit.
public int check(int n) {
int s = 0;
while(n>0) {
s += n%10;
n /= 10;
}
if(s/10 != 0){
return check(s);
}
return s;
}

JAVA error cannot find a symbol

I need to create a JAVA method: public static int[] Numb() that reads and returns a series of positive integer values. If the user enters -1 we should stop accepting values, and then I want to call it in the main method. And we should return to the user integers that he entered them, with the total number.
So if he entered the following:
5 6 1 2 3 -1
So the total number is : 6
The numbers entered are: 5 6 1 2 3 -1
I tried the following:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static int[] readNumbers(int[] n)
{
int[] a = new int[n.length];
Scanner scan = new Scanner(System.in);
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.nextString();
}
}
}
And here is a fiddle of them. I have an error that said:
Main.java:21: error: cannot find symbol
a[i] = Integer.nextString();
I am solving this exercise step by step, and I am creating the method that reads integers. Any help is appreciated.
Integer.nextString() doesn't exist, to get the next entered integer value, you may change your loop to either :
for(int i = 0;i<n.length;i++) {
a[i] = scan.nextInt();
}
or as #vikingsteve suggested :
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.parseInt(token);
}
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
initializeList(numList);
System.out.println("Num of integer in list: "+numList.size());
}
public static void initializeList(List<Integer> numList) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag) {
int num = sc.nextInt();
if(num==-1) {
flag = false;
}else {
numList.add(num);
}
}
sc.close();
}
Since the number of integers is unknown, use ArrayList. It's size can be altered unlike arrays.
You can create something like arraylist on your own..it can be done like this:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CustomArray c = new CustomArray(3);
boolean flag = true;
while (flag) {
int num = sc.nextInt();
if (num == -1) {
flag = false;
} else {
c.insert(num);
}
System.out.println(Arrays.toString(c.numList));
}
sc.close();
}
}
class CustomArray {
int[] numList;
int size; // size of numList[]
int numOfElements; // integers present in numList[]
public CustomArray(int size) {
// TODO Auto-generated constructor stub
numList = new int[size];
this.size = size;
numOfElements = 0;
}
void insert(int num) {
if (numOfElements < size) {
numList[numOfElements++] = num;
} else {
// list is full
size = size * 2; //double the size, you can use some other factor as well
//create a new list with new size
int[] newList = new int[size];
for (int i = 0; i < numOfElements; i++) {
//copy all the elements in new list
newList[i] = numList[i];
}
numList = newList;//make numList equal to new list
numList[numOfElements++] = num;
}
}
}

Issue converting array to array list

Trying to write a java code for a single row Battleship style game, and when I tried to convert from an array to an ArrayList, the game started returning "miss" no matter what.
public class SimpleDotComGame {
public static void main(String[] args) {
int numofGuess = 0;
Scanner sc = new Scanner(System.in);
SimpleDotCom dot = new SimpleDotCom();
int ranNum = (int) (Math.random() * 5);
ArrayList<Integer> locations = new ArrayList<Integer>();
locations.add(ranNum);
locations.add(ranNum + 1);
locations.add(ranNum + 2);
dot.setLocationCells(locations); //think like you're running a
// separate program with parameters to set cells as "locations"
boolean isAlive = true;
while (isAlive == true) {
System.out.println("Enter a number");
String userGuess = sc.next();
String result = dot.checkYourself(userGuess); //run program to
// check if cells were hit by userGuess
numofGuess++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numofGuess + " guesses");
}
}
sc.close();
}
}
public class SimpleDotCom {
int numofHits = 0;
ArrayList<Integer> locationCells;
public void setLocationCells(ArrayList<Integer> locations) { //locations
// variable described array so we must define it as array now
locationCells = locations;
}
public String checkYourself(String userGuess) { //check using parameter userGuess
int guess = Integer.parseInt(userGuess);
String result = "miss";
int index = locationCells.indexOf(userGuess);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
}
System.out.println(result);
return result;
}
}
Change :
int index = locationCells.indexOf(userGuess);
to
int index = locationCells.indexOf(guess);
userGuess is a String which can not possibly be in a list of Integers. guess is an int which can.

Making a Program that Reads and Writes Data - Then Computes Min, Max, Average

I'm making a program that reads some data from a text file and then takes that data and finds the minimum, maximum, and average of the numbers. For some reason I'm getting a lot of ridiculous errors I've never seen before. Here is my code:
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
public class Lab1 {
static int count = 0;
static int[] newData2 = new int[count];
// Method for reading the data and putting it into different arrays
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
}
static int min(int[] newData2) {
int min = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] < min) {
min = newData2[i];
}
}
return min;
}
static int max(int[] newData2) {
int max = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] > max) {
max = newData2[i];
}
}
return max;
}
static double average(int[] newData2) {
double average = 0;
int sum = 0;
for (int i = 0; i < newData2.length; i++) {
sum = newData2[i];
}
average = sum / newData2.length;
return average;
}
/*
* static int stddev(int[] newData2) { int[] avgDif = new
* int[newData2.length]; for(int i = 0; i < newData2.length; i++) {
* avgDif[i] = (int) (average(newData2) - newData2[i]); }
*
* }
*/
void write(String newdata, int min, int max, double average, int stddev) {
try {
File file = new File("stats.txt");
file.createNewFile();
FileWriter writer = new FileWriter("stats.txt");
writer.write("Minimum: " + min + "Maximum: " + max + "Average: " + average);
writer.close();
}catch(Exception e) {
System.out.println("Unable to write to the file.");
}
public static void main(String[] args) {
}
}
}
I have an error in my readData method, and it tells me that:
This method must return a result type of int[].
I'm literally returning an int array so I don't understand what the problem here is.
Then in my main method it says void is an invalid type for the variable main.
Here are some pointers:
each exit point of a method returning something must return something, if the line new Scanner(f); throws an exception, the first return is not reached, so you need a default one, like this:
private int[] readData() {
File f = new File("data.txt");
int count = 0;
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt(); // maybe you should handle the case where your input is too large for the array "newData"
}
return Arrays.copyOf(newData, count);
} catch (Exception e) {
System.out.println("Could not read the file.");
}
return null;
}
To reduce the size of an array, you should use Arrays.copyOf (see below)
You should avoid static fields (and in your case none are required)
Your method min and max are assuming there are elements in the array (at least one), you should not do that (or test it with an if):
private int min(int[] data) {
int min = Integer.MAX_VALUE; // handy constant :)
for (int i = 0; i < data.length; i++) {
if (data[i] < min) {
min = data[i];
}
}
return min;
}
private int max(int[] data) {
int max = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
In your average method there are a few mistakes:
private double average(int[] data) {
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i]; // here if you want a sum it's += not =
}
return (1.0 * sum) / data.length; // you want a double division, local "average" was useless
}
arrays are iterables so you can use "new style" for loops:
for (int value : newData) {
// use value
}
Some reading:
Java Integer division: How do you produce a double?
“Missing return statement” within if / for / while
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
//TODO: return something here if there is some kind of error
}
Because of the try-catch block you need to account for every possibility that could occur. When you return the array when the program succeeds you are expecting a return, but when there is an exception the program still expects a return value, but you did not provide one.

How to round an array of numbers to 3 digits in java

I am trying to round an array of numbers to three decimal places in java, the reason being that I am running into an OutOfMemoryError (array is exceeding the VM's limit). I was curious if there was a way to do this without writing an entire new method or anything drastic like that.
EDIT: here is all the code
public class GuitarHero {
public static void main(String[] args) {
int index = 0;
double sample = 0.0;
String keyboard ="1234567890qwertyuiopasdfghjklzxcvbnm,";
GuitarString[] string = new GuitarString[keyboard.length()];
for(int i = 0; i < 37; i++) {
double concert = 110.0 * Math.pow(2,i-24);
string[i] = new GuitarString(concert);
}
while (true){
if (StdDraw.hasNextKeyTyped()) {
char key = StdDraw.nextKeyTyped();
index = keyboard.indexOf(key);
if (index >= 0 && index < 37){
string[index].pluck();
}
//sample = string[index].sample() + string[index+1].sample();
//StdAudio.play(sample);
}
for(int i=0; i<37; i++){
sample = string[i].sample();
StdAudio.play(sample);
}
for(int i = 0; i < 37; i++){
string[i].tic();
}
}
}
}
end of code 1
public class GuitarString {
private RingBuffer buffer; // ring buffer
// YOUR OTHER INSTANCE VARIABLES HERE
private int ticTimes = 0;
// create a guitar string of the given frequency
public GuitarString(double frequency) {
// YOUR CODE HERE
int N;
N = (int)(44100/frequency);
buffer = new RingBuffer(N);
for (int i=1; i <=N; i++ ){
buffer.enqueue(0.0);
}
}
// create a guitar string whose size and initial values are given by the array
public GuitarString(double[] init) {
// YOUR CODE HERE
buffer = new RingBuffer(init.length);
for (int i = 0; i < init.length; i++){
buffer.enqueue(init[i]);
}
}
// pluck the guitar string by setting the buffer to white noise
public void pluck() {
// YOUR CODE HERE
while(!buffer.isEmpty()) buffer.dequeue();
while(!buffer.isFull()){
buffer.enqueue(Math.random()-0.5);
}
}
// advance the simulation one time step
public void tic() {
// YOUR CODE HERE
double value1, value2;
value1 = buffer.dequeue();
value2 = buffer.peek();
buffer.enqueue(((value1+value2)/2)*0.996);
ticTimes++;
}
// return the current sample
public double sample() {
// YOUR CODE HERE
return buffer.peek();
}
// return number of times tic was called
public int time() {
// YOUR CODE HERE
return ticTimes;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
double[] samples = { .2, .4, .5, .3, -.2, .4, .3, .0, -.1, -.3 };
GuitarString testString = new GuitarString(samples);
for (int i = 0; i < N; i++) {
int t = testString.time();
double sample = testString.sample();
System.out.printf("%6d %8.4f\n", t, sample);
testString.tic();
}
}
}
end of code 2
public class RingBuffer {
private int first; // index of first item in buffer
private int last; // index of last item in buffer
private int size; // current number of items of buffer
private double[] buffer;
// create an empty buffer, with given max capacity
public RingBuffer(int capacity) {
// YOUR CODE HERE
buffer = new double[capacity];
first =0;
last =capacity-1;
size =0;
}
// return number of items currently in the buffer
public int size() {
// YOUR CODE HERE
return size;
}
// is the buffer empty (size equals zero)?
public boolean isEmpty() {
// YOUR CODE HERE
if (size == 0)
return true;
else
return false;
}
// is the buffer full (size equals array capacity)?
public boolean isFull() {
// YOUR CODE HERE
if (size == buffer.length)
return true;
else
return false;
}
// add item x to the end
public void enqueue(double x) {
if (isFull()) { throw new RuntimeException("Ring buffer overflow"); }
// YOUR CODE HERE
last = (last+1)%buffer.length;
buffer[last]=x;
size++;
}
// delete and return item from the front
public double dequeue() {
if (isEmpty()) { throw new RuntimeException("Ring buffer underflow"); }
// YOUR CODE HERE
double temp = buffer[first];
first = (first+1)% buffer.length;
size--;
return temp;
}
// return (but do not delete) item from the front
public double peek() {
if (isEmpty()) { throw new RuntimeException("Ring buffer underflow"); }
// YOUR CODE HERE
return buffer[first];
}
// a simple test of the constructor and methods in RingBuffer
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
RingBuffer buffer = new RingBuffer(N);
for (int i = 1; i <= N; i++) {
buffer.enqueue(i);
}
double t = buffer.dequeue();
buffer.enqueue(t);
System.out.println("Size after wrap-around is " + buffer.size);
while (buffer.size() >= 2) {
double x = buffer.dequeue();
double y = buffer.dequeue();
buffer.enqueue(x + y);
}
System.out.println(buffer.peek());
}
}
Thanks!
Well in the first iteration of that loop the code is trying to allocate an array of 1,681,534,603 doubles (44100 / (110 * 2^-22)), which would require about 3GB of memory. I suggest you find a different solution.

Categories