Java InputMismatchException? - java

I'm try to do an exception on my codes if ever the user puts a string instead of an integer. My codes will swap the position of the largest index to the smallest index. Can you try to rectify this with me?
import java.util.Scanner;
import java.util.InputMismatchException;
public class ArraySwap
{
static int h;
static Scanner data = new Scanner(System.in);
static int[] list = new int[10];
public static void main(String[] args)throws InputMismatchException
{
System.out.println("Please enter 10 numbers: ");
for(h = 0; h < list.length; h++)
{
try
{
list[h] = data.nextInt();
}
catch(InputMismatchException h)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ h.toString());
continue;
}
}
swap();
}
public static void printArray(int[] list)
{
int counter;
for(counter = 0; counter < list.length; counter++)
System.out.print(list[counter] + " ");
}
public static int smallestIndex(int[] list)
{
int length1 = list.length;
int counter;
int minIndex = 0;
for (counter = 1; counter < length1; counter++)
if (list[minIndex] > list[counter])
minIndex = counter;
return minIndex;
}
public static int largestIndex(int[] list)
{
int length2 = list.length;
int counter;
int maxIndex = 0;
for (counter = 1; counter < length2; counter++)
if (list[maxIndex] < list[counter])
maxIndex = counter;
return maxIndex;
}
public static void swap()
{
System.out.print("List of elements: ");
printArray(list);
System.out.println();
int min_index = smallestIndex(list);
int max_index = largestIndex(list);
int min_num = list[min_index];
System.out.println("Largest element in list is: "
+ list[max_index]);
System.out.println("Smallest element in list is: "
+ list[min_index]);
min_num = list[min_index];
list[min_index] = list[max_index];
list[max_index] = min_num;
System.out.print("Revised list of elements: ");
printArray(list);
System.out.println();
}
}

You are already doing exception handling on the integer inputs:
try
{
list[h] = data.nextInt();
}
catch(InputMismatchException h)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ h.toString());
continue;
}
}
Your issue is that in your catch block, you are naming your InputMismatchException object as h. This is also your loop count variable. Change that.
catch(InputMismatchException ex)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ ex.toString());
continue;
}
Also your second issue is that the print statement in your catch block is being automatically taken as Scanner input for your next loop. So the program isn't allowing input of any more numbers once an error string has been entered. What you need to do is first use a data.next() to consume your error message.
catch (InputMismatchException ex) {
System.out.print("Please re-enter 10 numbers as an exception "
+ ex.toString());
data.next();
}

Related

not sure why while loop isn't looping

I am trying to prompt the user to enter 5 integers but it won't loop more than once. I don't know why this is happening and couldn't resolve the error by myself
Code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int counter= 0;
Boolean inputOK;
int iInput;
int data[]= new int[5];
// while (counter<5);
do {
System.out.println(" Please enter an integer");
while (!s.hasNextInt()) {
System.out.println("Invalid input");
System.out.println("Please Enter an integer value");
s.next();}
iInput=s.nextInt();
if (iInput < -10 || iInput > 10) {
System.out.println("Not a valid integer. Please enter a integer between -10 and 10");
inputOK = false;
} else {
inputOK = true;
}
System.out.println("before while loop"+ inputOK);
} while (!inputOK);
counter++;
System.out.println("counter value is"+ counter);
}
}
If you follow your code, you can see that when inputOK is true, there is no loop to get back to. It looks like you had some counter in mind, but you ended up not using it. The following code does what I think you intended with your code:
Scanner sc = new Scanner(System.in);
int[] data = new int[5];
for(int i = 0; i < data.length; i++) {
System.out.println("Please enter an integer.");
// Skip over non-integers.
while(!sc.hasNextInt()) {
System.out.println("Invalid input: " + sc.next());
}
// Read and store the integer if it is valid.
int nextInt = sc.nextInt();
if(nextInt < -10 || nextInt > 10) {
// Make the for loop repeat this iteration.
System.out.println("Not a valid integer. Please enter an integer between -10 and 10.");
i--;
continue;
}
data[i] = nextInt;
}
for(int i = 0; i < data.length; i++) {
System.out.println("data[" + i + "] = " + data[i]);
}

Random numbers in array, user input number. If appears in array, user gets points

I know how to create the array as i did below. But how would i check if the user inputed the same number. I tried using if statements but i kept getting errors. I also tried using a do while.
I have to write a program that generates and stores 20 random numbers in the array Data[] and asks the user to enter their guess which i did. If their number appears in the array, they get 2 points for each occurrence, the array is printed and all positions where the lucky number can be found. If it doesn't appear in the array, I have to print the lowest and highest values of the array and allow only one more try. if the player gets it right the second time they get 1 point for each appearance.
int lucky;
int Data[]= new int[20];
for(int i=0;i<Data.length;i++){
Data[i]=(int)(Math.random()*100);
}
for(int i=0;i<Data.length;++i){
System.out.println(Data[i]+"\t");
}
String input1=JOptionPane.showInputDialog("Enter your lucky number");
lucky=Integer.parseInt(input1);
System.out.println(lucky);
Something like this should work as you expect to see if the value exists in the array, it can be expanded to search and find for high/low values:
int counter = 0; //Assume not found at first
for (int i: Data) {
if (i==Integer.parseInt(input1)){
counter++;
}
}
System.out.println("The numer was found "+Integer.toString(counter)+" time(s).");
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] data = new int[20];
int guess;
int times;
int score = 0;
int tries = 0;
fillArrayWithRandoms(data);
while (tries < 2) {
System.out.print("Guess a number: ");
guess = sc.nextInt();
if ((times = timesInArray(guess, data)) != 0) {
if (tries == 0)
score += 2 * times;
else
score += times;
printArray(data);
fillArrayWithRandoms(data);
System.out.println("You are lucky! Score: " + score + "\n");
} else {
tries++;
System.out.println("You are unlucky!");
if (tries < 2)
printBoundaries(data);
System.out.println();
}
}
System.out.println("Game Over! Your score: " + score);
}
private static void printArray(int[] data) {
for (int element : data) {
System.out.print(element + " ");
}
System.out.println();
}
private static void fillArrayWithRandoms(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = (int) (Math.random() * 100);
}
}
private static int timesInArray(int guess, int[] data) {
int occurrence = 0;
for (int element : data) {
if (element == guess)
occurrence++;
}
return occurrence;
}
private static void printBoundaries(int[] data) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int element : data) {
if (element < min) {
min = element;
}
if (element > max) {
max = element;
}
}
System.out.println("Try a number between " + min + " and " + max);
}
}

java array searching method

I have to make an array whose 10 numbers are chosen by the user through a scanner. The program orders the 10 numbers in ascending order, then prints out the new list. Then It asks the user to enter any number and then uses a binary search to see if the number is in the list of 10 numbers.
Here is what I have so far:
import java.util.Scanner;
public class lab11 {
public static void main(String[] args){
double[] numbers = new double[10];
System.out.println("Please enter 10 double values:");
for (int i=0;i<10;i++){
numbers[i] = inputArray();
}
System.out.println("sorting");
print(selectionSort(numbers));
System.out.println("Please enter a search key:");
}
public static double inputArray(){
Scanner input = new Scanner(System.in);
System.out.print(">");
double d = input.nextInt();
return d;
}
public static double[] selectionSort(double[] list){
double temp;
for(int i=0; i < (list.length-1); i++){
for(int j = i+1; j < list.length; j++){
if(list[j] < list[i]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void print(double[] arr){
for(double d:arr){
System.out.println("list["+j+"]"+" = "+d);
}
}
public static int binarySearch(double[]list, double key){
int low=0,high=list.length -1;
key =input.nextInt();
while(high>=low){
int mid=(low+high)/2;
if(key<list[mid])
high=mid-1;
else if(key==list[mid]) return mid;
else low=mid+1;
}
return-1;
}
}
I need help with 2 things.
(1) is under the Print method. I want the program to print out like "list[i] = d" The d a number that the user puts in and it works fine, but the i doesn't. I want it to be the array number which is 0 through 9.
(2) I need help with invoking the binary search so I can have an output for the search.
Just for the right input, you can write a do...while loop, which loops till the input is valid:
for (int i = 0; i < 10; i++) {
double number;
Scanner input = new Scanner(System.in);
do {
System.out.print(">");
number = input.nextDouble();
} while (number < 0 || number > 10);
}
}
For the output you seem to want use
// [...] perform the sorting [...]
// enter the search key
System.out.println("Please enter a search key:");
final int position = Arrays.binarySearch(numbers, input.nextDouble());
if (position < 0) {
System.out.println("key is not in the list");
} else {
System.out.println("key is at position " + position);
}
I would write like this
public static void main(String[] args) {
// initialize
double[] numbers = new double[10];
Scanner input = new Scanner(System.in);
// insert variables into array
inputArray(numbers, input);
// start sorting
System.out.println("sorting");
selectionSort(numbers);
// print the sorted array
print(numbers);
// binary search
binarySearch(numbers, input);
// close scanner
input.close();
}
public static void inputArray(double[] numbers, Scanner input) {
System.out.println("Please enter 10 double values:");
for (int i = 0; i < 10; i++) {
System.out.print(">");
numbers[i] = input.nextDouble();
}
}
public static void print(double[] numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.println("list[" + i + "]" + " = " + numbers[i]);
}
}
public static double[] selectionSort(double[] list) {
double temp;
for (int i = 0; i < (list.length - 1); i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[j] < list[i]) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void binarySearch(double[] numbers, Scanner input) {
System.out.println("Please enter a search key:");
double key = input.nextDouble();
int index = Arrays.binarySearch(numbers, key);
if (index < 0) {
System.out.println(key + " is not in the list");
} else {
System.out.println(key + " is in the list, index = " + index);
}
}

printing distinct numbers java

I am having a hard time with this code. The code is finished but the output is wrong.
My code prints Enter ten numbers: 1 2 3 5 6 6 8 7 4 1
It should print
The distinct numbers are:
1 2 3 5 6 8 7 4
but it doesn't. It prints:
10 10 10 10 10 7
How can I fix it?
Here is my code:
import java.util.*;
public class homework1 {
public static void main(String[] args){
// input from user
Scanner input = new Scanner(System.in);
int [] numbers = new int[10];
boolean[] distinct = new boolean[10];
System.out.println("Enter ten numbers");
for (int i=0; i<numbers.length; i++){
System.out.println("Number " + (i + 1) +": ");
numbers [i] = input.nextInt();
distinct[i] = true;
for(int j = 0;j<10; j++){
if(numbers[i] == numbers[j] && i != j) {
distinct[i] = false;
}
}
}
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=distinct.length;
count++;
}
}
System.out.println("The number of distinct number is: "+numbers[count]);
System.out.println("The distinct numbers are: ");
for(int i= 0; i < 10; i++) {
if(distinct[i]) {
System.out.print(numbers[i] + " ");
}
}
System.out.println();
}
}
This line:
numbers[count]=distinct.length;
Is setting your outputs to be the length of the array (Which in this case is hard coded to 10. Try:
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=numbers[j];
count++;
}
}
Which will set your output to be the distinct number.
Plug: Check out Code Review
This will solve your problem.
If you use HashMap, you will have less code.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> distinctNumbers = new HashMap<Integer, String>();
// input from user
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers");
for (int i = 0; i < 10; i++) {
System.out.println("Number " + (i + 1) + ": ");
Integer numberEntered = input.nextInt();
distinctNumbers.put(numberEntered, null);
}
System.out.println("The number of distinct number is: " + distinctNumbers.size());
System.out.println("The distinct numbers are: ");
Set<Integer> keys = distinctNumbers.keySet();
for (Iterator<Integer> iterator = keys.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.print(" "+ integer);
}
}
}
Remove line numbers[count] = distinct.length; This make your output are all 10
Then, I change your code a little to make it run right:
...
int count = 0;
for (int j = 0; j < 10; j++) {
if (distinct[j]) {
//numbers[count] = distinct.length; //remove it, it nonsense
count++;
}
}
// distinct number should be count, not number[count]
System.out.println("The number of distinct number is: " + count);
....
public static void main(String[] args) {
int arr[] = {1,3,5,4,7,3,4,7};
Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; i++) {
if(frequency.containsKey(arr[i])){
int value = frequency.get(arr[i]);
frequency.put(arr[i], value + 1);
}
else {
frequency.put(arr[i], 1);
}
}
for(Map.Entry<Integer, Integer> entry : frequency.entrySet()) {
System.out.println(entry.getKey());
}
}
package Chapter7;
import java.util.Scanner;
public class Exercise7_5 {
public static void main(String[] args) {
// Print distinct numbers
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers: ");
for (int i = 0, j = 0; i < 10; i++) {
if (storeDistinctNumbers(j,input.nextInt(), numbers))
j++;
}
for (int i = 0; numbers[i] != 0 ; i++)
System.out.print(numbers[i] + " ");
}
public static boolean storeDistinctNumbers(int j, int num, int[] numbers) {
for (int e: numbers) {
if (e == num)
return false;
}
numbers[j] = num;
return true;
}
}

My programs print statement is wrong

When i run my program and choose a number between 0 and 100, it prints my answer wrong.
Java console
----jGRASP exec: java TestScores
How many tests do you have? 3
Enter grade for Test 1: 80
Enter grade for Test 2: 80
Enter grade for Test 3: 80
The average is: 26.666666666666668The average is: 53.333333333333336The average is: 80.0
----jGRASP: operation complete.
import java.util.Scanner;
public class TestScores {
public static void main(String[] args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index] > 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++) {
totGrades += grade[index];
average = totGrades / grade.length;
System.out.print("The average is: " + average);
}
}
}
public class InvalidTestScore extends Exception
{
public InvalidTestScore()
{
super(" Error: Enter a number between 0 and 100");
}
}
You print the average inside the loop that calculates the average.
Print it only outside the loop.
You should calculate sum in loop and then (after the loop) divide it by the number of elements.
I move the statement which calculates the sum from inside the loop to the outside, that works.
My new code is.
import java.util.Scanner;
public class TestScores
{
public static void main(String[]args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index]> 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++)
{
totGrades += grade[index];
}
average = totGrades/grade.length;
System.out.print("The average is: " + average);
}
}
public class InvalidTestScore extends Exception
{
public InvalidTestScore()
{
super(" Error: Enter a number between 0 and 100");
}
}
You can close my post.

Categories

Resources