Java for loop running both true and false conditions - java

I refactored a working project to practice creating callable methods when I broke the app. This app includes a simple String array with a method that matches user input with the array and prints the element name and index.
If I don't include a break at the end of the if else statements the app can match valid input but runs both if and else statements. It actually prints the if statement in the order of the index and prints the else output the number of times as the length of the array. In the attached pic, the input was index 0. if statement output In the pic index 0 was matched and printed with the number of else outputs as in the array. It seems the else statement is reading the array length.
If I add the break, the app only recognizes index 0 and will run the if statement as expected, but also runs the else statement. But only prints out if else output once. I hope this is clear. Trainers have simply said it is impossible to for a for loop to print of which I understand, yet I'm having a different experience.
Here is the code:
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What are you looking for? ");
//String product = scan.nextLine();
String[] aisles = {"apples", "bananas", "candy", "chocolate", "coffee", "tea"};
searchProduct(aisles);
}
public static void searchProduct(String[] aisles) {
String product = scan.nextLine();
for (int i = 0; i < aisles.length; i++) {
if (product.equals(aisles[i])) {
System.out.println("We have " + aisles[i] + " in aisle " + i);
} else {
System.out.println("Sorry we do not have that product");
}
}
}
}
I expect to match valid user input and run the if statement or run the else statement.

Here is a suggestion.
Change your method to return an int (aisle if the product exists or -1 if not).
Don't do any I/O in the method. Just pass the target of the search as an argument.
String[] aisles = {
"apples","bananas","candy","chocolate","coffee","tea"
};
System.out.println("What are you looking for? ");
String product = scan.nextLine();
int aisle = searchProduct(product, aisles);
if (aisle >= 0) {
System.out.println("We have " + product + " in aisle " + aisle);
} else {
System.out.println("Sorry we do not have that product");
}
public static int searchProduct(String product, String[] aisles) {
for (int aisle = 0; aisle < aisles.length; aisle++) {
if (product.equals(aisles[aisle])) {
return aisle;
}
}
return -1;
}

Related

Char count of each token in Tokenized String, Java

I'm trying to figure out if I can count the characters of each token and display that information such as:
day is tokenized and my output would be: "Day has 3 characters." and continue to do that for each token.
My last loop to print out the # of characters in each token never prints:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Example of Console:
Please type a sentence containing at least 4 words, with a maximum of 8 words:
Hello there this is a test
Thank you.
You entered:
Hello there this is a test
Each word in your sentence is: [Hello, there, this, is, a, test]
First off, I have added the necessary imports and built a class around this main method. This should compile.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class SOQ_20200913_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Next, let's look at this working example. It seems like everything up until your final while loop (the one that counts character length) works just fine. But if you notice, the while loop before the final one will continue looping until it has no more tokens to fetch. So, after it has finished gathering all of the tokens and has no more tokens to gather, you try and create the final while loop, asking it to gather more tokens. It would not have reached the while loop until it ran out of tokens to gather!
Finally, in order to solve this, you can simply go through the list that you added to in the second to last while loop, and simply cycle through that for your final loop!
For example:
int totalLength = 0;
for (String each : tokenizedInput) {
totalLength += each.length();
System.out.println("Word: " + each + " Length:" + each.length());
}

Accepting string inputs into an array and checking the availability of the string in the array

So I am completely new to java, and I want to create a code to accept string inputs from a user, and store it into an array. After this in the next statement, I will type a value into the terminal, and I want the code to compare my string input to one of the strings in the array and print available on the terminal when the string is available and vice versa. The first part of my code was right (hopefully) but I had a problem in comparing the strings. I feel it doesn't check the strings with my input in the code. Here is my code, Could anyone please help me with this? Thank you so much.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a[] = new String[20] //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() //entering a string to search
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) //I feel the problem is here
System.out.println(search + "course is available");
break;
else
System.out.println(search + "course is not available");
}
}
}
}
I expect the output to be
<string> course is available
when my string matches a string in the array and
<string> course is not available
when my entered string doesn't match a string in the array
But there is no output :(
I have modified your code and commented on line where it need to be explained. check it carefully.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
String a[] = new String[no_of_courses]; // do not assume when you have proper data.
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); // accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); // entering a string to search
boolean flag = false;
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) // I feel the problem is here
{
flag = true;//do not print here. just decide whether course is available or not
break;
}
}
//at the end of for loop check your flag and print accordingly.
if(flag) {
System.out.println(search + "course is available");
}else {
System.out.println(search + "course is not available");
}
}
}
}
class Course {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a[] = new String[20] ; //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if(no_of_courses <= 0)
System.out.println("Invalid Range");
else
{
System.out.println("Enter course names:");
for(int i=0 ; i < no_of_courses ; i++)
{
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() ; //entering a string to search
boolean found = false;
for(int i = 0 ; i < no_of_courses ; i++)
{
if(a[i].equalsIgnoreCase(search)) //I feel the problem is here
{
**found = true;**
break;
}
}
if(found) {
System.out.println(search+ "course is available");
}else {
System.out.println(search+ "course is not available");
}
}
}
}
This is really a good effort and you almost got it. So just a couple of things
Since you are inputting the number of courses, just use that value to initialise your array (it's just a good practice to get into to try not initialise things before you actually need them).
If you are doing String comparisons and case sensitivity does not matter, rather use .equalsIgnoreCase(String)
To solve your problem, you just needed a boolean variable to indicate whether or not you had found a match. Initially this would be FALSE (no match found) and you would run through your array until a match is found. Once found this would be flagged TRUE and you'd breakout your loop (which you correctly did).
Only once out your loop, you'd print out whether you found a match.
Have a look:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0) {
System.out.println("Invalid Range");
} else {
String a[] = new String[no_of_courses];
System.out.println("Enter course names:");
for (int i = 0; i < a.length; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); //entering a string to search
boolean courseFound = Boolean.FALSE;
for(int i = 0; i < a.length; i++) {
if (a[i].equalsIgnoreCase(search)) {
courseFound = Boolean.TRUE;
break;
}
}
if(courseFound) {
System.out.println(search + "course is available");
} else {
System.out.println(search + " course is not available");
}
}
}
Oh, just for interest (and when you start working with some more advanced constructs), you could always just use stream, which was introduced in Java 8. It'll trim down 12 lines to 5...
if(Arrays.stream(a).anyMatch(i -> i.equalsIgnoreCase(search))) {
System.out.println(search + " course is available");
} else {
System.out.println(search + " course is not available");
}
I noticed a few things - Does your program run to the end? When i copy/pasted into my ide i noticed a few missing semi-colons, and like Yhlas said, your last if/else statement syntax is incorrect.
And this doesn't have anything to do with whether or not your program will give you the right answer, but your last loop will print over and over again because it will check each element in a, and each time it loops and finds a mismatch it will print something out

Java: Display the complete set of unique values input after the user enters each new value

I need to write a code that "Display the complete set of unique values input after the user enters each new value." Such as:
The·complete·set·of·unique·values·entered·is:↵
Unique·Value·1:·is·100↵
Unique·Value·2:·is·10↵
Unique·Value·3:·is·20↵
I have attached my code below, and have the code completed, however, it seems to come across errors on my very last line to produce the last "this is the first time (user input) has been entered" & the unique value portion results of Unique Value # is (user input that's unique and stored in array). There seems to be an error in the very last System.out.println("Unique...) line.
Any help would be greatly appreciated.
import java.util.Scanner;
import java.util.ArrayList;
public class DisplayUniqueValueInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// creating an ArrayList from user input
ArrayList<Integer> userInputs = new ArrayList<Integer>(5);
// prompt user and store input
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
count++;
if (count == 5)
break;
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
} // end while statement
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < 5; i++) {
System.out.println("Unique Value" + userInputs[i] + "is:" + " ");
}
} // end main method
} // end of class
A little off-topic but if you must store unique elements, you normally go for a Set. That being said, in the portion of the code where you collect the user input, you are asking for 5 numbers but storing 4 e.g.:
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
// count++;
// if (count == 5) if you break here, the code below won't be reached
// break; thus you will never store the last user input
// Lists have a method contains that does exactly what you are trying to do
// Consider using ifExists = userInput.contains(a)
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
// consider breaking here after you have collected the last user input
// alternatively, use a do{ ... } while(); loop
count++;
if (count == 5)
break;
} // end while statement
You are not printing the iteration variable i e.g.:
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value " + (i + 1) + ": is " + userInputs.get(i));
}
Also as mentioned in another answer, in your for-loop the variable i must go up to < userInputs.size() since if you try to go up to 5, it will break if the user entered duplicate values.
For the last loop, you should do this instead, because your array is to store unique numbers, right? So if there is less than 5 unique number, your program will break, and why don't use Set instead?
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value" + userInputs.get(i) + "is:" + " ");
}
Your error is because in the last for loop you try to access your list with userInputs[i] instead of userInputs.get(i)
If you want to accept and print only unique value, Perhaps use Set instead of ArrayList. Example:-
public static void main(String args[]){
Set<Integer> numbers = new HashSet<>();
for(String input : args){
Integer num = Integer.parseInt(input);
if(!(numbers.add(num))){
throw new IllegalArgumentException("Number already have");
}
System.out.println("Unique number =" + num);
}
}
A Set is a collection that contains no duplicate elements. Refer to its javadoc for details.
** Sample above just for brevity, you may retrofit your program with Set type.

Output fails to print all the data i've inputted

I've been working on the same piece of java code for over a week now, t used to be a complete mess however i have got it now (through about a million iterations) to a somewhat working stage. The output i need is all three student names at the end with either a pass or fail beside their name, however my code will only output the last students name that i put in, completely ignoring the rest of the data i input.
If someone could teach me where i have gone wrong and also the quality of code i've produced and iterated, it would be much appreciated. Also to those who downvote my posts simply because it may seem easy to you, we aren't all experienced as you and don't forget that you used to be in my position once, so be thoughtful.
class Main extends BIO {
public static void main(String args[]) {
{
int i = 0;
int moduleMark = BIO.getInt();
String first_name = BIO.getString();
while (i++ < 3) {
System.out.print("Enter The Students name : ");
first_name = BIO.getString();
if (first_name.equals("END"))
break;
System.out.print("Their Module mark : ");
moduleMark = BIO.getInt();
}
if (moduleMark >= 40) {
System.out.println(first_name + " Pass");
} else {
System.out.println(first_name + " Fail");
}
}
}
}
first_name gets overwritten inside the loop constantly. When you exit the loop, first_name will be whatever the last name it received was.
If you can print them as you go, just print inside the loop. This will alternate between printing the results and asking for a new name/grade:
while (i++ < 3) {
System.out.print("Enter The Students name : ");
first_name = BIO.getString();
if (first_name.equals("END"))
break;
System.out.print("Their Module mark : ");
moduleMark = BIO.getInt();
if (moduleMark >= 40) {
System.out.println(first_name + " Pass");
} else {
System.out.println(first_name + " Fail");
}
If they must be printed at the end, you'll need to put the names and grades into lists, then iterate over the lists at the end:
// Create lists to hold grades and names
List<String> names = new ArrayList<>();
List<Integer> grades = new ArrayList<>();
while (i++ < 3) {
System.out.print("Enter The Students name : ");
first_name = BIO.getString();
if (first_name.equals("END"))
break;
// Add name to list
names.add(first_name);
System.out.print("Their Module mark : ");
moduleMark = BIO.getInt();
// Add grade to list
grades.add(moduleMark);
}
// Iterate both lists at once, printing inside the loop
for(int i = 0; i < names.size(); i++) {
String name = names.get(i);
Integer grade = grades.get(i);
if (grade >= 40) {
System.out.println(name + " Pass");
} else {
System.out.println(name + " Fail");
}
}

Search Term Finder in Array

Here is the code:
import java.util.Scanner;
public class Finder {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String [] names = new String[5];
String searchTerm = "";
for (int i = 0; i <= names.length - 1; i++) {
System.out.print("Enter a name: ");
names[i] = scnr.next();
}
System.out.println();
System.out.print("Enter a name to search for: ");
searchTerm = scnr.next();
for (int i = 0; i <= names.length - 1; i++) {
if (searchTerm.equals(names[i])) {
System.out.println(searchTerm + " found!!");
}
else {
System.out.println(searchTerm + " not found!!");
}
}
}
}
I am working on the if/else statement in the second for loop and when I add the else part of the statement, it returns:
Enter a name: Luke
Enter a name: Kassy
Enter a name: Chloe
Enter a name: Jon
Enter a name: Jake
Enter a name to search for: Chloe
Chloe not found!!
Chloe not found!!
Chloe found!!
Chloe not found!!
Chloe not found!!
I am not sure why it just doesn't say "Chloe found!!" instead of what it says?
With your code now, when you're looping to find the element "Chloe" in the names array, you're going through each element and printing a statement out no matter what. "Chloe" is names[2] but your loop checks names[0] and names[1] first. Since they are not "Chloe", it will print "Chloe not found" (the else part of your if statement). Once it gets to names[2], it will then have found "Chloe" and the if part of your if statement will be executed, printing out "Chloe found". However your loop does not stop there, so the loop will look at names[3] and names[4] and print out "Chloe not found" because none of them equals "Chloe". The simple fix is to only print "Chloe not found" when the loop ends without finding "Chloe" and to only print "Chloe found" when in the middle of the loop, "Chloe" is found. There are many ways to do this but one way I propose is using a boolean variable to check after the loop is done to see if "Chloe" was found or not.
boolean termFound = false;
for (int i = 0; i <= names.length - 1; i++) {
if (searchTerm.equals(names[i])) {
System.out.println(searchTerm + " found!!");
termFound = true;
break;//if term is found, you can break out of the loop early
}
}
if(!termFound){ //if searchTerm was not found
System.out.println(sertTerm + " not found!!");
}

Categories