else statement printing multiple times - array loop - java

I want my code to loop through an array and only give the user an option to delete a student only if there are values in the array. If all the array values are null then I want it to print out a message. The problem is that my message is printing out multiple times for each null element in the array.
My code:
static void deleteStudent() {
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
for (i = studentChoice + 1;i < studentNamesArray.length; i++) {
studentNamesArray[i-1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(i = studentChoice + 1;i < 9;i++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[i-1][y] = studentMarksArray[i][y];
}
}
markArrayCount = markArrayCount - 1;
for(int y = 0;y < 3;y++) {
studentMarksArray[9][y] = 0;
}
} else {
System.out.println("There are no students stored");
}
}
}

The else block runs in each loop iteration. If you want to run it only once at the end, do something like this:
boolean studentFound = false;
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
...
Then after the for:
if (!studentFound) {
System.out.println("There are no students stored");
}

Here is how I would determine if all the elements are null. The reason yours prints it out for each null element is that the print statement is inside the for loop.
boolean allNull = true; // default is that everything is null
for(int i = 0; i < studentNamesArray.length; i++) { // iterate through entire array
if(studentNamesArray[i] != null) { // if even 1 of them is not null
allNull = false; // set allNull to false
break; // and break out of the for loop
}
}
if(allNull) System.out.println("There are no students stored!");

I suggest to use 'boolean' variable, lets name it 'flag'. Initialize it as 'false'. If you found not null element in array, when set 'flag = true'. After 'for' loop check 'if (!flag) System.out.println ("There are no students.");'.

In your for loops, you use the same variable i, in which it overrides the original variable used in the for loop.
Try something like this:
static void deleteStudent() {
for (int i = 0;i < 10;i++) {
if (studentNamesArray[i] != null) {
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
for (int j = studentChoice + 1;j < studentNamesArray.length; j++) {
studentNamesArray[j-1] = studentNamesArray[j];
}
nameArrayCount = nameArrayCount -1;
studentNamesArray[studentNamesArray.length - 1] = null;
for(int k = studentChoice + 1;k < 9;k++) {
for(int y = 0;y < 3;y++) {
studentMarksArray[k-1][y] = studentMarksArray[k][y];
}
}
markArrayCount = markArrayCount - 1;
for(int z = 0;z < 3;z++) {
studentMarksArray[9][z] = 0;
}
} else {
System.out.println("hi");
}
}
}
Although, I am not sure what you are trying to print out, I made adjustments to the other variable names based on my intuition; the result might not be exactly as resulted, but I am sure you can make further adjustments with the variable names so that you are not over-riding each other and causing excessive loops.

Related

Java Array nested for loops, not clearing second for to go back to the first

The for loops in the code below are first looping through the user entries, then checking the number of spaces " " in the string. After checking through them a question is asked if they want to display strings with no spaces, one, or more. I don't think the loop is making it past the first instance of the for loop as the second should be looking for a 0 value on the count variable. Below is the nested for loops:
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
if (array[i] != null) {
for (int count = 0; array[i].charAt(i) != ' ';count++) {
if(count == 0)
System.out.println(array[i]+" ");
}
}
}
}
Primary code for reference:
import java.util.*;
import java.util.Scanner;
public class StringsWithSpaces {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter anything..., or type QUIT to quit.");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
boolean result = Arrays.stream(array).anyMatch("QUIT"::equals);
if(result)
{
break;
}
}
String str = null;
int len = -1;
System.out.println("Would you like to display strings with No Spaces, One Space or More? Type No, One, More to see the results: ");
String answer = s.nextLine();
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
if (array[i] != null) {
for (int count = 0; array[i].charAt(i) != ' ';count++) {
if(count == 0)
System.out.println(array[i]+" ");
}
}
}
}
else if(answer.equals("One"))
{
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
//System.out.print(array[i] + " ");
}
}
}
else
System.out.println("No values to show");
System.out.println();
}
}
I have looked for something similar, but could only find other languages. Thanks for all the help.
In the first set of nested loops you're basically checking the same character of each word each time. You should use count as the parameter for the charAt method instead of whatever index is in i;
Also you should only print out the word when count equals the length of the word minus one.
Here it is:
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
if (array[i] != null) {
for (int count = 0; array[i].charAt(i) != ' ' ;count++) {
if(count == array[i].length()-1) {
System.out.println(array[i]);
break;
}
}
}
}
}
I also rewrote the second set of nested loops, it should explain itself:
else if(answer.equals("One"))
{
for (int i = 0; i < array.length;i++) {
int count = 0;
for (int j = 0; j < array[i].length(); j++) {
if (Character.isSpaceChar(array[i].charAt(j)))
count++;
}
if (count == 1) {
System.out.println(array[i]);
}
}
}
EDIT: I forgot to mention that I added the break statement that you forgot. It ensures that the for loop is exited when you reach the last character in the string. Without this statement your application would crash each time it hits the end of a string because of an IndexOutOfBoundsException.

Java How to get start and end of an element in an ArrayList

I have some dynamic values in an ArrayList
ClassnameOne <!----Begin---->
Classnametwo <!----Begin---->
Classnamethree <!----Begin---->
Classnamethree <!----End---->
Classnametwo <!----End--->
ClassnameOne <!----End---->
What I want to do is to get the beginning occurrence of an element and when it ends. So for example ClassnameOne would be 5, Classnametwo would be 3.
This is what I have done so far:
ArrayList<String> one = new ArrayList<String>();
for (int i = 0; i < one.size(); i++) {
if(one.get(i).contains("<!----End---->") && one.get(i).equals(one.get(i+1))) {
break;
} else {
count++;
System.out.println(one.get(i));
}
System.out.println(count);
}
This doesn't give the right answer. Can you please help?
ArrayList<String> one = new ArrayList<String>();
for (int starti = 0; starti < one.size(); ++starti) {
String[] words = one.get(starti).split(" ", 2);
if (words[1].equals("<!----Begin---->")) {
int n = 0;
String sought = words[0] + " " + "<!----End---->";
for (int endi = starti + 1; endi < one.size(); ++endi) {
if (one.get(endi).equals(sought) {
n = endi - starti;
break;
}
}
System.out.printf("%s at %d covers %d lines.%n", words[0], starti, n);
}
}
Assuming that the names do not repeat, otherwise a stack (or such) would to be needed.

Not found string value on array

I am a beginner on java.
Why it always show not found?
and how exactly make a not found string value on array?
String[] array = new String[10];
String b = "5";
for (int i = 0; i < 10; i++) {
String in = String.valueOf(i);
array[i] = in;
}
for (int i = 0; i < 10; i++) {
if (b.equals(array[i])) {
System.out.println("found " + array[i]);
} else if (!b.equals(array[i])) {
System.out.println("not found");
System.exit(0);
}
}
}
Your second for loop terminates on i = 0 when you call System.exit(0); (the program actually terminates overall when you call that).
} else if (!b.equals(array[i])) {
System.out.println("not found");
System.exit(0);
}
Suggest changing the logic to break from the loop when the match has been found.
for (int i = 0; i < 10; i++) {
if (b.equals(array[i])) {
System.out.println("found " + array[i]);
break;
}
}
Okay i've been figure it out.
Thanks for the advice.
Just make "not found" statement outside the loop.
String[] array = new String[10];
String b = "10";
boolean c = false;
for (int i = 0; i < 10; i++) {
String in = String.valueOf(i);
array[i] = in;
}
for (int i = 0; i < 10; i++) {
if (b.equals(array[i])) {
System.out.println("found " + array[i]);
} else if (!b.equals(array[i])) {
c = true;
}
}
if (c == true){
System.out.println("not found");
}
}

Entering an If statement with a hashmap conditions

for (int i = 0; i < pac.length; i++)
{
for (int j=0;j<mem.length;j++)
{
String[] words = mem[j].split(" ");
for (int k = 1; k < words.length; k++)
{
if (words[k].equals(pac[i])
{ //done system.out.println here and it's right
if (!members.containsKey(pac[i])) //won't enter this if correctly
{
members.put(pac[i], " " + words[0]);
}
else
{
String old = members.get(pac[i]);
members.put(pac[i], old + " " + words[0]);
}
}
else
{
members.put(pac[i], "");
}
}
}
}
I need the code to take an array pac which contains a list of organizations and then a list of people's names with their organizations after. I have to put them into a hashmap of members. I cant seem to get it to enter the if statement correctly though. It reaches there correctly. I've used the printing to see what should go into it and that part is correct. Members is an empty hashmap yet all but only one iteration of the loops will go into the first if statement when most should go into it.
use label you can solve your problem. because any one iteration of 2nd loop can empty your member. try this
for (int i = 0; i < pac.length; i++) {
action:
for (int j = 0; j < mem.length; j++) {
String[] words = mem[j].split(" ");
for (int k = 1; k < words.length; k++) {
//System.out.println(words[0] + "ttt");
if (words[k].equals(pac[i])) {
System.out.println(words[k]);
if (!members.containsKey(pac[i]))
{
members.put(pac[i], " " + words[0]);
break action;
} else {
String old = members.get(pac[i]);
members.put(pac[i], old + " " + words[0]);
break action;
}
} else {
members.put(pac[i], "");
}
}
}
}
and use persons as a key for members instead of organization. because a org have more number of persons.

How can I avoid repetition of the same number?

This is what I want :
Let the user enter as many numbers as they want until a non number is entered (you may
assume there will be less than 100 numbers). Find the most frequently entered number. (If
there are more than one, print all of them.)
Example output:
Input: 5
Input: 4
Input: 9
Input: 9
Input: 4
Input: 1
Input: a
Most common: 4, 9
I have got to the point in my code where I have managed to find out which are the most common numbers. However, I don't want to print out the same number over and over again; example from above: Most common: 4, 9, 9, 4
What needs to be done?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[100];
System.out.print("Input: ");
input[0] = in.readLine();
int size = 0;
for (int i = 1; i < 100 && isNumeric(input[i-1]); i++) {
System.out.print("Input: ");
input[i] = in.readLine();
size = size + 1;
}
/*for (int i = 0; i < size; i++) { //testing
System.out.println(input[i]);
}*/
int numOccur;
int[] occur = new int[size];
for(int i = 0; i < size; i++) {
numOccur = 0;
for (int j = 0; j < size; j++) {
if(input[i].equals(input[j])) {
numOccur = numOccur + 1;
}
}
occur[i] = numOccur;
//System.out.println(numOccur); //testing
}
int maxOccur = 0;
for(int i = 0; i < size; i++) {
if(occur[i] > maxOccur) {
maxOccur = occur[i];
}
}
//System.out.println(maxOccur); //testing
for (int i = 0; i < size && !numFound; i++) {
if(occur[i] == maxOccur) {
System.out.println(input[i]);
}
}
}
//checks if s is an in, true if it is an int
public static boolean isNumeric (String s) {
try {
Integer.parseInt(s);
return true; //parse was successful
} catch (NumberFormatException nfe) {
return false;
}
}
Found the solution!
String[] mostCommon = new String[size];
int numMostCommon = 0;
boolean numFound = false;
for (int i = 0; i < size; i++) {
int isDifferent = 0;
if (occur[i] == maxOccur) {
for (int j = 0; j < size; j++) {
if (!(input[i].equals(mostCommon[j]))) {
isDifferent = isDifferent + 1;
}
}
if (isDifferent == size) {
mostCommon[numMostCommon] = input[i];
numMostCommon = numMostCommon + 1;
}
}
}
for (int i = 0; i < numMostCommon - 1; i++) {
System.out.print("Most common: " + mostCommon[i] + ", ");
}
System.out.println(mostCommon[numMostCommon - 1]);
you could use the hash table for this to store the frequenceis as the limit is very less i.e. less than 100.
pseudo code would be like:
vector<int> hash(101)
cin>>input
if(isnumeric(input))
hash[input]++
else{
max=max_element(hash.begin(),hash.end());
for(int i=0;i<100;i++)
if(hash[i]==max)
print i
}
Set<Integer> uniqueMaxOccur = new HashSet<Integer>();
for (int i = 0; i < size ; i++) {
if(occur[i] == maxOccur) {
//System.out.println(input[i]);
uniqueMaxOccur.add(input[i]);
}
}
and display the values in the set
You can use a Set and store the values already printed.
What about something like this?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<string,int> numberLookup = new HashMap<string,int>();
Boolean doContinue = true;
while (doContinue)
{
System.out.print("Input: ");
String input = in.readLine();
if (isNumeric(input))
{
if (!numberLookup.containsKey(input))
numberLookup.put(input,1);
else
numberLookup.put(input, numberLookup.get(input) + 1);
}
else
doContinue = false;
}
maxOccur = numberLookup.values().max();
System.out.print("These numbers were all entered " + maxOccur + " times:");
Iterator it = numberLookup.entrySet().iterator();
while (it.hasNext())
{
(Map.Entry)it.next();
System.out.println(pairs.getKey());
}
}
Sorry, I'm a C# person and don't have a Java compiler on me, so this might need some tweaking.

Categories