How would I split this inputted string? (Java) - 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;
}
}

Related

How to get the Scanner to scan all the elements in an array, in java

This is the Question: Create an array of Strings and assign 5 names to it. Ask the user what their name is, if their name is the same as one that is already in the list do something. Get creative!, use a for-each loop to print every name in the array with a space in-between each indices.
This is what I have so far. One of the issues I am having is that the scanner is only comparing the input to the first name on the array and not the rest.
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
}
else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
break;
}
}
}
Feel free to comment on any other issues you see. I am new at this and I'd appreciate an feedback. Thx
Maybe this will be helpful. I think the "break" is called prematurely. There are lots of ways you can solve this, but I used a boolean to determine if the name was found. Then I used the boolean after the loop to determine what to print.
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
boolean isFound = false;
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
isFound = true;
break;
}
}
if (isFound) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
} else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
}
Same method but slightly different :)
`import java.util.Scanner;
import java.util.ArrayList;
public class New {
public static void main (String[]args) {
String [] cities = {"Poznan", "Warsaw", "Gdansk", "Wroclaw", "Krakow", "Lodz", "Katowice"};
Scanner scan = new Scanner(System.in);
System.out.println("What is the name of your city in Poland? ");
String name = scan.nextLine();
for (String n:cities) {
if (n.equalsIgnoreCase(name)) {
System.out.println("You are citizen of Poland from " +name);
System.out.println("Thank your for visiting " +name);
}
else {
System.out.println("You are not from Poland!!!" );
System.out.println("There is not city in Poland called" +name);
}
break;
}
}
}`

How do get the code to respond if user dose not type anything and just presses enter?

I want my code to respond if the user only presses enter and doesn't type anything else. I use .trim to react to only putting in spaces but, it gives me an error when I just hit enter as the input. Here is what I have so far:
import java.util.Scanner;
class Main {
static Scanner name = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What is your first name?");
String a = name.nextLine();
String b = a.substring(0, 1).toUpperCase() + a.substring(1);
String c = a.trim();
if (c.length() != 0) {
if (a.contains(" ")) {
System.out.println("You put space in your name. : (");
} else {
System.out.println(b + " is a nice name! : )");
}
} else {
System.out.println("Thats not a name! : (");
}
}
}
try (Scanner scan = new Scanner(System.in)) {
System.out.println("What is your first name?");
String str = scan.nextLine().trim();
if (str.isEmpty())
System.err.println("You entered an empty name");
else if (str.contains(" "))
System.err.println("You put space in your name.");
else {
String name = Character.toUpperCase(str.charAt(0)) + str.substring(1);
System.out.println('\'' + name + "' is a nice name!");
}
}
I think this is probably what you want. Furthermore, I've also highlighted a few best practices.
class Main {
private static Scanner scanner = new Scanner(System.in); // Point 0 - Use access modifiers!
public static void main(String[] args) {
System.out.println("What is your first name?");
String name = ""; // Point 1 - Initialize your variables to avoid NullPointerException
// Point 2 - Always check if there is something to read from scanner
if (scanner.hasNextLine()) {
name = scanner.nextLine();
}
// Point 3 - You can methods in place instead of stack variables
if (!name.isEmpty()) {
if(name.contains(" ")) {
System.out.println("You put space in your name. : (");
} else {
// Point 4 - You can do away with extra variables
System.out.println(capitalize(name) + " is a nice name! : )");
}
} else {
System.out.println("That's not a name! : (");
}
scanner.close(); // Point 5 - Clean up your resources
}
// Point 6 - Concise methods makes code more readable
private static String capitalize(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
}
You can look up more about Scanner.

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.

Java basic usage of string [duplicate]

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");

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");

Categories

Resources