Finding a letter in a string using charAt and while loop Java - java

I'm trying to make a program that sees if a user-entered letter is in the string "hello", and if it is, print that it is in the string and where it is in the string. The error is "bad operand types for binary operator"
String str = "hello", guess;
int testing = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a letter: ");
guess = scan.nextLine(); // Enters a letter
// finds the letter in the string
while (str.charAt(testing) != guess && testing != 6) {
testing++; // Continues loop
}
//prints where letter is if it is in the string
if (str.charAt(testing) == guess)
System.out.println("The letter is at "+testing);
else
System.out.println("Could not find that letter.");

You are trying to compare a char to a String.
Compare a char to a char:
while (str.charAt(testing) != guess.charAt(0) && testing != 6)
and
if (str.charAt(testing) == guess.charAt(0))
I'd also change your stopping condition to avoid StringIndexOutOfBoundsException when no match is found:
while (testing < str.length () && str.charAt(testing) != guess.charAt(0))
and
if (testing < str.length () && str.charAt(testing) == guess.charAt(0))

String str = "hello";
char guess;
int testing = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a letter: ");
guess = scan.next().charAt(0); // Enters a letter
// finds the letter in the string
while (str.charAt(testing) != guess && testing != 5) {
testing++; // Continues loop
}
//prints where letter is if it is in the string
if (str.charAt(testing) == guess)
System.out.println("The letter is at "+(testing+1));
else
System.out.println("Could not find that letter.");
I've tried this and it works. Note that there are two "l" so it will show only the position of the first one

Related

How can I do the input loop that exits the program?

"Enter a word or press 'Q' to quit" but I don't know how to do it. It seems confusing to me a little bit.
This is my first time coding in Java and I'm still learning.
public class RemSpecialChar {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
String stringArray = "";
do {
System.out.print("Enter a word or 'Q' to quit: ");
String str = scan.nextLine();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) > 64 && str.charAt(i) <= 122) { //returns true if both conditions returns true
//adding characters into empty string
stringArray = stringArray + str.charAt(i);
}
System.out.print("Input string without special characters: " + stringArray); //string results
}
}
while (stringArray != "q" || stringArray != "Q");
}
}
}
THIS IS THE SAMPLE OUTPUT:
Enter a word or 'Q' to quit: Black?204123,.Scoop (input)
Input string without special characters: BlackScoop (output)
Enter a word or 'Q' to quit: q (input)
(end program)
terminal output:
Enter a word or 'Q' to quit: q
Enter a word or 'Q' to quit: q
Enter a word or 'Q' to quit: q
Enter a word or 'Q' to quit: q
Enter a word or 'Q' to quit: q
Enter a word or 'Q' to quit: q
Enter a word or 'Q' to quit: q
Enter a word or 'Q' to quit:
Use a while loop to read the inputs and break the loop if the input is 'Q'.
public static void main(String[] args)
{
try(Scanner sc = new Scanner(System.in))
{
while(true)
{
System.out.print("Enter a word or press 'Q' to quit: ");
String word = sc.nextLine();
if ("q".equalsIgnoreCase(word))
break;
System.out.println(word);
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Exiting... ");
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
while (true) {
String inputdata = scan.nextLine();
if (inputdata.length() == 1 && (inputdata.charAt(0) == 'Q' || inputdata.charAt(0) == 'q')) {
break;
}
String stringArray = "";
for (int i = 0; i < inputdata.length(); i++) {
if (inputdata.charAt(i) > 64 && inputdata.charAt(i) <= 122) { // returns true if both conditions
// returns true
// adding characters into empty string
stringArray = stringArray + inputdata.charAt(i);
}
}
System.out.print("Input string without special characters: " + stringArray);
}
}
}
}
Take a look at this line:
while (stringArray != "q" || stringArray != "Q")
This repeats while stringArray is not "q" or not "Q". In other words, it must be both "q" and "Q" at the same time for it to exit, which is not possible.
What you actually wanted is to use &&:
while (stringArray != "q" && stringArray != "Q")
Repeat while not "q" and also not "Q".
While this is the root of your problem, I'll still advice you to use the answer that you accepted already.
Edit: As commented, you also shouldn't be comparing strings with == or !=.
while (!"q".equals(stringArray) && !"Q".equals(stringArray))
And you might as well use equalsIgnoreCase like in the other answer then. I simply wanted to point out the main flaw in the logic of using || instead of && here.

When i run my code, after inputting a number it doesnt let me input a string, and it goes ahead

when i input the number it just moves ahead without letting me enter the string and shows an output
when i use sc.next();, it does not go forward without the string, but i want to use sc.nextLine(), but it is not working
public class project1
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int n;
char a;
System.out.println("Enter \n 1 for counting the total number of vowels in it \n 2 for printing the first letter of each word in a string");
n = sc.nextInt();
switch(n)
{
case 1:
int count = 0;
System.out.println("Input a string");
String str = sc.nextLine();
str = str.toLowerCase();
for(int i = 0; i < str.length(); i++)
{
a = str.charAt(i);
if(a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
count++;
}
System.out.println("There are "+ count +" vowels in the string.");
break;
case 2:
System.out.println("Input a string");
String str2 = sc.nextLine();
System.out.println("First letter of each word:");
for(int i = 0; i < str2.length(); i++)
{
a = str2.charAt(i);
if(a == ' ')
System.out.print(str2.charAt(i+1) + ", ");
}
break;
}
}
}
The sc.nextInt will only read the integer part and leave the rest on the input stream for your next scanner command. Therefor the newline character from your first entry is still available when you try to get the string input with sc.nextLine().
You could either read the entire line and convert it to an int with:
n = Integer.parseInt(sc.nextLine());
switch(n)
or you could simply add a sc.nextLine() after your sc.nextInt() to consume the rest of the input line.
n = sc.nextInt();
sc.nextLine();
switch(n)
By the way, your method for writing the first letter of each word will skip the first word and also crash if the sentence ends with a space. Maybe try String.split() instead.

Trying to end loop when user input = q

Essentially I am trying to create a Pig Latin converter. However, for this assignment a requirement is to allow the user to enter 'Q' to quit entering in words. I can get the code to compile, but whenever the user enters Q it crashes and throws:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at mission4aa.Mission4AA.main(Mission4AA.java:38)
I am just completley unsure where to even go about fixing this. I've been trying.
import java.util.Scanner;
public class Mission4AA {
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
System.out.println("Enter another word(Q to exit): ");
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}
}
Because when you are doing this check
if(userInput.charAt(1) != firstVowel) {
If the user has input a 'q', userInput will only have a 0 term ( Length 1 ). You are effectively trying to get the second character of the users input. To solve your problem, i would do the check for 'q' at the start of the do section ( or simply scrap the do-while concept and use a while(true) loop ). Note that in future you should handle input that is of length 1. But for your issue, something like this would work
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
//here
if(userInput.equals("q") || userInput.equals("Q")){
System.out.println("Thank you");
return;
}
//else continue
If the user enters just Q or q - there's no char at index 1, which is why your code throws the java.lang.StringIndexOutOfBoundsException exception.
There are many ways to fix this. In my case, I just converted your do-while to a while(true) and I use break if the input is just Q or q.
// get first input
userInput = scanIn.next();
while(true){
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
// check next word here - if Q or q, break out and finish
userInput = scanIn.next();
if(userInput.equalsIgnoreCase("q")) {
break;
}
System.out.println("Enter another word(Q to exit): ");
}
Note - you'd need to rearrange your print statements accordingly.
The problem appears to be that you read the user input in the beginning of the loop, thus the condition in your do-while loop checks the previous user input - not the new one.
In addition the else-branch of your if-statement assumes that the input is at least 2 characters long if(userInput.charAt(1) != firstVowel) {...}.
This is what causes the exception as the input "q" reaches the else-branch, but is only of length 1.
You need to make two changes to your code:
You need to read the userinput before checking the loop-condition.
In the else-branch you must check that the input is at least 2 characters long before checking if the second character is a vowel.
Modified code below:
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
do {
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(end > 1 && userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
} else { /* Handle handle input of length 1 */}
}
System.out.println("Enter another word(Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}

I can't restrict my program to accept only binary numbers

I'm creating a program for my gui number converter. I want my program to ask user a binary string and if he does not enter a binary number, the program will show him error message and will ask him to enter again. The problem is that I can add restriction to alphabets but when it comes to numbers then it fails or it keeps showing the error message.
import java.util.*;
public class test {
Scanner key = new Scanner(System.in);
String in;
int b;
public test(){
do{
System.out.println("Enter the binary string of 5 numbers");
in = key.nextLine();
int i,j;
char ch;
for (i=0 ; i<=5 ; i++){
b = 0;
ch = in.charAt(i);
j = ch;
if (Character.isDigit(ch) && ch<=0 && ch>=1)
b = 1;
else
System.out.println("Please enter a binary number (1 , 0)");
break;
//b = 1;
}
}while(b != 1);
int c;
c = Integer.parseInt(in);
System.out.println("your number is: " + c );
}
public static void main (String args[]){
test obj = new test();
}
}
ch<=0 && ch>=1 does not do what you think it does. The character codes for "0" and "1" are 48 and 49, so you should check for those instead. Also, your >= comparators are backwards, but that's not really the clearest way to write this code. And since you're comparing for just those two values, Character.isDigit(ch) is redundant.
Try one of these:
ch == 48 || ch == 49
ch == '0' || ch == '1'
Scanner has an overloaded nextInt method that uses a radix
int binaryNumber = scanner.nextInt(2);
1) First logic error here for (i=0 ; i<=5 ; i++) replace i<=5 to i<5
2) change the if else condition like below
if (Character.isDigit(ch) && (ch == '0' || ch == '1'))
{
b = 1;
}
else
{
System.out.println("Please enter a binary number (1 , 0)");
break;
}

How do I check if input is equal to a lettter in an array?

I am creating a hangman game and I was wondering how I would check if an inputted letter is equal to one in the array. The code is below.
Scanner input = new Scanner(System.in);
int x = 0;
System.out.println("Enter a word for hangman!!");
String word = input.next();
char[] word2 = word.toCharArray();
do{
System.out.println("guess a letter");
String letter = input.next();
if(letter. ){
}
}while( x < 5 );
Thanks
use a simple method
boolean containsLetter(char letter)
{
for(Char c : word2)
{
if(c == letter)
return true;
}
// We got here means no matches
return false;
}
Then check:
if(!containsLetter(letter))
// does not contain the letter

Categories