if loop is not working? can anyone help me - java

public class meaingCompare {
public static void main(String[] args) {
int cnt = 0;
String st1, u, st2;
st2 = "funny";
int n = 5;
System.out.println("Enter the string");
Scanner in=new Scanner(System.in);
st1 = in.nextLine();
String[] v = st1.split("\\s+");
for(int i = 0; i < st1.length(); i++) {
if(v[i].equalsIgnoreCase(st2))
cnt++;
}
if(cnt>=4)
System.out.println(" match found");
}
}
I am just a beginner in java.I want to get the output as match found if the no: of words in the input string match the word funny is greater than 4 but the if loop is not working.

Your stop condition in the for loop is wrong: since you're looping on the array of strings v you should stop when you've reached the last element. Modify:
for(int i=0;i<st1.length();i++)
to:
for(int i=0;i<v.length;i++)

when traversing due to this st1.length() we get ArrayIndexOutofBoundException so compare with array length instead of strings length.
This works:
public static void main(String[] args)
{
int cnt=0;
String st1,u,st2;
st2="funny";
int n=5;
System.out.println("Enter the string");
Scanner in=new Scanner(System.in);
st1=in.nextLine();
String[]v=st1.split("\\s+");
for(int i=0;i<v.length;i++)
{
if(v[i].equalsIgnoreCase(st2))
cnt++;
}
if(cnt>=4)
System.out.println(" match found");
}
}

First of all, there is no such thing as an if loop. You have a for loop.
Your problem is that in your for loop, you check if i is less then the length of the String st1. However you need to check if I is less then the length of the array v. So, change this statement:
for(int i = 0; i < st1.length(); i++)
to this:
for(int i = 0; i < v.length; i++)
Hope this helped.

Related

getting an error in my palindrome java program

I have created a palindorme java program which is getting an error.the error is saying int cannot be converted to boolean.
import java.util.Scanner;
public class palindrome
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int l,i;
String s,s1;
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i=0;l-i-1;i++)
{
s1 = s + s.charAt(i);
}
if(s1==s)
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
}
For loop condition seems wrong.
for(initial counter; condition to terminate; increase counter) {}
for(i=0; i<l; i++) {}
Along with the answer above you can try a different approach. You don't need to go all the string length to check a palindrome. A palindrome can be checked iterating half of the array length like this -
public void checkPalindrome(String strToCheck){
char[] arr = strToCheck.toCharArray();
int size = arr.length;
char [] original = Arrays.copyOf(arr,arr.length);
for (int i = 0; i < size / 2; i++) {
char temp = arr[i];
arr[i] = arr[size-i-1];
arr[size-i-1] = temp;
}
if(Arrays.equals(arr, original)) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}
}
What are done here:
reversing the string first iterating the halfway
comparing the reversed string with the original using Arrays.equals() method.
There are quite a few things off here, first here is the fixed code:
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int l,i;
String s = "",s1 = "";
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i = l - 1; i >= 0; i--)
{
s1 = s1 + s.charAt(i);
}
if(s1.equals(s))
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
The first thing to fix was your for loop, as you saw you were getting an error. This was fixed by setting the initial i to the length minus 1, changing the loop condition to i >= 0, and using i-- to subtract 1 from i each loop.
These changes to the loop were made so that the character starting from the last position in the String is the first one being return by s.charAt(i) so you can reverse the String. I think you were attempting to do something along these lines to add the characters starting from the end to a String.
I also changed s1 = s + s.charAt(i) to s1 = s1 + s.charAt() so the correct String is being appended. (This should probably be StringBuilder however).
s and s1 now have the initial condition of "" instead of nothing.
And finally you cannot compare String equality with ==, it must be s1.equals(s).
Test Run:
Enter your string
racecar
This is Palindrome

I am generating a series of numbers delimited with space but I want to remove the space at end

I am generating the series of numbers using for loop, delimited with space but I want to remove trailing space at last. Unable to use trim() for the output.
import java.util.*;
public class Main {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
int str = s.nextInt();
for(int i=1; i<=str; i++) {
System.out.printf("%d", i);
System.out.print(" ");
}
}
}
1 2 3 4 5(space here)
but I want output without the space after 5.
int i;
for(i = 1; i < str.length(); i++) {
System.out.print(i + " ");
}
System.out.println(i);
Do an if test inside the for-loop like this
if (i == str) {
System.out.printf("%d", i);
} else {
System.out.printf("%d", i);
System.out.print(" ");
}
The logic you want is to print a space behind every number, except for the last number. You should have this conditional logic in your code somewhere. Like,
if (i < str)
System.out.print(" ");
Note: it's very confusing to call a variable str if it contains a number; everyone will assume that it's a String instead of a number. You could change code to something like this:
public static void main(String [] args){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for(int i = 1; i <= n; i++) {
System.out.print(i);
if (i < n)
System.out.print(" ");
}
}

How to check character values on a String array?

I was asked to write a Java program which gets 5 strings from user and collects it in an array. Furthermore, I need to check every single string in the array and only print the ones who has more than four characters.
public static void main(String[] args) {
Scanner mbk = new Scanner(System.in);
int repetition[] = { 1, 2, 3, 4, 5 };
String words[] = new String[repetition.length];
for (int i = 0; i < words.length; i++) {
System.out.println("Please enter element " + repetition[i] + ":");
words[i] = mbk.nextLine();
}
}
This is the code that I have written and I'm stuck. Can anyone help?
First of all, It's a very bad practice to use variable names like mbk, the variable name should be easily understood by any other developer reading your code. It's name should reflect it's purpose. Here's a small revision of your code.
Also, Leaving a I/O stream open can cause you a big time of trouble, so i have also added the scanner.close statement.
public static void main(String[] args) throws Exception {
Scanner userInput = new Scanner(System.in);
int maxArrayLength[] = { 1, 2, 3, 4, 5 };
String words[] = new String[maxArrayLength.length];
for (int i = 0; i < words.length; i++) {
System.out.println("Please enter element " + maxArrayLength[i] + ":");
words[i] = userInput.nextLine();
}
for(int lengthCheckCounter = 0; lengthCheckCounter < words.length; lengthCheckCounter++)
if(words[lengthCheckCounter].length() > 4)
System.out.println(words[lengthCheckCounter] + "-" + words[lengthCheckCounter].length());
userInput.close();
}
Another way of closing the I/O stream/resources could be to use try-with-resources block featured since JDK 1.7. Then we can write your code as follows:
try(Scanner userInput = new Scanner(System.in)) {
// All other code
}
If you are on JDK 1.8, you can use a single line to do everything as suggested in Lonely Neuron's comment:
// Initialize your words array here
// Take user input
// Print words greater than 4 using JDK 1.8 Filter below
Arrays.stream(words).filter(s -> s.length() > 4).forEach(System.out::println)
Yo, I gotchu:
this goes through the entire list, and prints anything that has a greater length than 4.
for (int i = 0; i < yourArray.length; i++) {
if (yourArray[i].length() > 4) {
System.out.println(yourArray[i]);
}
}
Use the length() method
for(String s: words){
if(s.length()>=4){
System.out.println(s);
}
}
words[j].length() will give you the length of the string in index j of your array. I am leaving you to compare it to 4, And to introduce a variable j (you may call it i again or any other name you find fitting).
import java.util.Scanner;
public class StackOf4 {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
String[] names=new String[5];
for(int i=0;i<5;i++) {
System.out.println("Enter a string:");
names[i]=scn.nextLine();
}
System.out.println("The strings with more than 4 characters are: ");
for(int i=0;i<5;i++) {
if(names[i].length()>4)
System.out.println(names[i]);
}
}
}

Counting Upper and Lower characters in a string using an array

I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}

Java using a while loop to load user input into an array

I was wondering how to load up an array (with user input) using a while loop. The code below prints a 0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int n = 0;
int[] myArray = new int[10];
System.out.printf("enter a value>>");
while (scan.nextInt() > 0) {
for (i = 0; i > 0; i++) {
myArray[i] = scan.nextInt();
}
System.out.printf("enter a value>>");
}
System.out.printf("array index 2 is %d", myArray[2]);
}
There are multiple things wrong with your code:
First of all
while(scan.nextInt() > 0){
Scanner.nextInt() returns an int from your standard input so you actually have to pick up that value. You are checking here what the user typed but then not using it at all and storing the next thing that the user types by saying:
myArray[i] = scan.nextInt();
You don't really need the outer while loop, just use the for loop, its enough.
However, your for loop is off as well:
for(i = 0; i > 0; i++){
It starts at i equal to 0 and runs while i is greater than 0. This means it will never actually run the code within the loop because 0 is never greater than 0. And if it did run (you started it at some number < 0), you would end up in an infinite loop because your condition i > 0 is always true for positive numbers.
Change the loop to:
for(i = 0; i < 10; i++){
Now, your loop could look like:
for(i = 0; i < 10; i++){ // do this 10 times
System.out.printf("enter a value>>"); // print a statement to the screen
myArray[i] = scan.nextInt(); // read an integer from the user and store it into the array
}
one other way to do it
Scanner scan = new Scanner(System.in);
List list = new ArrayList();
while(true){
System.out.println("Enter a value to store in list");
list.add(scan.nextInt());
System.out.println("Enter more value y to continue or enter n to exit");
Scanner s = new Scanner(System.in);
String ans = s.nextLine();
if(ans.equals("n"))
break;
}
System.out.println(list);
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
int[] arr=new int[4];
int i;
for(i=0;i<4;i++)
{
System.out.println("Enter the number: ");
arr[i]=input.nextInt();
}
for(i=0;i<4;i++)
{
System.out.println(arr[i]);
}
}
Hope this code helps.

Categories

Resources