"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.
Related
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.
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
I am attempting to take an input of A or B in either Uppercase or LowerCase to follow on through the if statement. I can't figure out how to do this. At the moment, it's only taking in UpperCase A or B. Looked around the forum and the class notes, came up with nothing. Any help would be appriciated!
I tried using toUpperCase() but don't think i am putting it in the right place. It keeps giving me an error
import java.util.Scanner;
public class printNumber{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please select an option between A or B: ");
char user = input.next().charAt(0);
System.out.println("You have selected " +user+ " : ");
if (user == 'A'){
for(int n=1; n<=100; n++){
if((n%2)==0)
System.out.println(n);
}
}
else if (user =='B'){
for (int x =1; x<=100; x=x+2){
System.out.println(x);
}
}
else
System.out.println("Error, please try again!");
}
}
import java.util.Scanner;
public class printNumber{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please select an option between A or B: ");
String opt=input.nextLine();
System.out.println("You have selected " +user+ " : ");
if (opt.equalsIgnoreCase("A")){
for(int n=1; n<=100; n++){
if((n%2)==0)
System.out.println(n);
}
}
else if (opt.equalsIgnoreCase("B")){
for (int x =1; x<=100; x=x+2){
System.out.println(x);
}
}
else
System.out.println("Error, please try again!");
}
}
or you can simply use
import java.util.Scanner;
public class printNumber{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please select an option between A or B: ");
String opt=input.next();
System.out.println("You have selected " +user+ " : ");
if (opt == "A" || opt == "a"){
for(int n=1; n<=100; n++){
if((n%2)==0)
System.out.println(n);
}
}
else if (opt == "B" || opt == "b"){
for (int x =1; x<=100; x=x+2){
System.out.println(x);
}
}
else
System.out.println("Error, please try again!");
}
}
You can use
char user = input.next().toUpperCase().charAt(0);
Try this
if (user == 'A' || user == 'a')
The same for 'B'
You are calling next() method of Scanner class, which returns String, so rather than converting it into a character you can use equalsIgnoreCase() method on the input String for validation. But always check the length of the input string and show error message if the length of the string entered by user is greater than 1.
"a".equalsIgnoreCase("A") and "a".equalsIgnoreCase("a") will be always true.
I really do not know to how explain this but here we go.
I am testing something for a bigger program I have to make. In the program I have to validate input from the user to see if it is being to be accepted as a valid answer.
I have the code to where it will say if the input is invalid but if I attempted to enter another letter the code crashes with this error:
Enter a letter:
f
Your answer is not valid.
A
Enter a letter:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at example.main(example.java:18)
Here is the code:
import java.util.Scanner;
public class example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
user_answer=input.nextLine().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
input.next();
}
}
while (!UserInput);
}
}
either remove input.next() or change it to input.nextLine()
What's happening is that input.next() will catch the A you input. Then you go back to the beginning of the do and start over, and do input.nextLine() but you had already pressed enter to input A and the A was consumed by input.next().
Remove the input.next(); and it will work fine. The reason is because when you use input.next(), it reads the next character the user types, without exiting the line. Then when the input.nextLine() executes, it reads that same line, but immediately after the number. Since nothing is after the number, it reads in nothing "" and the charAt(0); becomes out of bounds.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
// user_answer=input.nextLine().charAt(0);
user_answer=input.next().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
// input.next();
}
}
while(!UserInput);
}
}
The assignment asks for three strings of alphabetical input (that is, letters and no numbers), then compare lexicographically and draw the middle one.
I found a similar concern here (Java: Three strings, lexicographic order), but can't comment to add my question. I sorted (for an instant) how to appropriately return the output, but now the code isn't giving any output and I don't know what I did wrong.
public static void main(String[] args)
{
printHeading();
String topString;
String middleString;
String bottomString;
Scanner in;
in = new Scanner(System.in);
System.out.println("Please enter a first word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a first word:");
in.nextLine(); // Captures the first word
}
String firstWord = in.nextLine();
System.out.println("Please enter a second word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a second word:");
in.nextLine(); // Captures the second word
}
String secondWord = in.nextLine();
System.out.println("Please enter a third word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a third word:");
in.nextLine(); // Captures the third word
}
String thirdWord = in.nextLine();
if (firstWord.equalsIgnoreCase(secondWord) && secondWord.equalsIgnoreCase(thirdWord))
{
System.out.println();
System.out.println("The words are the same! Please try again.");
}
if (firstWord.compareTo(secondWord) > 0 && firstWord.compareTo(thirdWord) > 0)
{
topString = firstWord;
}
else if (firstWord.compareTo(secondWord) < 0 && firstWord.compareTo(thirdWord) > 0)
{
middleString = firstWord;
System.out.println();
System.out.println("The second word in lexicographic order is: " + middleString);
}
else
{
bottomString = firstWord;
}
if (secondWord.compareTo(firstWord) > 0 && secondWord.compareTo(thirdWord) > 0)
{
topString = secondWord;
}
else if (secondWord.compareTo(firstWord) < 0 && secondWord.compareTo(thirdWord) > 0)
{
middleString = secondWord;
System.out.println();
System.out.println("The second word in lexicographic order is: " + middleString);
}
else
{
bottomString = secondWord;
}
if (thirdWord.compareTo(secondWord) > 0 && thirdWord.compareTo(firstWord) > 0)
{
topString = thirdWord;
}
else if (thirdWord.compareTo(secondWord) < 0 && thirdWord.compareTo(firstWord) > 0)
{
middleString = thirdWord;
System.out.println();
System.out.println("The second word in lexicographic order is: " + middleString);
}
else
{
bottomString = thirdWord;
}
Your string comparison statements are incorrect - you need to check them and rewrite it. Here is another way to do it:
import java.util.Scanner;
public class FindMiddleWord
{
public static void main(String[] args)
{
String[] wordArray = new String[3];
Scanner in;
in = new Scanner(System.in);
System.out.println("Please enter a first word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a first word:");
in.nextLine(); // Captures the first word
}
String firstWord = in.nextLine();
wordArray[0] = firstWord;
System.out.println("Please enter a second word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a second word:");
in.nextLine(); // Captures the second word
}
String secondWord = in.nextLine();
wordArray[1] = secondWord;
System.out.println("Please enter a third word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a third word:");
in.nextLine(); // Captures the third word
}
String thirdWord = in.nextLine();
wordArray[2] = thirdWord;
String temp;
int i,j = 0;
for (i = 0; i < wordArray.length; i++) {
for (j = 0; j < wordArray.length; j++) {
if (wordArray[i].compareToIgnoreCase(wordArray[j]) < 0) {
temp = wordArray[i];
wordArray[i] = wordArray[j];
wordArray[j] = temp;
}
}
}
System.out.println("The Middle Word is : "+wordArray[1]);
}
}