Array element search - java

I am new to java and have been trying to write how to search multidimensional arrays. My code works for elements found but when I enter an element that does not match, it does not printout anything. Please tell me what's wrong with my code.
import java.util.Scanner;
public class ArraySearch {
public static void main (String[] args){
Scanner input = new Scanner(System.in);
//lets create the array
int [] [] arrayOfInts = {{1, 2,3,4}, {5,6,7,8},{9,10,11,12}};
//create search variables
System.out.println("Enter the key number to search for in the array: ");
int key = input.nextInt();
boolean foundIt;
//perform search using a for loop
for (int i = 0; i <arrayOfInts.length; i++){
for (int j = 0; j <arrayOfInts[i].length; j++){
if (arrayOfInts[i][j] == key) {
foundIt = true;
if (foundIt) {
System.out.println("found " + key + " at row " +i+ " column " +j);
} else {
System.out.println(key + "is not in the array");
}
}
}
}
}
}

You should initialize your boolean to false, since local variables must be initialized before being used :
boolean foundIt = false;
Otherwise, if the key wasn't found, foundIt would be uninitialized when you access it in your if condition.
Not initializing foundIt should have given you a compliation error (The local variable foundIt may not have been initialized), but you have another error that hid this error. Your if statement that prints the output should be outside the for loops. Now it's inside the condition that finds a match, so it would only be evaluated if you found a match.

You can change your code to following. There are many issues in your code. You have to make correct order of {}, If you do so you needs to initialize foundIt
Scanner input = new Scanner(System.in);
//lets create the array
int[][] arrayOfInts = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
//create search variables
System.out.println("Enter the key number to search for in the array: ");
int key = input.nextInt();
boolean foundIt = false;
for (int i = 0; i < arrayOfInts.length; i++) {
for (int j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == key) {
System.out.println("found " + key + " at row " + i + " column " + j);
// if found it will change the foundIt to true
foundIt = true;
}
}
}
if (!foundIt) {
System.out.println(key + "is not in the array");
}

Your bracketing is wrong. The if - else statement
if (foundIt) {
System.out.println("found " + key + " at row " +i+ " column " +j);
} else
{System.out.println(key + "is not in the array");
}
Is inside the check of the for loop.
if (arrayOfInts[i][j] == key) {
You probably want to have it inside of the for loop to show the message for each match. But then you should just put a println message inside the if statement in the for loop
if (arrayOfInts[i][j] == key) {
System.out.println("found " + key + " at row " +i+ " column " +j);
And to print the other message when the key was never found, but this has to be done at the end. Make sure you initialize the boolean in the beginning!
boolean foundIt = false;
...
//at the end
if(!foundIt) {
System.out.println("found " + key + " at row " +i+ " column " +j);
}

// perform search using a for loop
for (int i = 0; i < arrayOfInts.length; i++) {
for (int j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == key) {
System.out.println("found " + key + " at row " + i + " column "
+ j);
return;
}
}
}
System.out.println(key + "is not in the array");
I just added a return on finding the desired element and cut/paste the else branch to the end of the loop.

Your System.out is only inside this if-block
if (arrayOfInts[i][j] == key)
so if you don't find something the is no printout
I would do it in this way:
...
for (int i = 0; i <arrayOfInts.length; i++){
for (int j = 0; j <arrayOfInts[i].length; j++){
if (arrayOfInts[i][j] == key) {
foundIt = true;
// Tell where you found it
System.out.println("found " + key + " at row " +i+ " column " +j);
}
}
}
// After all check whether you found something anytime
if(!foundIt){
System.out.println(key + "is not in the array");
}
...

It's because your print statements the if (foundIt) ... else block is within the if (arrayOfInts[i][j] == key) block. This means that if the int is not found, the code never enters that inner if check where you print.
You can move the "not found" to the end.
For example:
boolean foundIt = false;
// perform search using a for loop
for (int i = 0; i < arrayOfInts.length; i++)
{
for (int j = 0; j < arrayOfInts[i].length; j++)
{
if (arrayOfInts[i][j] == key)
{
foundIt = true;
System.out.println("found " + key + " at row " + i + " column " + j);
}
}
}
if (!foundIt)
{
System.out.println(key + "is not in the array");
}
Don't forget to initialize the foundIt to false first.

My Suggested Solution is :
bool foundit=false;
for (int i = 0; i <arrayOfInts.length; i++){
for (int j = 0; j <arrayOfInts[i].length; j++){
if (arrayOfInts[i][j] == key)
{
foundIt = true;
break;
System.out.println("found " + key + " at row " +i+ " column " +j);
}
}
}
if(!foundit)
{
system.out.println("Key not found in the array.")
}

This works:
import java.util.Scanner;
public class ArraySearch {
public static void main (String[] args){
Scanner input = new Scanner(System.in);
//lets create the array
int [] [] arrayOfInts = {{1, 2,3,4}, {5,6,7,8},{9,10,11,12}};
//create search variables
System.out.println("Enter the key number to search for in the array: ");
int key = input.nextInt();
//perform search using a for loop
for (int i = 0; i <arrayOfInts.length; i++){
for (int j = 0; j <arrayOfInts[i].length; j++){
if (arrayOfInts[i][j] == key) {
System.out.println("found " + key + " at row " +i+ " column " +j);
return;
}
}
}
System.out.println(key + " is not in the array");
}
}
Why:
commands in operatorif (arrayOfInts[i][j] == key) {} executing only if the element is found in array, so it is no need to use your boolean foundIt;. Use return to end executing the class, cos we have found what we wanted. The line System.out.println(key + " is not in the array"); should be after the two cycles so it will work only if we've checked each element of the two-dimensional array before.

Related

Print index position of letter from sentence using JOptionPane

I need to ask the user to input a sentence and then a letter.
The program should then print out how many letters the sentence contains. Also the index position of
the specified character that the user inputted.
My problem is that I don't know how to find the position of that character.
NOTE: I have searched the web for answer.
import javax.swing.*;
public class Main {
public static void main(String[] args) {
String sentence; //Store the users senctence
String sentence2; //Stores the letter that the user wants to count.
int index;
sentence = JOptionPane.showInputDialog("Write a sentence");
sentence2 = JOptionPane.showInputDialog("Write a letter");
int sLenght = 0;
int countCha = sentence2.indexOf(sentence2);
if (sentence == null || sentence.equals(""))
JOptionPane.showMessageDialog(null, "You need to input a sentence to continue");
else {
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) != 1)
sLenght++;
}
JOptionPane.showMessageDialog(null, "The sentence contains" + " " + sLenght +
" " + "characters" + "\n" + "Tecknet" + " " + sentence2 + " " + "occurs" + sentence.indexOf(sentence2) + " " + "times");
}
}
}
If you want to show just the first index where the character is found, you can use String#indexOf(int ch). If you want to display all the positions where the letter occurs in the sentence, you can use String#indexOf(String str, int fromIndex).
Demo:
public class Main {
public static void main(String[] args) {
String sentence = "Hello world!";
char ch = 'l';
int index = sentence.indexOf(ch);
if (index != -1) {
System.out.println("The first occurance of '" + ch + "' is at " + index);
} else {
System.out.println("The letter, '" + ch + "'does not exist in the sentence");
}
// All positions
System.out.println("All positions: ");
int fromIndex = 0, count = 0;
for (int i = 0; i < sentence.length(); i++) {
index = sentence.indexOf(ch, fromIndex);
if (index != -1) {
System.out.println("'" + ch + "' was found at " + index);
fromIndex = index + 1;
count++;
}
}
if (count == 0) {
System.out.println("The letter, '" + ch + "'does not exist in the sentence");
}
}
}
Output:
The first occurance of 'l' is at 2
All positions:
'l' was found at 2
'l' was found at 3
'l' was found at 9
Alternatively, you can use String#charAt:
public class Main {
public static void main(String[] args) {
String sentence = "Hello world!";
char ch = 'l';
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ch) {
System.out.println("'" + ch + "' was found at " + i);
count++;
}
}
if (count == 0) {
System.out.println("The letter, '" + ch + "'does not exist in the sentence");
}
}
}
Output:
'l' was found at 2
'l' was found at 3
'l' was found at 9
You can also add all the positions to a List<Integer> and display the same.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String sentence = "Hello world!";
char ch = 'l';
List<Integer> positions = new ArrayList<>();
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ch) {
positions.add(i);
}
}
if (positions.size() == 0) {
System.out.println("The letter, '" + ch + "'does not exist in the sentence");
} else {
System.out.println("The positions where '" + ch + "' was found is/are " + positions);
}
}
}
Output:
The positions where 'l' was found is/are [2, 3, 9]
Split the sentence into single letters and go through them. If it matches add it to some List that will be returned.
public List<Integer> findOccurences(String letter, String sentence){
List<Integer> positions = new ArrayList<>();
String[] letters = sentence.split("");
for(int i = 0; i<letters.length; i++){
if(letter.equals(letters[i])){
positions.add(i);
}
}
return positions;
}
Then call it with
List<Integer> occurenceList = findOccurences(sentence2, sentence);

Problems with while() loop [duplicate]

This question already has answers here:
Comparing two integer arrays in Java
(10 answers)
Closed 7 years ago.
The statement before the begining of while loop System.out.println("Value of i before loop = " + i); is not being printed and the value of i in the loop is not being printed starting from 1. Instead it starts printing from a random big int.
package main;
import java.util.Random;
public class Main {
public static void main(String args[]){
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!(c_gen.equals(in))){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
}
You are directly comparing arrays resulting in an infinite loop. Those results are being printed but are going to be at the top of tons and tons of output. Fix your comparison.
Sotirios' intuition is correct - your bug is in the line while(!(c_gen.equals(in))). You can't compare arrays for equality using the .equals(...) method because "arrays inherit their equals-method from Object, [thus] an identity comparison will be performed for the inner arrays, which will fail, since a and b do not refer to the same arrays." (source). Thus because c_gen and in will always refer to different arrays (even if their contents are the same), your loop will go forever.
Try Arrays.equals(..) instead:
public static void main(String[] args) {
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!Arrays.equals(in, c_gen)){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
This works (terminates in finite time) for me, with sample output:
Value of i before loop = 0
1 9 9 ..................1
5 4 1 ..................2
1 1 6 ..................3
1 3 6 ..................4
.... //Omitted because of space
6 5 8 ..................1028
2 5 9 ..................1029
in = 2 5 9
c_gen = 2 5 9
i = 1029
I get:
Value of i before loop = 0
2 2 1 ..................1
2 2 4 ..................2
...
Suggest you rebuild the project and try again.
As originally posted your code will not terminate because int[].equals(int[]) will not do what you expect.
You could try this though.
private static boolean equals(int[] a, int[] b) {
if (a == null && b == null) {
// Both null
return true;
}
if (a == null || b == null) {
// One null
return false;
}
if (a.length != b.length) {
// Differ in length.
return false;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
// Mismatch
return false;
}
}
// Same.
return true;
}
public void test() {
Random ran = new Random();
int[] in = {2, 5, 9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while (!equals(c_gen, in)) {
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for (int x : in) {
System.out.print(x + " ");
}
System.out.print("\n" + "c_gen = ");
for (int x : c_gen) {
System.out.print(x + " ");
}
System.out.println("\n" + "i = " + i);
}

Java If statement Array Address

I have a code that will give me the coordinates of certain points in an array using user input. What code would I add to make the code output say that the address could not be found if the number in the array is not there? I'm pretty sure I need an else statement but I can't get it to work. Here is the code I have right now.
import java.util.Scanner;
public class LabActivityArray
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
int rows;
int columns;
int check1,check2;
System.out.println("Enter number of rows: ");
rows = scanner.nextInt();
System.out.println ("Now enter the number of columns: ");
columns = scanner.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the number to start the array: ");
int value = scanner.nextInt();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
array[i][j]=value++;
System.out.print(array[i][j] + " " );
}
System.out.println();
}
System.out.println("Please give one integer value to be checked in the array: ");
check1 = scanner.nextInt();
System.out.println ("Please give a second integer value to be checked in the array: ");
check2 = scanner.nextInt();
for ( int i = 0; i < rows; ++i )
{
for ( int j = 0; j < columns; ++j )
{
if ( array[i][j] == check1 )
{
System.out.print(array[i][j] + " is located at address array[" + i + "," + j + "]");
}
if ( array[i][j] == check2 )
{
System.out.print("\n" + array[i][j] + " is located at address array[" + i + "," + j + "]");
System.out.println();
}
}
}
}
}
step 1: make a flag say
boolean check1Found = false;
step 2: if you find the value, set the flag to true
if ( array[i][j] == check1 )
{
System.out.print(array[i][j] + " is located at address array[" + i + "," + j + "]");
check1Found = true;
}
step 3: after your loop is finished, print a message if that flag is still false
if(check1Found == false)
{
System.out.println("check 1 not found");
}
You could add two bool flag which are false at first but when the numbers youre searching are found, they are set to true.
bool foundFlag1 = false;
bool foundFlag2 = false;
Then
if ( array[i][j] == check2 ) {
foundFlag2 = true;
..
}
and do the same for check1.
If the flags are false, you know that you couldn't find those inputs!
You are almost right here. Here is the Pseudocode
Initialize Boolean Flag = false;
Search for number in array. if found set Flag = True.
After searching the number in array, check Flag.
If Flag = False, print "the address could not be found"
I would do this:
boolean check1Flag = false;
boolean check2Flag = false;
for ( int i = 0; i < rows; ++i )
{
for ( int j = 0; j < columns; ++j )
{
if ( array[i][j] == check1 )
{
System.out.println(array[i][j] + " is located at address array[" + i + "," + j + "]");
check1Flag = true;
}
if ( array[i][j] == check2 )
{
System.out.println(array[i][j] + " is located at address array[" + i + "," + j + "]");
check2Flag = true;
}
}
}
if(!check1Flag)
{
System.out.println("Can't find " + check1);
}
if(!check2Flag)
{
System.out.println("Can't find " + check2);
}
The flags are set to true when the array is found, so if either are false than that address could not be found.

Infinite loop cant figure out how to stop it java

Hi, I'm trying to learn Java slowly, but I'm having trouble with a infinite loop. Below is my code. From the start of the constructor until the end of the display method, how do I go about making the loop stop after the last entry added?
public UnitResults(int Size, String title)
{
this.fName = new String [Size];
this.surname = new String [Size];
this.Marks = new int [Size];
pointer = 0;
fName[pointer] = "Daniel";
surname[pointer] = "Scullion";
Marks[pointer] = 60;
unitTitle = title;
pointer ++;
}
public Boolean add( String tempfName, String tempsName, int newGrade)
{
if (pointer == fName.length)
{
System.out.println("The Students Database is full");
return false;
}
else
{
fName [pointer] = tempfName;
surname [pointer] = tempsName;
Marks[pointer] = newGrade;
pointer ++;
System.out.println("Student Added");
return true;
}
} // end Add
public void display()
{
System.out.println("Students Results\n");
for (int index = 0; index < pointer; index++)
{
System.out.println( unitTitle + "\n"
+ fName[index] + "\n"
+ surname[index] + "\n"
+ Marks[index] + "\n"
+ "\n" );
index++;
}
}
Thanks for any help with this!
The index++; line is not required and indeed is probably the cause of your infinite loop. The index++ is already specified in the for() statement. Adding is again means that index is incremented by 2 for each loop.
for (int index=0; index < pointer; index ++)
{
System.out.println( unitTitle + "\n"
+ fName[index] + "\n"
+ surname[index] + "\n"
+ Marks[index] + "\n"
+ "\n" );
index++; // <<<----- this line should not be here
}

NoSuchElementException reading/ scanning input

Here is the main problem:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at ExamAnalysis.main(ExamAnalysis.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
The program compiles and runs. It's just that I am either getting the java.util.NoSuchElementException along with my five jother errors with (answer.charAt(i) == char) near the bottom. Here is my program:
import java.io.*;
import java.util.Scanner;
class ExamAnalysis
{
public static void main(String [] args) throws FileNotFoundException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type the correct answers to the exam questions, one right after the other: ");
String answers = keyboard.nextLine();
System.out.println("Where is the file with all the student responses? ");
String responses = keyboard.nextLine();
Scanner read = new Scanner(new File(responses));
while (read.hasNextLine())
{
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
int p = 1;
p += i;
System.out.println("Student " + p + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on 9 students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
}
}
public static void resultsByStudents(String responses, String answers)
{
System.out.println ("Student # Correct Incorrect Blank");
System.out.println ("~~~~~~~~~ ~~~~~~~ ~~~~~~~~~ ~~~~~");
int student = 0;
int correct = 0;
int incorrect = 0;
int blank = 0;
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j <= responses.length(); j++)
{
if ((responses.charAt(j)) == answers.charAt(j))
correct++;
else if ((responses.charAt(j)) != answers.charAt(j))
incorrect++;
else
blank++;
}
System.out.println(student + " " + correct + " " + incorrect + " " + blank);
student++;
}
}
public static void analysis(String responses)
{
System.out.println("QUESTION ANALYSIS (* marks the correct response)");
System.out.println("~~~~~~~~~~~~~~~~~");
//stores the percentage of each choice chosen
double A = 0;
double B = 0;
double C = 0;
double D = 0;
double E = 0;
double X = 0;
// tallys every variable chosen per question
for (int i = 0; i <= 10; i++) // go through all the questions
{
for (int j = 0; j <= responses.charAt(i); j++) //go through all the student responses
{
// variable that are being tallied
int chooseA = 0;
int chooseB = 0;
int chooseC = 0;
int chooseD = 0;
int chooseE = 0;
int chooseBlank = 0;
//variables take percentage of choices that have been chosen from each student
A = chooseA/9;
B = chooseB/9;
C = chooseC/9;
D = chooseD/9;
E = chooseE/9;
X = chooseBlank/9;
// variables that will print the asterisk with certain character of correct answer
String a = "A";
String b = "B";
String c = "C";
String d = "D";
String e = "E";
String blank = "blank";
if (responses.charAt(j) == A)
chooseA++;
else if (responses.charAt(j) == B)
chooseB++;
else if (responses.charAt(j) == C)
chooseC++;
else if (responses.charAt(j) == D)
chooseD++;
else if (responses.charAt(j) == E)
chooseE++;
else
chooseBlank++;
System.out.println("Question #" + i);
if (answers.charAt(i) == 'A') a = "A*"; // answers cannot be resolved(I already made it a global variable in my main method.)
else if (answers.charAt(i) == 'B') b = "B*";// answers cannot be resolved
else if (answers.charAt(i) == 'C') c = "C*";// answers cannot be resolved
else if (answers.charAt(i) == 'D') d = "D*";// answers cannot be resolved
else if (answers.charAt(i) == 'E') e = "E*";// answers cannot be resolved
System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + blank);
System.out.println (chooseA + " " + chooseB + " " + chooseC + " " + chooseD + " " + chooseE + " " + chooseBlank );
System.out.println (A + " " + B + " " + C + " " + D + " " + E + " " + X);
}
}
}
}
while (read.hasNextLine())
{
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
int p = 1;
p += i;
System.out.println("Student " + p + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on 9 students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
}
}
Your logic here is confusing you. read.nextLine(); "Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line."
So you are saying, does it have a line? If so, read the next 10...well...11 lines, which isn't what you want. You don't know if there are 11 lines past this point. Don't know what that text file looks like, but you will want to restructure this part to either say, "While it has a next line", or "Read 11 lines"
Remove the for loop may resolve the issue. You are checking only once by using while(hasNextLine() ) but calling read.nextLine() 10 times in for loop.
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
.......
}
int i = 0;
int numberOfStudents = 9;
while (i < numberOfStudents && read.hasNextLine()){
responses = read.nextLine();
i++;
System.out.println("Student " + i + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on "+ numberOfStudents +" students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
i < numberOfStudents : makes the required number of inserts
read.hasNextLine() : checks if there is input from console. If not the program waits for input.
for (int i = 0; i <= 10; i++)
count from 0 -> 10 = 11 students

Categories