How to solve Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 - java

I am a newbie and i have no idea what is wrong with my code here. I am going to write both the questions and my code here. Please if anyone can help me.
So the question says:
You have to tell the total number of chores the person can perform in the given time.
The first input is the total number of time the user got.
The second input is the total number of chores the user wants to perform.
The final inputs is the time it will take to complete each task.
and here goes my code:
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int totalmins, chores=0, eachtime, totalchores, counter=0;
// getting the input
System.out.println("Enter the total time:");
totalmins=scan.nextInt();
while (totalmins>100000) {
System.out.println("Enter again. Less than 100000:");
totalmins=scan.nextInt();
}
System.out.println("Enter the total chores:");
chores=scan.nextInt();
int [] time = new int[chores];
for (int i=1; i<chores; i++) {
System.out.println("Enter time:");
eachtime=scan.nextInt();
time[i]=eachtime;
}
// arranging in ascending order
for (int i=0;i<time.length; i++) {
if (time[i] > time[i+1]) {
int temp = time[i];
time[i]=time[i+1];
time[i+1]=temp;
}
}
for (int i=0;i<time.length; i++) {
totalchores=time[i] + time[i+1];
counter++;
if (totalchores>totalmins) {
counter=counter-1;
System.out.println(counter);
}
}
}

I think the point that you're missing is that in an array of length 3, the entries are numbered 0, 1 and 2. If you try to use entry number 3, you'll get that exception. But that's exactly what you're doing - all of your loops continue until i = 2 (including that case), but then you go ahead and try to use entry i + 1 of the array.

Related

How do I fix my duplicate detection code? Java

I have here a scanner in which collects series of numbers. I want it to scan the list every time user inputs a number so if the user inputs a number that is already in the list the new input will be disregarded/ignored and at the same time not adding increment to the loop.
The problem is the code can't seem to identify the duplicates. It continues to register the duplicate number even after few tries.
My code so far:
public class Number {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How Many Numbers You want to Enter:");
int n = input.nextInt();
List<Integer> number = new ArrayList<>();
for(int s=0;s<n;s++) {
int t = input.nextInt();
for (int j = 1; j < number.size(); j++) {
if (t == number.get(j)) {
System.out.print("Duplicate!");
s--;
continue;
} else {
number.add(t);
}
}
}
}
}
At the moment nothing at all is being saved in the number list, so the first thing to do is add debugging to work out why, or better yet, we can make use of the ArrayList.contains(...) method to solve this quite easily without needing the nested loop that that is causing your issue, for example the following works:
for(int s=0;s<n;s++) {
int t = input.nextInt();
if(number.contains(t)){
System.out.print("Duplicate!\r\n");
s--;
continue;
} else {
number.add(t);
}
}
//Print the result
System.out.println(Arrays.deepToString(number.toArray()));
And an output for a length of 5 and this number sequence 2,3,7,3,5,1 is:
How Many Numbers You want to Enter:5
2
3
7
3
Duplicate!
5
1
[2, 3, 7, 5, 1]

How to count the frequency of each number in an array based on user input

i just started learning java and was hoping i could get some help on a logical problem im having. My goal is to as user to enter multiple numbers into an array. I then request the user to insert number from their initial input and print the frequency of that number compared to their first input. I have searched for some time and all the explanations are beyond my level so if anyone could reduce the explanation to a dummy level that will be great.
public class numberCounting {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] storage = new int[100];
int counter = 0;
System.out.println("How many total enteries?");
int total = input.nextInt();
for (int i = 1; i <= total; i++) {
System.out.println("Enter the " + i + " number");
int entry = input.nextInt();
storage[i] = entry;
}
System.out.println("what number do you want to count the frequency of?: ");
int frequency = input.nextInt();
for (int x : frequency) {
if (x == x) {
counter++;
}
System.out.println("There are " + counter + "repeats of your number");
}
}
}
You are checking the wrong input and on top of that you are looping wrongly. Does it even compile? Change it to that
for (int x: storage) {
if (x == frequency) counter++;
}
Besides that - an array starts at the zero index. You are skipping the first entry by setting i = 1.

Java Integer.parseInt() breaks program

I have a question to do in my Java class, and it asks me to write a program that takes in n numbers from the user and outputs the average of them. I know I could do it a much simpler way, just by asking the user to enter the amount of values (s)he needs to enter at the beginning, but I want to create the program so the user doesn't necessarily have to know the number of values at the beginning.
So for this, I create an array of 100 length (which hopefully covers the amount the user needs to enter) inside a for loop (rendering that 100 length array null after the loop, so the program doesn't become too memory heavy) and running a counter trough each iteration. Once the user enters stop, the loop ends, and the values entered into the 100 length array gets transferred to an array the size of the count.
Here is the code:
import java.util.*;
import java.lang.*;
public class main
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
//Question 1
System.out.println("Enter your numbers. (Enter 'Stop' when you're done)");
int temp = 0;
String uInput = "";
char stopper;
int count = 0;
double total = 0;
int a = 0;
boolean inStop = true;
for (boolean stop = false; stop != true;)
{
int array [] = new int [100];
if (inStop == true)
{
System.out.println("point 5");
System.out.print("Input: ");
uInput = input.nextLine(); //reads user input
}
try //empty input repeater
{
System.out.println("point 1");
try //dealing with letters in string instead of numbers
{
System.out.println("point 2");
temp = Integer.parseInt(uInput); //converts string to int
array[count] = temp;
count++;
System.out.println(inStop);
if (inStop == false) //executes when stop has been reached
{
System.out.println("point 3");
int numberArray [] = new int [count]; //fills final array
for (int i = 0; i < count; i++)
{
numberArray[i] = array[i];
}
for (a = 0; a < numberArray.length; a++)
{
total = total + numberArray[a];
}
total = total / a;
stop = true; //ends parent loop
}
}
catch (NumberFormatException e) //catches letters in string and checks for stop
{
System.out.println("point 4");
stopper = uInput.charAt(0);
stopper = Character.toUpperCase(stopper);
if (stopper == 'S')
{
inStop = false;
System.out.println("point 6");
}
}
}
catch (StringIndexOutOfBoundsException e)
{
}
}
System.out.println("The average of the values entered is: " + total + ".");
}
}
The problem is, as you can see there are numerous numbered printouts that indicate (to me) where the program is at the moment. All runs fine, except for point 3. Point 3 for some reason doesn't execute whatsoever. No matter what I do. Now, the problem lies on line 34, temp = Integer.valueOf(uInput); //converts string to int
If I put in a print function directly after that line, that position doesn't print onto the screen. I believe there are no syntax or logic errors with that part, and so does my lecturer, however the code still doesn't execute and the program loops infinitely afterwards. Something is breaking either temp or uInput in that line and we cannot figure out what. I have compiled and ran the code through a different compiler to what I initially used and even tried in the Command Prompt with the same results (so it is not the IDE causing the issue).
Any insight we may have missed would be appreciated. Thanks.
p.s.: don't knock my lecturer, he didn't write the code, and it isn't that easily readable. He could easily know what the problem is, if not for any error in my explanations or his interpretations of how my program is meant to run.
I think that the reason you are having a problem identifying the issue is because of your code structure.
You have mixed the logic for informing the use, with the logic for reading the inputs, and calculating.
If your main method only deal with informing the user, and relies on another method to calculate the average,and another to read the user's input everything will be easier to read, follow and see that you are parsing "stop" as an int.
public static void main(String[] args) {
System.out.println("instructions");
int[] all = readUserInputs();
double ave = calculateAverage(all);
System.out.println("message " + ave);
}
private static double calculateAverage(int[] numbers) {
// I will leave it to you to fill this out
return yourValue;
}
private static String readUserInputs() {
Scanner input;// as above
int[] values; // is an array best? What about a List?
for (int i = 0; ; i++) {
String line = input.nextLine();
if ("stop".equals(line) {
break;
}
//try to parse and put into array/list
}
return values;
}
Hopefully you will find this easier to read and work with,I have left a few gaps for you to fill in.

Scanner does not assign value to the arrayList

import java.util.*;
public class TestScoreTestor {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> score = new ArrayList<Integer>();
// Scanner keyboard = new Scanner(System.in);
Scanner test = new Scanner(System.in);
System.out.println("Enter the scores(enter the input by Ctrl+z): ");
// int a = keyboard.nextInt(); // **** add this to swallow EOL token
while(test.hasNextInt()) {
score.add(test.nextInt());
}
test.close();
System.out.println();
System.out.println(score.size());
// the scores are not involved
for (int i = 1; i <= score.size(); i++) {
System.out.println(score.get(i));
}
Scores grade = new Scores(score);
System.out.println("Your grade: " + grade.getLetterGrade());
}
}
The above is my code and I have a problem of assigning value from Scanner test to ArrayList score. When I run the code, this shows that
Enter the scores(enter the input by Ctrl+z):
90 90 90
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Lab05Q6.Scores.averageScore(Scores.java:29)
at Lab05Q6.Scores.getLetterGrade(Scores.java:36)
at Lab05Q6.TestScoreTestor.main(TestScoreTestor.java:29)
"0" is the size of the arrayList, so I think that there may be some problem during the value adding
while(test.hasNextInt()) {
score.add(test.nextInt());
}
and also I have tried the solutions for others' questions similar to mine,but it does not work. Could you please help me with these question?
Some suggestions and that might help you get it off better :
while(test.hasNextInt()) {
score.add(test.nextInt());
}
This loop will terminate only if you enter some non-digit character. Space and new line will not terminate the loop.
for (int i = 1; i <= score.size(); i++) {
System.out.println(score.get(i));
}
Exception you posted, will never be reached because you will always end up into index out of bound exception. Also, you are starting with index = 1, you might want to start from index 0. Not sure about your logic in Score class.
Also, as what others said, if you posted exception from any class, please provide that.

Trying to find average throws for a dice game

I am trying to simulate a dice game experiment. The goal is to find the average amount of rolls it will take to get the same value of a die to show in the wanted amount of consecutive rolls.
My program asks the user how many times the user wants to run the program. So it will run the loop, then stop after they get their answer, then show the amount of throws it took. Then it will repeat as many times as the user specified.
I want to take the totalThrows from each experiment and add each totalThrows together then divide by my variable turns to get the average amount of throws it would take.
I am having some trouble getting the sum of all the totalThrows. And I can only get the last totalThrow. I would appreciate it if any of you could give some suggestions on how to resolve this. I think an array could help but I haven't learned arrays in class yet.
Here is my code.
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
int value, turns=0, nSides, rollLength; //declare variables
int totalThrows=0, roll=0, count=0,finish=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
System.out.println("\n");
do
{
//Countinue loop until count = rollLength
while(count!=rollLength){
roll = randomNumber.nextInt(nSides)+1;
totalThrows++; //will increment after every roll
//When roll comes up as a watched value I want to increment count by one
if(roll==value){
count++; //This should stop until count is my rollLength
}
else if (roll!=value){ //When an unwanted roll comes up start over
count=0;
}
}
//finish counts how many times the experiment was successful
if (count==rollLength){
finish++;
}
System.out.println("\n");
//Display totalThrows it took until rollLength variable occurs
System.out.println("Your total rolls is: "+ totalThrows);
} while(finish!=turns); //This will repeat the experiment
}
}
Simply declare another variable up top:
int averageThrows = 0;
Add to this value each time the loop ends:
do {
// ...
averageThrows += totalThrows;
} while( finish != turns );
And then divide it by the number of turns:
averageThrows /= turns;
That ought to do it for you.

Categories

Resources