Fairly easy question, but I was basically given code to debug and I've fixed all errors but one. When trying to make the program more friendly and include error handling, I found that the error message is thrown even if the condition is satisfied (that is, the number in the array that a user searches for actually exists within the array). Not looking for a direct answer, just a hint. I've tried using combinations of if/else as well as moving around curly braces.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find: ");
try {
int number = input.nextInt();
int index = Arrays.binarySearch(array, number);
for (int i = 0; i < array.length; i++) {
if ( array[i] == number )
System.out.println("Found " + number + " at index " + index++);
}
System.out.printf("Your number was not found within the array.");
}
catch (InputMismatchException e){
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}
}
Console output example:
Enter an integer to find: -9
Found -9 at index 0
Your number was not found within the array.
Array.binarySearch will return the index if it finds the value, otherwise it will return -1.
If index == -1, you can print the "not found message" without entering the loop at all.
Otherwise, if index > 0, then you can enter the loop and iterate over the array to find each index where the value is a match.
This is required if you want a message for multiple matches as binarySearch will just return the the first index the value was found at.
As an aside, binarySearch requires the array to be sorted first, otherwise the results will be undefined. I don't know if this is a problem as array is declared outside of the example.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find: ");
try {
int number = input.nextInt();
int index = Arrays.binarySearch(array, number);
if (index > 0) {
for (int i = 0; i < array.length; i++) {
if ( array[i] == number ) {
System.out.println("Found " + number + " at index " + i);
}
}
} else {
System.out.printf("Sorry, your number wasn't found.");
}
}
catch (InputMismatchException e) {
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}
in your code:
"Your number was not found within the array." will always be printed unless there is an exception caught by catch block
also one interesting thing about binary search is :
if an element is not present in the array, it returns negative of the probable position if the searched element "would have been" present.
Example : in this program, if you search for 9,it will return -3
if you search for 65,it will return -6
This will work correctly:
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class debug {
public static void main(String...args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find: ");
int i, array[]={-9,8,14,56,64};
try {
int number = input.nextInt();
int index = Arrays.binarySearch(array, number);
if(index>=0)
System.out.println("Found " + number + " using binary search at index " + index);
else
System.out.println("Not Found !! index returned by binary search is : "+index);
boolean flag=false;
for (i = 0; i < array.length; i++) {
if ( array[i] == number ){
flag=true;
break;
}
}
if(flag)
System.out.println("Found " + number + " using for loop at index " + i);
else
System.out.printf("Your number was not found within the array.");
}
catch (InputMismatchException e){
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}
}
}
The condition inside the loop is wrong. If the first element of the array isn't the value you were looking for, it immediately terminates. The error handling must be after the loop. Try this:
boolean found = false;
for (int i = 0; i < array.length; i++) {
if ( array[i] == number ){
System.out.println("Found " + number + " at index " + index++);
found = true;}
}
if(!found)
throw new IllegalArgumentException("Your number was not found within the array.");
Related
The below while loop runs an extra time. I am trying to perform a user input that accepts 10 valid numbers from the user and prints their sum. However, the while loop executes an extra time and asks for the 11th input.
import java.util.Scanner;
class userInput{
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i++;
System.out.println("Enter number " + "#" +i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
}else{
System.out.println("Invalid Input");
}
}
System.out.println("The sum of your entered numbers are = " + sum);
}
}
In addition to those great comments, you should probably only increment "i" if you get a VALID input:
while(i <= 10) {
System.out.print("Enter number " + "#" +i + ": ");
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
i++;
}else{
System.out.println("Invalid Input");
sc.next();
}
}
Note that when you have a bad input you need to get rid of it with "sc.next()".
First - make sure you're formatted correctly.
(I've indented your loops, moved your output into the main class, fixed up some curly brackets/loop endings).
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i++;
System.out.println("Enter number " + "#" +i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
}
else{
System.out.println("Invalid Input");
}
}
System.out.println("The sum of your entered numbers are = " + sum);
}
Alright - so running the code, I've found there are the correct amount of times asked, but the input prompt is displaying the wrong number with the first input prompt starting on 2, the last one on 11.
The reason for this is the i++ runs before asking for an input, thus it counts up before outputting.
This can easily be fixed by moving said i++ to just underneath the else clause - as follows:
else{
System.out.println("Invalid Input");
}
i++
}
the main problem here is that you're increasing the variable at the start of your while loop. If that's what you're looking for then that's fine, but if you want to stop the loop when it hits 10 you'll need to have it like while(i < 10) if the i++ were at the end of the loop, then you could do while(i <= 10)
Ex:
i = 0;
while(i < 10){
i++;
//code here
}
this will make the code that uses i use the values between 1 and 10. using <= will use the values between 1 and 11.
another example:
i = 0;
while(i < 10){
//code here
i++;
}
this will make the code that uses i use the values between 0 and 9. using <= will use the values between 0 and 10.
another way people do an incremental loop is doing a for loop rather than a while loop
this would look like:
for(int i = 0; i < 10; i++){
//code here
}
this also allows you to create a variable that will only be inside the loop, so rather than making it at the beginning of the method or before the loop, you could make it inside the for loop. This is not good if the variable is used elsewhere though.
Currently in programming fundamentals course and I'm having some trouble finalizing my code. I know it's super sloppy, but I've invested a lot of time trying to figure this out. Everything works except the final println statement. I can't get it to print out at the right time. It always prints even when the value is found. I know the problem lies in the final if statement, but I honestly can't figure out what to put in there. Thanks for any help.
System.out.print("\n\nPlease enter number to search for: ");
Scanner scan = new Scanner (System.in);
int search = scan.nextInt();
int index = 1;
for (int numb : unsortedArray) {
if (numb == search)
System.out.println("\nSearch Value: " + numb + " is found at location: " + (index) +" in the unsorted array.");
index++;
}
for (int numb : sortedArray) {
if (numb == search)
System.out.println("\nSearch Value: " + numb + " is found at location: " + (index -10) +" in the sorted array.");
index++;
}
if (search != 1) {
System.out.println("Search Value: " + search + " was not found.");
}
The issue is that you are checking if the search variable is not equal to 1, where search is the input you are receiving from the console from the user.
if (search != 1) {
System.out.println("Search Value: " + search + " was not found.");
}
This doesn't seem quite right to me, cause it looks like you are only wanting to print this out if you were unable to find that value in both the unsorted and sorted arrays that you have.
Instead, I suggest creating a boolean before all of your for loops and set it to false... If you find the value in either of the arrays, set it to true!
Finally, change the final if statement to check to see if we found the value in the arrays. (i.e. if the boolean is true.)
My program is supposed to make sure each value the user enters is between 10-100. The value is then stored in the array. That part works fine. The other condition is that the value the user enters has to be different from all the other arrays. ie...array[0]=20 so all of the other arrays can no longer equal to be set to 20. I've been trying to solve this but I'm just not sure where to go. I tried setting statements after my while(userInput < 10 || userInput > 100) to check for any repeats and that worked. The problem was then the user could enter values less than 10 and greater than 100. Any help would be greatly appreciated!
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
for(int x = 0; x < array.length; x++)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
while(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100: ");
userInput = input.nextInt();
}
array[x] = userInput;
System.out.println(array[x]);
counter++;
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
}
You should get rid of the for and second while loop, and check if the value entered is in the desired range.
If it is, you verify for duplicates, store it in the array and increment the counter. If it’s not, you show the bad input message.
Either way, it continues to ask for an valid input until the counter gets to 5.
I hope it helps!
I changed your logic a little bit, see if you can understand it
(There are better ways of doing this, but I think this is more understandable)
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
if(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100.\n");
}
else {
//This is a valid input, now we have to check whether it is a duplicate
boolean isItDuplicate = false;
for(int i = 0; i < counter; i++)
{
if(userInput == array[i])
{
isItDuplicate = true;
}
}
if(isItDuplicate == true)
{
System.out.print("Please enter a number that is not a duplicate.\n");
}
else
{
array[counter] = userInput;
System.out.println(array[counter]);
counter++;
}
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
Don't use variable counter when var x does the same thing for you.
Don't use nested loops when the limiting condition of both loops need to be checked together in each iteration. Merge those loops into one wherever possible.
First of all, get rid of your nested loops. They're redundant. Let's look at your problem's specification. Your input needs to fulfill 3 requirements:
Be greater than or equal to 10
Be less than or equal to 100
Be a unique element inside the array
The first two conditions are simple enough to check. For the final condition, you need to search the values inside the array and see if there are any matches to your input. If so, the input is invalid. A simple way to approach this is to check every member of the array and to stop if a duplicate is found. There are better, more efficient ways to do this. Don't be afraid to search the internet to learn a searching algorithm. Below is a simple solution to your problem. It's far from ideal or efficient, but it's easy enough for a beginner to understand.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
int userInput;
while(counter < 5) {
System.out.print("Enter a number between 10 & 100: ");
userInput = in.nextInt();
if( (userInput >= 10 && userInput <= 100) && !searchDuplicates(array, userInput) ) {
array[counter] = userInput;
counter++;
} else {
System.out.println("Invalid value entered");
}
}
for(int i = 0; i < array.length; i++)
System.out.println("Value " + (i + 1) + ": " + array[i]);
}
private static boolean searchDuplicates(int[] array, int input) {
for(int i = 0; i < array.length; i++)
if(array[i] == input)
return true;
return false;
}
}
I want this to start over if the try fails. I have found many answers to vaguely similar situations, but not with the for loop and with my structure. Doing this is not required and will not benefit my assignment, but I just want to do it. The program works as it is required to and beyond (yes this is very beginner stuff). I've tried and tried with do...while and for loops, and I either get infinite loops, can't find symbol, etc. I know if I keep trying I will get it, and I also have a hunch about some of my mistakes, but I really want someone experienced to look at this and make a suggestion.
try{
System.out.print("Please enter an integer: ");
int original = sc.nextInt();
int entry = Math.abs(original);
String str = new Integer(entry).toString();
int len = str.length();
System.out.println();
System.out.println("The entry is " + len + " digits long.");
System.out.println();
System.out.print("The digits entered are: ");
int runningTotal;
int ttl = 0;
for (int i=1; i<=len; i++){
System.out.print(str.charAt(i-1) + " ");
char num1 = str.charAt(i-1);
String num2 = Character.toString(num1);
runningTotal = Integer.parseInt(num2);
ttl = ttl + runningTotal;
}
System.out.println("\n");
System.out.println("The sum of the digits entered is: " + ttl + "\n");
}
catch (InputMismatchException imeRef){
System.out.println("Data type error: " + imeRef.toString() +"\n"
+ "No letters or special characters allowed.");
}
Do you really need to put the whole thing in a try..catch block? Wrap only the bit that's error prone.
In any case, this code is in a function - if you really want to start over on error, try this:
void foo() {
try {
doSomeDangerousThing();
catch(Exception e) {
foo()
}
}
Of course, this is a dangerous game to play - if it raised an error on the last call, why won't it on this call, if nothing changed? You potentially create a deadly infinite loop. Unless the parameters change, the error will most likely recur.
If you want to just run code over and over and over, use a while loop.
using while loop
try this
while(true){
try{
Scanner sc = new Scanner(System.in);
System.out.print("Please enter an integer: ");
int original = sc.nextInt();
int entry = Math.abs(original);
String str = new Integer(entry).toString();
int len = str.length();
System.out.println();
System.out.println("The entry is " + len + " digits long.");
System.out.println();
System.out.print("The digits entered are: ");
int runningTotal;
int ttl = 0;
for (int i=1; i<=len; i++){
System.out.print(str.charAt(i-1) + " ");
char num1 = str.charAt(i-1);
String num2 = Character.toString(num1);
runningTotal = Integer.parseInt(num2);
ttl = ttl + runningTotal;
}
System.out.println("\n");
System.out.println("The sum of the digits entered is: " + ttl + "\n");
break;
}
catch (InputMismatchException imeRef){
System.out.println("Data type error: " + imeRef.toString() +"\n"
+ "No letters or special characters allowed.");
}
}
Try making a method:
public int askForInt() {
int input;
try {
input = sc.nextInt();
}
catch(InputMismatchException imeRef) {
System.out.println(" Try again, etc...");
askForInt();
}
return input;
}
and then after you ask the user for the integer the first time just call the method:
System.out.print("Please enter an integer: ");
int original = askForInt();
// proceed
When the user types a value it checks if it exists in an array.
import java.util.Scanner;
public class array1 {
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a value");
int num = scan.nextInt();
int [] arraynumbers = {1,2,3,4,5,6,7,8,9,10};
for(int i = 0; i < arraynumbers.length; i++) {
if (arraynumbers[i] == num){
System.out.println("The value you have entered " + num + ", exists in the array");
}else{
System.out.println("The value you have entered does not exist in the array");
}
}
}
}
So, when ever I type a number to test it prints:
Enter a value
3
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered 3, exists in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
I am not 100% sure why this happens.
Questions
Is it because there is nothing stopping it from finishing when it finds a number in the array?
Is there a way to prevent this?
Thank you
You are probably looking out for a break. The entire loop is traversed even if your num is found. And either of the if or else block is executed. This would help you :
if (arraynumbers[i] == num) {
System.out.println("The value you have entered " + num + ", exists in the array");
break;
}
and probably to avoid printing anything in case the value is not matched you can remove the else block from your code.
The break statement is definitely key. However, if you want to print whether the number is found or not, you may want to consider something like this:
int num = scan.nextInt();
int [] arraynumbers = {1,2,3,4,5,6,7,8,9,10};
String srchStr = "does not exist";
for(int i = 0; i < arraynumbers.length; i++) {
if (arraynumbers[i] == num) {
srchStr = "exists";
break;
}
}
System.out.println("The value you have entered " + num + ", " + srchStr + " in the array");
When you put that check in a loop like this, it means you check every number in the array:
for(int i = 0; i < arraynumbers.length; i++) {
}
You could do this:
List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
if (values.contains(num)) {
System.out.println("The value you have entered " + num + ", exists in the array")
} else {
System.out.println("The value you have entered does not exist in the array");
}