Java basic usage of string [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am trying to code a program that allows to enter various words(step by step) until one types in "quit" .
I am having trouble stopping the loop (even with the word quit typed, it doesn't stop)
Using System.out.println(sum); I can check that the words are adding up, but it never stops..
((Summary : if(string == "quit") does not work and for (String end = "quit"; string!=end;) does not work ))
Sorry if its hard to read. its my second day coding :(
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
if (string == "quit")
{System.out.println("Ending system");
}
else{
for(String end = "quit"; string!=end; )
{
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
String stringextra = scanner.nextLine();
if(stringextra == "quit"){break;}
string = stringextra;
}
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
}}

Strings string and "quit" are not the same objects(as stored in the jvm) yet equal so checking with == will not work.
You need to use:
string.equals("quit")
see Object.equals() for more information

As pointed out in the other answer you need to use .equals() to compare strings. Also, your for loop is incorrect. A while loop is what is normally used in this case:
public class end_on_quit {
public static void main(String[] args)
{
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
while ( ! string.equals("quit") )
{
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
string = scanner.nextLine();
}
System.out.println("Ending system");
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
}

Easiest way to doing something like your code using do while so your code running until user write quit. I will give you simple example :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String stringextra = scanner.nextLine();
if (stringextra.equalsIgnoreCase("quit")) {
System.out.println("Bye bye");
System.exit(0);
} else {
do {
sum = sum + " " + stringextra;
System.out.println(sum);
System.out.println("Type in another word");
stringextra = scanner.nextLine();
} while (!stringextra.equalsIgnoreCase("quit"));
}
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
I hope this help you, good luck.

You should use equalsto compare strings. In this case for you example is better use while instead of for to loop.
When you use equalsIgnoreCase it means that is no matter if the word is upper case or lower case (is the same).
The application finishes when the user types "quit or ends or QUIT or ENDS"
Example:
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
while (!string.equalsIgnoreCase("quit")) {
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
string = scanner.nextLine();
if (string.equalsIgnoreCase("ends")) {
string = "quit";
}
}
System.out.println("Ending system");
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
System.exit(0);
}
Output:
Type in a word
hi
Type in another word
this
Type in another word
an
Type in another word
example
Type in another word
ENDS
Ending system
Stopping... due to the word quit
all the words typed are hi this an example
Process finished with exit code 0

Simply do System.exit(0) after System.out.println("Ending system");

Related

Parsing string generating my generated error message when nothing is entered

I am currently working on an assignment to parse strings and I am running into an issue.
It appears, that if nothing is entered, it is generating my error message I have created when a comma is not inputted.
According to the assignment in zybooks, it should not be outputting anything. Below is my code.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
//local variables
String lineString;
String firstWord;
String secondWord;
int commaLocation;
boolean inputDone;
//checks to end the program
inputDone = false;
//keeps the loop running until q is entered
while (!inputDone) {
System.out.println("Enter input string: ");
lineString = scnr.nextLine();
//checks comma
commaLocation = lineString.indexOf(',');
if (commaLocation == -1) {
System.out.println("Error: No comma in string");
}
else {
firstWord = lineString.substring(0, commaLocation);
firstWord = firstWord.replace(" ", "");
secondWord = lineString.substring(commaLocation + 1, lineString.length());
secondWord = secondWord.replace(" ", "");
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
System.out.println();
}
if (lineString.equals("q")) {
inputDone = true;
}
}
return;
}
}
It happens because when nothing is entered, comma cannot be found, therefore indexOf returns -1.
I would add something like
if (lineString.isEmpty()) {
continue;
}
right after lineString = scnr.nextLine();
EDIT:
I just noticed, that your error message will be printed in case, when your input equals 'q'. I assume this is not an expected behaviour, so I recommend to place
if (lineString.equals("q")) {
inputDone = true;
}
right after assignment of lineString or the if block I suggested above.

Asking user to enter specific number of strings then adding each string to array?

New to java. I need to ask the user the number of strings (consisting only of upper and lowercase letters, spaces, and numbers) they want to input. These strings need to be stored in an array. Then I created a boolean method to be able to tell if those strings are palindromic (ignoring spaces and cases). If it is palindromic then I add to the result list to print later on. I am confused on how to ask the user to input that exact amount of strings and how to check each individual string. I must use StringBuilder. This is what I have so far (it's kind of a mess, sorry). I feel like I'm using the StringBuilder/array wrong, how can I fix this?
public class Palindromes {
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder(numOfStrings);
for(int n=0; n < paliString; n++){
paliString[n] = scan.nextLine();
scan.nextLine();
String[] stringPali = new String[numOfStrings];
StringBuilder str = paliString;
if(isPali(userString)){
paliString = append.userString;
}
System.out.println("The palindromes are: " + userString ";");
}
static boolean isPali(String userString) {
int l = 0;
int h = userString.length() - 1;
// Lowercase string
userString = userString.toLowerCase();
// Compares character until they are equal
while (l <= h) {
char getAtl = userString.charAt(l);
char getAth = userString.charAt(h);
// If there is another symbol in left
// of sentence
if (!(getAtl >= 'a' && getAtl <= 'z'))
l++;
// If there is another symbol in right
// of sentence
else if (!(getAth >= 'a' && getAth <= 'z'))
h--;
// If characters are equal
else if (getAtl == getAth) {
l++;
h--;
}
// If characters are not equal then
// sentence is not palindrome
else
return false;
}
// Returns true if sentence is palindrome
return true;
}
}
SAMPLE RESULT:
Enter the number of strings: 8
Enter the strings:
Race Car
Mountain Dew
BATMAN
Taco Cat
Stressed Desserts
Is Mayonnaise an instrument
swap paws
A Toyotas a Toyota
The palindromes are: Race Car; Taco Cat; Stressed Desserts; swap paws; A Toyotas a Toyota
As I think the best way to answer this is to help you learn in small steps, I tried to stick with your initial idea on how to solve this and edited your main method with minimal changes.
This one does the trick.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
if (paliString.length() > 0) {
paliString.append("; ");
}
paliString.append(userString);
}
}
System.out.println("The palindromes are: " + paliString);
}
Key changes:
I added scan.nextLine(); right after reading the number of strings. This handles the newline you get when the user hits enter.
You don't need to initialize the StringBuilder with numOfStrings. This just preallocates the size of the StringBuilder in characters. Not the number of strings. Either way, it's not necessary. StringBuilder grows as needed.
I suggest you inspect what I did inside the for-loop. This was the biggest mess and changed significantly.
Last but not least: Writing the result needs to be outside of the for-loop, after all palindromes have been added to the StringBuilder.
Edit
Based on your comment, in this next iteration, I changed the usage of StringBuilder to the usage of an ArrayList. (Which is something completely different)
I am using it here because Lists in Java grow on demand. And since the number of palindromes is probably not equal to the number of input strings, this is the way to go. To really assign it to an array, one could always call String[] paliStringsArray = paliStrings.toArray(new String[]{}); but as ArrayLists already use an underlying array and are not necessary to to generate the output you want, I didn't put it into the new version.
Please compare the differences of this step to the previous version. I also added this String.join("; ", paliStrings) part, which creates the output you want.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
And now to the last step. Arvind Kumar Avinash actually solved a part that I also missed in the initial question. (I'll read more carefully in the future). He was validating the user input. So for the last iteration, I added his validation code in a modified way. I put it into a method as I think that makes things clearer and gets rid of the necessity of a the boolean valid variable.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = readNextLine(scan);
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
static String readNextLine(Scanner scanner) {
while (true) {
String userString = scanner.nextLine();
if (userString.matches("[A-Za-z0-9 ]+")) {
return userString;
} else {
System.out.println("Error: invalid input.");
}
}
}
I need to ask the user the number of strings (consisting only of upper
and lowercase letters, spaces, and numbers) they want to input. These
strings need to be stored in an array.
I have done the above part of your question. I hope, this will give you direction to move forward.
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
System.out.print("Enter a string consisting of only letters and digits: ");
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: a
Error: invalid input.
Enter the number of strings: 3
Enter a string consisting of only letters and digits: Arvind
Enter a string consisting of only letters and digits: Kumar Avinash
Enter a string consisting of only letters and digits: !#£$%^&*()_+
Error: invalid input.
Enter a string consisting of only letters and digits: Hello #
Error: invalid input.
Enter a string consisting of only letters and digits: Hello 123
Feel free to comment in case of any doubt/issue.
Wish you all the best!
[Update]
Based on your request, I have posted the following update which asks for the strings only once and then allows the user to enter all the strings one-by-one:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
System.out.println("Enter " + numOfStrings + " strings consisting of only letters and digits: ");
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: 3
Enter 3 strings consisting of only letters and digits:
Arvind
Kumar
He$ll0
Error: invalid input.
Avinash
Feel free to comment in case of any doubt.

How to restrict amount of characters a user can enter?

For my program below, I want it so that the user must enter a word 2 or more characters long, but I do not know how to make that restriction.
This is a palindrome program, and it is used to test whether the word is a palindrome or not. It lets me enter a word of any length but I want to restrict to 2 or more, and if they enter only a one character word, a message should display "Wrong word".
import java.util.*;
class PalindromeTesterSamJiang1 {
public static void main(String [] arg) {
int x=0;
Scanner in=new Scanner(System.in);
System.out.printf("Menu: Please select an option \n"
+ "1)Palindrome Tester\n"
+ "0)Exit program \n");
x=in.nextInt();
switch (x){
case 1:
lol test=new lol();
test.palindromeTester("");
test.displayInfo();
break;
default:
System.out.println("Goodbye");
break;
}
}
}
class lol {
String original, reverse = "";
public String palindromeTester(String reference) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word to Test: ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
return original;
}
public void displayInfo() {
if (original.equals(reverse))
System.out.println("RESULT: A PALINDROME");
else
System.out.println("RESULT: NOT A PALINDROME");
String[] arguments = new String[] {"123"};
PalindromeTesterSamJiang1.main(arguments);
}
}
You can read the input in a loop,
print an error if the input is too short,
break out when you get a valid input, for example:
while (true) {
System.out.println("Enter a word to Test: ");
original = in.nextLine();
if (original.length() > 2) {
break;
}
System.out.println("Too short. Word must be at least 2 characters");
}
System.out.println("Enter a word to Test: ");
original = in.nextLine();
String[] array = original.split(" ");
if(array.length < 2)
System.out.print("Enter atleast 2 sentence");

How would I split this inputted string? (Java)

I have been working on a program that prompts the user to enter strings, and they are assumed to only enter strings "f name" or "m name." It then lists the names of the males and females entered in separate lists. However, instead of the program listing just the names, it also lists the "f"s and "m"s in front of each name. I tried placing a split method after the user inputs the gender and name, but it doesn't work. I'm sure I'm missing something, but I can't seem to place it. Any help would be appreciated. :)
package labs.lab5;
import java.util.Scanner;
public class NameProcessor {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
UnboundedQueueInterface<String> males;
males = new ArrayUnbndQueue<>(10);
UnboundedQueueInterface<String> females;
females = new ArrayUnbndQueue<>(10);
String input;
do{
System.out.print("Input a gender and name (x done to quit)>");
input = s.nextLine();
input.split(" ");
if(input.startsWith("m"))
{
males.enqueue(input);
}
else if(input.startsWith("f"))
{
females.enqueue(input);
}
else if(input.startsWith("x done"))
{
break;
}
}
while(!input.startsWith("x done"));
System.out.print("males: ");
while(!males.isEmpty())
{
input = males.dequeue();
System.out.println(input + " ");
}
System.out.print("females: ");
while(!females.isEmpty())
{
input = females.dequeue();
System.out.println(input + " ");
}
}
}
Replace males.enqueue(input); with males.enqueue(input.substring(2));
Actually you need to skip first 2 symbols: 'm' (or 'f') and ' '.
You should check for null values and trim the string, but otherwise a simple modification to your code, as follows, works.
do{
System.out.print("Input a gender and name (x done to quit)>");
input = s.nextLine();
String[] tokens = input.split(" ");
if(input.startsWith("m"))
{
males.enqueue(tokens[1]);
}
else if(input.startsWith("f"))
{
females.enqueue(tokens[1]);
}
else if(input.startsWith("x done"))
{
break;
}
}

How to limit the input to the Scanner?

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = checkInput(in, "Enter an integer and a base: ");
int inputBase = checkInput(in, "");
}
public static int checkInput(Scanner in, String prompt) {
System.out.print(prompt);
while (!in.hasNextInt()) {
in.next();
System.out.println("Sorry, that is an invalid input.");
System.out.print(prompt);
}
return in.nextInt();
}
This method works and doesn't return any bad input i.e., ; p "hello".
My question is how can I limit the number of inputs the scanner will read. Say I input 5 five % ; but I only want 5 and five to be passed in to my method and the rest dropped.
I looked through the Java API but couldn't find a method that would limit the amount of user input accepted. Am I just missing it or is there another way to do this?
Edit: I have tried using the .length() method to limit the input but then that doesn't allow integers greater than the .length() parameter.
Here is a working sample of how you could accomplish what you need. I broke it up so that the user is prompted once for each input which makes it easier to validate. I changed your checkInput method to getInput which only returns valid user input as a String where it is then converted into an int.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = Integer.parseInt(getInput(in, "Enter an integer: "));
int inputBase = Integer.parseInt(getInput(in, "Enter a base: "));
System.out.println("Int: " + inputInt + ", base: " + inputBase);
}
public static String getInput(Scanner in, String prompt) { // Get valid user input
System.out.print(prompt); // Tell user what to input
String text = "";
while (true) { // Keep looping until valid input is found
text = in.nextLine(); // Get input from stdin
if(isInteger(text)) // Check if they put in integer
break; // Exit loop
System.out.print("Try again, " + prompt); // Wasn't valid, prompt again
}
return text; // Return valid user input
}
private static boolean isInteger(String str) { // Check if string is integer
try {
Integer.parseInt(str); // If this doesn't fail then it's integer
return true;
} catch(NumberFormatException e) {
return false; // Wasn't integer
}
}
Sample run:
Enter an integer: 2 dog five 3
Try again, Enter an integer: 2
Enter a base: cat
Try again, Enter a base: 3
Int: 2, base: 3
It helps to separate functionality - you were trying to read input, validate input, and convert to int all in one method. If you break it up it becomes easier to manage.
Scanner sc= new Scanner(System.in);
String string = sc.findInLine(".{500}"); // length of your input you want
findInLine(String pattern)
method of Scanner class of java.util package. This method returns a String object that satisfies the pattern specified as method argument.
see this article
If you want to only get the first two words (or strings delimited by spaces) you can use the str.split(" "); method.
For example:
String input = in.nextLine(); // Gets the next line the user enters (as a String)
String[] inputWords = input.split(" "); // inputWords[0] is first word, inputWords[1]
// is second word... etc
String validInput = inputWords[0] + " " + inputWords[1]; // Combines the first and
// second words into a string, so if you had "5 five %" validInput would be "5 five"
// inputWords[0] is "5", inputWords[1] is "five", inputWords[3] is "%" etc for any other words...
This will essentially limit the number of inputs to two words. I hope this helps!
Scanner scan = new Scanner(System.in);
System.out.println ("enter a 2 numbers");
String s;
s = scan.nextLine();
Scanner scan2 = new Scanner(s);
int one = scan2.nextInt();
int two = scan2.nextInt();
System.out.println (" int 1 = " + one + " int 2 = " + two);
enter a 2 numbers
23 45 68 96 45
int 1 = 23 int 2 = 45
Process completed.

Categories

Resources