Input Mismatch Exceptions - java

I've been instructed to create a code that takes a user's first 5 inputs (doubles) and finds the average. My only problem is creating an exception if a user inputs anything other than a number. Could someone show how I can add this exception to my code?
import java.util.*;
public class Test1
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
System.out.println("Please enter a number: ");
double first = numbers.nextInt();
System.out.println("Please enter a number: ");
double second = numbers.nextInt();
System.out.println("Please enter a number: ");
double third = numbers.nextInt();
System.out.println("Please enter a number: ");
double fourth = numbers.nextInt();
System.out.println("Please enter a number: ");
double fifth = numbers.nextInt();
System.out.println("The average is\t" + ((first + second + third + fourth + fifth)/5)+"\t");
}
}

This will handle the user typing non Integers.
It also removes the static Scanner userInput which isn't being used.
public class HelloWorld
{
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
int total =0;
int numberOfQuestion = 5;
for (int i = 0; i < numberOfQuestion ; i ++) {
System.out.println("Please enter a number: ");
while (!numbers.hasNextInt()) {
System.out.println("Input was not a number, please enter a number: ");
numbers.next();
}
total = total + numbers.nextInt();
}
System.out.println("The average is\t" + (total/numberOfQuestion)+"\t");
}
}

Related

How to add to java code that will ask user to enter an amount from 1 to 1000

Java program that will:
User can input an amount from 1.00 to 1,000.00
Any amount beyond the allowed range will display an error.
This block of code below is prints the number entered by an user:
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Creates a reader instance which takes
// input from standard input - keyboard
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
// nextInt() reads the next integer from the keyboard
int number = reader.nextInt();
// println() prints the following line to the output screen
System.out.println("You entered: " + number);
}
}
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
double number;
System.out.print("Enter a number from 1.00 to 1,000.00: ");
number= reader.nextDouble();
//As long as the input is not within the range requests a new input
while (!(number>=1.00 && number<=1000.00)){
System.out.print("Input arrival!\nEnter a number from 1.00 to 1,000.00: ");
number= reader.nextDouble();
}
System.out.println("You entered: " + number);
}
note: The number range you specified corresponds to a double type

Scanner doesnt read input in else statement

Im trying to ask the user for two numbers. I want to check if those inputs are in fact numbers but the code I have so far does not let me enter a second value if the first input is a string.
So the scanner does not read anything the else statement.
How could I make it work?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fname = console.nextLine();
System.out.print("Please enter your last name: ");
String lname = console.nextLine();
System.out.print("Please enter your first number: ");
if (console.hasNextInt()) {
int number1 = console.nextInt();
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
}
} else
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
// this part does not work
}
}
}
You just need to add console.nextLine(); after your else statement, because the Scanner.hasNextInt method does not move cursor past your previous input (if it is a string).

How do I enter values from a loop into an array list?

this is my code:
public static void main(String[] args) {
System.out.println("Please enter the number of values you would like to enter: ");
Scanner scan = new Scanner(System.in);
int intNumberOfNumbers = scan.nextInt();
for (int i = 0; i < intNumberOfNumbers; i++) {
System.out.println("Please enter a value for index " + i + ":");
int intValue = scan.nextInt();
}
}
What I'm trying to do is create a scanner that asks how many values they want to enter and whatever that value is, that's how many times it asks for number input. The problem is after I ask the question how can I add the number to an array list?
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int numOfInput=sc.nextInt();
ArrayList<Integer> array=new ArrayList<Integer>();
while(numOfInput-->0){
array.add(sc.nextInt());
}
}
public static void main(String[] args) {
System.out.println("Please enter the number of values you would like to enter: ");
Scanner scan = new Scanner(System.in);
int intNumberOfNumbers = scan.nextInt();
ArrayList<Integer> myArray= new ArrayList<>();
for (int i = 0; i < intNumberOfNumbers; i++) {
System.out.println("Please enter a value for index " + i + ":");
int intValue = scan.nextInt();
myArray.add(intValue);
}
}

Using a for loop to read ONLY 5 numbers and average them. JAVA

Really having issues with this program I'm making. I've searched this site and a few others, although have yet to find a solution. It may look like I'm just soliciting help but I truly am stuck. I am to make a program that reads in 5 numbers from the user and average those numbers. My extent of knowledge of Java is the Scanner class and for loops, yet haven't used while loops yet. Here is the very poorly written code:
public class Average5
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int num;
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
num = sc.nextInt();
}
I honestly have no clue what to do. More or less self taught.
public class Average5 {
public static void main(String args[]) {
int numlenngth = 5;
double total = 0;
Scanner sc = new Scanner(System.in);
for (int num1 = 0; num1 < numlenngth; num1++) {
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : " + (total / numlenngth));
}
}
output >>
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 2
Average : 1.2
For calculating exact average, you need to take double(sum) instead of int and add(sum) everytime with the user value.
public class Average5
{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to enter for calculating average: ");
int totalCount = sc.nextInt();
double sum=0;
for(int i= 0; i<totalCount; i++)
{
System.out.print("Please enter a number: ");
sum += sc.nextDouble();
}
System.out.println("Average of number is"+(sum/totalCount));
}
This is almost the same as the others posted, but it is limited to entering only 5 numbers and it takes care of possibly resulting floating number in the final division:
import java.util.Scanner;
public class Average5 {
private static final int TOTAL = 5;
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
double sum = 0;
System.out.format("You have to enter %d numbers now.\n", TOTAL);
for (int cnt = 1; cnt <= TOTAL; cnt++) {
System.out.format("Please enter number %d of %d: ", cnt, TOTAL);
sum += scanner.nextInt();
}
System.out.format("The average is %f.\n", sum / TOTAL);
scanner.close();
}
}
Here you can use the array to store the numbers:
public class Average5 {
private static final int MAX = 5;
public static void main(String[] args) {
int[] numbers = new int[MAX];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < MAX; i++) {
System.out.println("Please type the number");
numbers[i] = sc.nextInt();
}
float average = getAverage(numbers);
System.out.println("The average of the five numbers: " + average);
}
public static float getAverage(int[] arg0) {
int sum = 0;
float Ret = 0.0f;
if(arg0 != null) {
for(int i = 0; i < MAX; i++) {
sum += arg0[i];
Ret = sum / MAX;
}
return Ret;
}
}
This is not the only way to slove this problem.
int num = 0;
float total = 0f;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : "+(total/num));

getting an average of students graded test scores

Read in information for ALL students before doing any calculations or displaying any output. Verify
that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered.
Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid,
display an error message and allow the user to re-enter that invalid score. Once all student info is read
in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s
exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade,
based on the following percentages:
90-100 A, 80-89.9 B, 70-79.9 C, 60-60.9 D, Below 60 F
This is what i have typed out already but its giving me some errors and I'm not sure I'm assigning the values correctly.
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
int [] exams = new int[4];
int student = 1;
do
{
String [] names = new String[student];
System.out.print("PLease enter the name of student" + student );
names[student-1] = s.nextLine();
for ( int i = 1; i < exams.length; i++){
if(i==4){
System.out.print("Please enter score for Final Exam: ");
}
System.out.print("Please enter score for Exam" + i);
exams[i] = s.nextInt();
if((exams[1]<0||exams[1]>50)||(exams[2]<0||exams[2]>50)||(exams[3]<0||exams[3]>50)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[4]<0||exams[4]>100){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
System.out.println("do you wish to enter another?");
again = s.nextLine();
student++;
}while (again.equalsIgnoreCase ("y"));
}
}
This is the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Proj4.main(Proj4.java:32)
But its confusing because line 32 is just a } so i really don't know exactly what it means,
i know i probably need to reduce the length of one of the inputs for the arrays but I'm not sure which or if there's even more wrong than that.
EDIT:
Sorry here is my question, Would you guys help me figure out the problem and/or tell me if or what i am doing wrong to get the output required of me?
Array exams has 4 elements only but you try to access 5th element with index 4 here exams[4]<0. First index of array is 0 (not 1).
Does the below work for you?
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String again = "y";
int[] exams = new int[4];
int student = 1;
do {
String[] names = new String[student];
System.out.print("PLease enter the name of student" + student);
names[student - 1] = s.nextLine();
for (int i = 0; i < exams.length; i++) {
System.out.println(i + " i");
if (i == 3) {
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
if (exams[3] < 0 || exams[3] > 100) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
} else {
System.out.print("Please enter score for Exam " + i);
exams[i] = s.nextInt();
if ((exams[i] < 0 || exams[i] > 50)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.println("do you wish to enter another?");
again = s.next();
student++;
} while (again.equalsIgnoreCase("y"));
}

Categories

Resources