Hi guys im trying to make a average calculator (I'm learning java now), everything works fine except 1 thing.
Here is my code:
package projects;
import java.util.Scanner;
public class average {
public static void main (String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("/////////////////////////////////");
System.out.println("/// Average Calculator ///");
System.out.println("/////////////////////////////////");
System.out.println("How many numbers: ");
int totalnumbers = sc.nextInt();
int average = 0;
int[] list;
list = new int [totalnumbers];
for(int X = 1 ; X <= totalnumbers ; X++){
System.out.println("Please choose number " + X +": ");
list[X] = sc.nextInt();
average+=list[X];
}
System.out.println("Your average is:" + (average/totalnumbers));
sc.close();
}
}
i cant figure out whats wrong but when its supposed to give me the average, it gives me this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at projects.average.main(average.java:19)
Array indexing goes from 0 to N-1.
The runtime exception occurs when you attempt to access list[X] with x == totalnumbers.
Change this:
for(int X = 1 ; X <= totalnumbers ; X++){
System.out.println("Please choose number " + X +": ");
list[X] = sc.nextInt();
average+=list[X];
To this:
for(int X = 0 ; X < totalnumbers ; X++){
System.out.println("Please choose number " + (X+1) +": ");
list[X] = sc.nextInt();
average+=list[X];
An array of totalnumbers items starts with index 0 and ends in index totalnumbers-1.
Your X iterates from 1 to totalnumbers, hence the exception when X reaches totalnumbers.
Related
Write a function that receives double-digit numbers, until a number that is not double-digit is received.
• For each number received the program will generate a reverse number and print it. For example : 67 will be printed 76.
• The program will print a count of some of the received numbers thet contains the digit 5 in the digit
Unity (right digit).
I researched the error I got a couple of times but couldn't solve it, if you guys can help much appreciated.
public static void switchInput() {
Scanner star = new Scanner(System.in);
int x=0 , temp=0 , y=1 , i , b=0;
x= star.nextInt();
int[] Switch = new int[x];
//input
for(i=0 ; i<y ; i++){
System.out.println("insert num "+ y + " :");
temp= star.nextInt();
x++;
y++;
Switch[i]=temp;
if(temp<10||temp>99) {
y=i;
}
if(temp%10==5) {
b++;
}
temp=0;
}
star.close();
//Switch
int j , temp2 , temp3=0;
for(j=0 ; j<x ; j++) {
temp3=Switch[j]/10;
temp2=Switch[j]%10;
temp3+=temp2*10;
Switch[j]=0;
Switch[j]=temp3;
}
//print
for(int z = 0;z<x-1;z++) {
System.out.print(" "+Switch[z]+ " ");
}
System.out.println("Number of times 5 was used is : " + b);
}
I got the error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 44 out of bounds for length 44
at hagashaShadi.q1.switchInput(q1.java:37)
at hagashaShadi.q1.main(q1.java:67)
See x= star.nextInt(); here your providing size of array suppose its x=3
which means int[] Switch = new int[3]; but when you are running for loop you are getting like this Switch[4] which is out of bound for the array of size 3. So solution is to use either while loop and insert only when it satisfy the condition and it should break once it cross size of array or if you want to use for loop then break out of loop when i>length-of-array
Have a look at the below code for more understanding
public static void switchInput() {
Scanner star = new Scanner(System.in);
int i=0 , countDigit=0;
List<Integer> numList=new ArrayList<>();
boolean isTwoDigitNumber=true;
//Insert all input number of 2 digit
while(isTwoDigitNumber)
{
System.out.println("insert num "+ (i+1)+ " :");
int temp= star.nextInt();
if(temp%10==5){
countDigit++;
}
if(temp>10&&temp<99) {
numList.add(temp);
i++;
}else {
isTwoDigitNumber=false;
}
}
star.close();
//Switch
//reverse the number and print
for(int j=0 ; j<numList.size() ; j++) {
int num = numList.get(j), reversed = 0;
//System.out.println("Original Number: " + num);
// run loop until num becomes 0
while(num != 0) {
// get last digit from num
int digit = num % 10;
reversed = reversed * 10 + digit;
// remove the last digit from num
num /= 10;
}
System.out.println("reverse Number: " + reversed);
}
//print number of times 5
System.out.println("Number of times 5 was used is : "+countDigit);
}
An assignment I am working on is asking me to modify a bar chart program they provided me with. So far I think I've got everything correct, although it specifies that "if a player has scored 48 points, then display four asterisks." However, my code displays five asterisks when a player has scored 48 points. How can I make it so that it only displays 4 asterisks? My instructor mentioned using integer division in my for loop which I did use, but that did not work.
import java.util.Scanner;
public class BarChart2 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int artPoints;
int bobPoints;
int calPoints;
int danPoints;
int eliPoints;
final int AMT_EACH_ASTERISK = 10;
System.out.println("Enter points earned for the season");
System.out.print(" by Art >> ");
artPoints = input.nextInt();
System.out.print(" by Bob >> ");
bobPoints = input.nextInt();
System.out.print(" by Cal >> ");
calPoints = input.nextInt();
System.out.print(" by Dan >> ");
danPoints = input.nextInt();
System.out.print(" by Eli >> ");
eliPoints = input.nextInt();
System.out.println("\nPoints for Season (each asterisk represents " +
AMT_EACH_ASTERISK + " points)\n");
drawChart("Art", artPoints, AMT_EACH_ASTERISK);
drawChart("Bob", bobPoints, AMT_EACH_ASTERISK);
drawChart("Cal", calPoints, AMT_EACH_ASTERISK);
drawChart("Dan", danPoints, AMT_EACH_ASTERISK);
drawChart("Eli", eliPoints, AMT_EACH_ASTERISK);
}
public static void drawChart(String name, int points, int amt_each) { // Main issue here
System.out.print(name + ": ");
int numAsterisks = points / amt_each;
for(numAsterisks = 0; numAsterisks < points; numAsterisks += amt_each)
System.out.print("*");
System.out.println();
}
}
Well, you're basically doing the correct calculation (integer division) here: int numAsterisks = points / amt_each; (this will result in 48/10 = 4).
However, you are then throwing that value away by reinitializing numAsterisks to 0 in your loop (for(numAsterisks = 0; ...)).
Instead do something like this:
for(int i= 0; i < numAsterisks; i++) {
System.out.print("*");
}
System.out.println();
Note that I added curly braces to the loop's body to make it clear what belongs into the loop and what doesn't. This is meant to prevent errors that could come from assuming that statements like System.out.println(); would be part of the body because of their indentation.
I need help validating input. I have a program that works with student grades based off user input. if someone enters grades below 0 or over 100 I want this loop to restart. Here is what I have so far:
double scores[] = new double[size];
for (int i = 0;i<= scores.length-1;i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
}
System.out.println("Here are your scores: " + Arrays.toString(scores));
I'm confused on how to implement invalid checker. I know it has something to do with a while loop. such as while a value is 0, and if someone enters invalid answer it will change from 0. But not sure how exactly I should do this, or if theres a better way
Any help appreciated. thanks
You can make use of a nested while loop and conditional statement for this:
for (int i = 0;i< scores.length;i++){
while(true){
System.out.print("\n\nScore number " + (i+1) + ": ");
int score = sc.nextInt();
if(score >= 0 && score <=100){
scores[i] = score;
break;
}else{
System.out.println("Error: score entered is outside allowable range");
System.out.println("Please try again");
continue;
}
}
}
You can simply ask the user to re-enter the value of the score which has been entered wrong.
double scores[] = new double[size];
for (int i = 0; i<= scores.length-1; i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
if(scores[i] < 0 || scores[i] > 100) {
i -= 1;
continue;
}
}
I'm confused on how to implement invalid checker. I know it has something to do with a while loop.
do-while loop is preferred in input validation because it allows input to be received first, then check if it passes the requirement. If input is invalid, repeat.
for(int i=0; i<scores.length; i++){
do{
System.out.print("\n\nScore number " + (i+1) + ": ");
input = sc.nextInt();
}while(input < 0 || input > 100);
scores[i] = input;
}
The for-loop and do-while loop serve different purpose. Hence, do not be confused by the
- for-loop which is only responsible to receive multiple inputs for the array and the
- while loop which is only responsible for validating every single input.
import java.util.Scanner;
import java.util.Arrays;
public class AttendanceManager {
public static void main(String args[])
{
System.out.println("Enter the number of students that are to be recorded.");
Scanner studentNum = new Scanner(System.in);
int x = studentNum.nextInt();
final int number[] = new int[x];
for(int i=0; i<x; i++)
{
System.out.println("Enter 1 if the student is present and 0 if the student is not.");
final Scanner attendance = new Scanner(System.in);
int inp = attendance.nextInt();
int y = inp;
switch (inp)
{
case 1:
number[y] = 1;
y = y++;
break;
case 0:
number[y] = 2;
y = y++;
break;
default:
System.out.println("Please enter 1 or 0.");
i--;
}
}
System.out.println("Total Students: " + number.length);
for(int k=0; k<number.length; k++)
{
if (number[k] == 1)
System.out.println("Student " + (k+1) + " is " + "present.");
else if (number[k] == 2)
System.out.println("Student " + (k+1) + " is " + "absent.");
else
System.out.println("error");
}
}
}
Output:
Enter the number of students that are to be recorded.
5
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
0
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
0
Total Students: 5
Student 1 is absent.
Student 2 is present.
error
error
error
why do the last 3 not get assigned to 1 or 0?
You're using the WRONG array index:
int inp = attendance.nextInt();
int y = inp;
switch (inp)
{
case 1:
number[y] = 1;
y = y++;
y is the value the user input, e.g. 1 or 0, which you then use as your number array index. But since the user only enters 1 or 0, you NEVER set array indexes 2, 3, 4, etc... So you're trying to output array entries that never got defined.
It should be
number[i] = 1;
^--
You are introducing another counter y which has no use, just keep the i one alone.
As the possible values of y where 0 or 1 , none of the other indexes of your array would be populated correctly.
Even worse with your current code :
Index 0 will always contain 1 if 0 was provided (0 otherwise)
Index 1 will always contain 2 if 1 was provided (0 otherwise)
Other indexes are never populated, and will always contain 0.
for(int i=0; i<x; i++)
{
System.out.println("Enter 1 if the student is present and 0 if the student is not.");
final Scanner attendance = new Scanner(System.in);
int inp = attendance.nextInt();
//int y = inp;
switch (inp)
{
case 1:
number[i] = 1;
break;
case 0:
number[i] = 2;
break;
default:
System.out.println("Please enter 1 or 0.");
i--;
}
}
Write a java programs that prompts the user to enter user's name and 4 numbers, reads them, then prints the smallest and largest of all the numbers typed in by the user. The program will continue looping if the largest number is greater or equal to 10. At the end, program will show how many times the program has looped. How can i loop and find how many times the program looped ?
import java.io.*;
import java.util.*;
class largestLoop
{
public static void main(String [] args) throws IOException
{
String name;
int[] num = new int[4]; // save 4 number in array
int smallest = num[0], largest = num[0];
do{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name : ");
name = stdin.readLine();
System.out.println(name + ", Please enter 4 numbers");
// Read for number using for loop
Scanner inData = new Scanner(System.in);
for(int i = 0; i < num.length; i++)
{
System.out.print("Enter " + (i+1) + " : "); // value i will + 1
num[i] = inData.nextInt();
}
// Find larger and smallest
for (int i : num)
{
if (i < smallest)
{
smallest = i;
} // end finding smallest
else if (i > largest)
{
largest = i;
} // end finding largest number
} // end finding largest and smallest values
System.out.println("Largest = " + largest);
System.out.println("Smallest = " + smallest);
}while(largest >= 10);
}
}
Output :
Enter your name : testing
testing, Please enter 4 numbers
Enter 1 : 2
Enter 2 : 6
Enter 3 : -5
Enter 4 : 16
Largest : 16
Smallest : 0
Enter your name : google
google, Please enter 4 numbers
Enter 1 : 5
Enter 2 : 8
Enter 3 : 1
Enter 4 : 6
Largest : 16
Smallest : 0
Enter your name : ....
The program become infinite loop. It should stop whenever user enter numbers that less than or equal to 10. The Largest and Smallest also does not right, when user enter <= 10 in next loop number. It will display a previous value or Largest. Also , the smallest keep display a 0 value.
First of all the assignment:
int smallest = num[0], largest = num[0];
is not dynamic in nature. Meaning the value of smallest and largest is not going to change everytime the value of num[0] changes. You need to do that manually everytime new values are entered.
Secondly you have not used any variable to actually count the number of loops.
Making these changes your code should look something like this:
package com.abhinav.testing;
import java.io.*;
import java.util.*;
class largestLoop
{
public static void main(String [] args) throws IOException
{
String name;
int[] num = new int[4]; // save 4 number in array
int smallest=0,largest=0;
int count=0;
do{
count++;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name : ");
name = stdin.readLine();
System.out.println(name + ", Please enter 4 numbers");
// Read for number using for loop
Scanner inData = new Scanner(System.in);
for(int i = 0; i < num.length; i++)
{
System.out.print("Enter " + (i+1) + " : "); // value i will + 1
num[i] = inData.nextInt();
}
smallest = num[0];
largest = num[0];
// Find larger and smallest
for (int i : num)
{
if (i < smallest)
{
smallest = i;
} // end finding smallest
else if (i > largest)
{
largest = i;
} // end finding largest number
} // end finding largest and smallest values
System.out.println("Largest = " + largest);
System.out.println("Smallest = " + smallest);
}while(largest >= 10);
System.out.println("Number of times the loop ran= "+count);
}
}