I got confused and didn't know what to add or change the loops.
Can someone please help me and tell me what I should do in order to run my code? It would be a big help to me. I'm only a beginner in Java...
**here's my code: **
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
System.out.println("Enter "+ size + " values: \n");
for(i=0; i < num.length; i++){
x = input.nextInt();
num[i]=x;
if ( num [i] == x );
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
if ( num[i] == search){
System.out.println (search + " is found in the array!");
}
else{
System.out.println ("Your number is not in the array.");
}
}
}
The sample output of my task is (using scanner):
Input the size of the array: 4
Enter the values:
14
15
16
17
Enter the search value: 14
14 is found in your input array.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
// System.out.println("Enter "+ size + " values: \n");
for(i=0; i < num.length; i++){
System.out.println("Enter Number to add at index "+i+" : ");
x = input.nextInt();
num[i]=x;
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
boolean condition=false;
for(i=0; i < num.length; i++){
if ( num[i] == search){
condition=true;
break;
}
}
if(condition==true){
System.out.println("Number is Array!");
}
else{
System.out.println("Number is not in array");
}
}
your code is to be like this
there is logical error's in your code
to find an element you must traverse through array which can be achieved using loop so the last if else statement in your code must be in a loop
as due to the post increment in first loop after the completion of loop the value of i is one greater than last index of array so in if else statement at if ( num[i] == search) index is not found in array due to which it generates error.
for example I enter array size 3 and at num[0] I enter 1 at num[1] I enter 2 and at num[2] I enter 3 after the loop finishes the value of i become 3 when it come to conditional statement (if else) so it become if(num[3] == search ) but 3 index is not present in array so it generates error.
You need a loop to compare each element of the array with the search value.
boolean found = false;
for (int x : num)
if (x == search) {
found = true;
break;
}
System.out.println(found ? search + " is found in the array!" : "Your number is not in the array.");
Alternatively, with streams:
System.out.println(Arrays.stream(num).anyMatch(x -> x == search) ?
search + " is found in the array!" : "Your number is not in the array.");
Scanner input = new Scanner (System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
System.out.println("Enter "+ size + " values: \n");
for (i = 0; i < num.length; i++)
{
x = input.nextInt();
num[i] = x;
if (num[i] == x);
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
boolean flag=false;
for( i=0;i<num.length;i++)
{
if (num[i] == search) {
flag = true;
System.out.println(num[i]+" is found in your input array");
break;
}
}
if (flag==false)
{
System.out.println("Your number is not in the array.");
}
}
[Screenshot][1]
Related
I'm a beginner in Java programming and I created a program that accepts 10 numbers as input from users and prints them. The first section is using for loop and the second section is using while loop. The first section works properly and the second section isn't displaying output. Could anybody help me?
import java.util.Scanner;
public class ArrayOfTenElements {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numArray1[] = new int [10];
int numArray2[] = new int [10];
int i;
//First Section
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
for(i=0;i<10;i++) {
numArray1[i] = scanner.nextInt();
}
System.out.println("The entered numbers are: ");
for(i=0;i<10;i++) {
System.out.print(numArray1[i] + " ");
}
//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
numArray2[j] = scanner.nextInt();
j++;
}
System.out.println("The entered numbers are: ");
while(j<10) {
System.out.print(numArray2[j] + " ");
j++;
}
scanner.close();
}
}
You are not resetting variable j back to 0 after the 1st loop. so the 2nd loop starts with a value of 10 for j, and hence, while loop is not executed.
//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
numArray2[j] = scanner.nextInt();
j++;
}
// add this
j = 0;
System.out.println("The entered numbers are: ");
while(j<10) {
System.out.print(numArray2[j] + " ");
j++;
}
When you use last for loop j value is 10 in the beginning of that loop
as you declare j out of the scope.So you should declare new variable
and replace while loop from it.The other thing is you should use for
loop to showing array2.Normally we use while loops for only when we
not knowing about end time.So we use for loop for this.
//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
numArray2[j] = scanner.nextInt();
j++;
}
System.out.println("The entered numbers are: ");
for(i=0;i<10;i++) {
System.out.print(numArray2[i] + " ");
}
When the program asks the user to input 10 elements (numbers), but the user entered any letter or word, I want the program to display "INVALID INPUT". I tried an if statement but it doesn't work. Any help is much appreciated!
This is my code:
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i < 10; i++) {
Array[i] = input.nextInt();
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
System.out.print("Element at index "+index+" is " + Array[index]);
}
}
You can use a try-catch and catch a InputMismatchException, where you can then handle it accordingly.
Like so:
try{
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i < 10; i++) {
Array[i] = input.nextInt();
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
System.out.print("Element at index "+index+" is " + Array[index]);
}catch(InputMismatchException e){
System.out.println("INVALID INPUT");
}
For example, when I input:
spectric is not cool
I get:
INVALID INPUT
Because spectric is cool
Try the following: You need to catch the input mismatch and then continue taking input. It is important to update the loop counter to allow for all 10 inputs to be taken.
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i < 10; i++) {
try {
Array[i] = input.nextInt();
} catch(InputMismatchException ie) {
System.out.println("Bad input - please re-enter");
i--; // update loop;
input.nextLine();// clear bad input from buffer scanner.
}
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
System.out.print("Element at index "+index+" is " + Array[index]);
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;
}
}
Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.
My problem is that for example there's only three passing grades, the user entered then the size of passGrade array would only be three, same with failGrade: if the user entered two failing grades then the size of failGrade array would only be two, in short I want the two arrays to be of fixed lengths. In my program it goes out of bounds.
Here's the piece of code I'm referring to:
Scanner input=new Scanner(System.in);
int gradeSize=0;
int fixedPassed=0;
int fixedFail=0;
int grades[]=new int[gradeSize];
int passGrade[]=new int[fixedPassed];
int failGrade[]=new int[fixedFail];
System.out.print("Enter Grade Size: ");
gradeSize=input.nextInt();
System.out.println();
System.out.print("Enter Grades: ");
for(int i=0; i<gradeSize; i++)
{
grades[i]=input.nextInt();
while(grades[i]<1 || grades[i]>100)
{
grades[i]=input.nextInt();
}
if(grades[i]>=75)
{
fixedPassed++;
passGrade[i]=grades[i];
}
else if(grades[i]<75)
{
fixedFail++;
failGrade[i]=grades[i];
}
}
for(int i=0; i<fixedPassed; i++)
{
System.out.print(passGrade[i]+" ");
}
for(int i=0; i<fixedFail; i++)
{
System.out.print(failGrade[i]+" ");
}
Java arrays are fixed size. So you need to get the input, then count the pass/fails. Then create your pass fail arrays and then copy the grades into them. You could do something like this,
System.out.print("Enter Grade Size: ");
int gradeSize = input.nextInt();
int passCount = 0;
int grades[]=new int[gradeSize];
System.out.println();
System.out.print("Enter Grades: ");
for (int i = 0; i < gradeSize; i++) {
grades[i] = input.nextInt();
if(grades[i] >= 75) {
passCount++;
}
}
int passGrade[] = new int[passCount];
int failGrade[] = new int[grades.length - passCount];
int failCount = passCount = 0;
for (int grade : grades) {
if (grade >= 75) {
passGrade[passCount++] = grade;
} else {
failGrade[failCount++] = grade;
}
}
System.out.println("Passing Grades: " + Arrays.toString(passGrade));
System.out.println("Failing Grades: " + Arrays.toString(failGrade));
Since you don't know in advance the length of the input, and you don't know in advance how many passed and how many failed, you can't create the arrays before first processing the input.
You should use 3 collections (HashSet, ArrayList, etc ...) to store the input grades, passed grades and failed grades. Once you are done, you can initialize your 3 arrays based on the size() of the collections, and then iterate over the collections to copy their contents to the arrays.