How do I check for an empty string in a Boolean statement? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an assignment where I have to attach the letters "un" to any word that the user inputs (unless the inputted word already has "un" in front of it, in which case I just return the inputted word). I'm testing my method but I encountered one problem: my program keeps returning an error if I were to test for an empty input. Here is my code:
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter: ");
String input = keyboard.nextLine();
if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else if(input.equals(""))
{
System.out.println("un");
}
else
{
System.out.println("un" + input);
}
So I wanted to ask how I can test for an empty input/blank string since, evidently, the "" quotations do not work.

There's nothing wrong with checking input.equals("") per-se. The problem is that you have another test beforehand that throws an exception if input is shorter than 2 characters.
There are several ways to solve this, but I'd just simplify things and use startsWith. An empty string doesn't really need a special case of its own - just slap un before it, and you'll get un:
if (input.toLowerCase().startsWith("un")) {
System.out.println(input);
} else {
System.out.println("un" + input);
}

You are having this problem because you are trying to get the substring of string that doesnt have the required length. Put the empty string check first.
if(input.equals("")||input.length==1)
{
System.out.println("un");
}
else if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else
{
System.out.println("un" + input);
}

If this weren't homework, and the library could be used for other things ( using it in this single purpose may be overkill ), you could use StringUtils.PrependIfMissing().
It does exactly this and handles nulls as well.

Related

Do while loop condition not matching with variables inputted through scanners [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 hours ago.
Improve this question
I am a beginner in Java and this issue arose when I was working on a HackerRank problem that I have solved but it still confuses me why it wouldn't work the first iteration of code I made to solve it. This code function is to separate a string and an integer into two columns with the integer being limited to three digits and string having 10 chr limit, covered by "========". Also, I intend the code only ends when the user has inputted "nothing" or white spaces.
However, the do while loop keeps going as its condition does not match the inputted variables created by the scanner, being white spaces. I had a clue that it might be when I used an integer scanner as it interfered with the string scanner, but I tried clearing the scanner by using nextLine(), and it wouldn't work with the loop. I tried using scanner.reset() and also declaring the integer first as a string and then converting it back to an integer but the loop keeps going. I tried simplifying it, and I found out that the loop ends when I use "word = scanner.nextLine();" but it wouldn't work with the loop. Hope you guys can educate me and possible ways to fix this issue.
package hackerRankTestCode;
import java.util.Scanner;
import java.lang.*;
import java.util.concurrent.atomic.DoubleAdder;
public class TestCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = "";
Integer number = 0;
String baruNumber = "";
System.out.println("================================");
do {
word = scanner.next();
number = scanner.nextInt();
String blank = new String(new char[15 - word.length()]).replace("\0", " ");
if(number<100 && number>=10){
baruNumber = "0"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=0 && number<10) {
baruNumber = "00"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=100) {
System.out.println(word+blank+number);
}
}
while(!word.isBlank() && number != 0);
scanner.close();
System.out.println("================================");
}
}

How to print several values stored in String? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need help with this problem, it seems it's not as easy I thought it would be. I've tried some options from early feedbacks but it didn't help.
The thing is though that when userinput is like: i dont know the output should be displayed in screen: Sure, Sir
Or when user-input is like: I dont know (I with upercase) the output should be: Sure, Sir.
Or when user-input is like: idk (i dont know) the output should be: Sure, Sir.
But neither of those things are happening so...Help!
import java.util.Scanner;
public class Something{
static void Some(){
Scanner input = new Scanner(System.in);
String answer;
System.out.println("Hello Sir, what can I do for you?");
answer = input.nextLine();
String [] idk = {"I dont know", "i dont know", "idk"};
if(answer.equals(idk)) {
System.out.println("Sure Sir ");
} else {
System.out.println("Sir, anything?");
}
}
public static void main(String [] args) {
Some();
}
}
input: I dont know or i dont know or idk
output: Sir, anything?
/*
provide the input value and a listing of acceptable values
returns true if acceptableValues contains value
*/
public static boolean anyMatch(String value, String... acceptableValues) {
return Arrays.stream(acceptableValues).anyMatch((String t) -> value.equals(t));
}
It's better to use a collection (Set or List) to store the versions of the acceptable answers and then use method Collection::contains. Also it may be worth to store the strings written in lower case, and convert the input to lower case:
List<String> idk = Arrays.asList("i don't know", "i dont know", "idk");
if (idk.contains(answer.toLowerCase())) {
System.out.println("Sure Sir ");
} else {
System.out.println("Sir, anything?");
}

What do i need to do, to make this trim method work? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
enter image description hereI'm trying to use trim to figure out if someone imputed an empty string, and return the response " Say something, please". This is the peace of code:
else if(statement.trim().length() == 0 )
{
response = "Say something, please";
}
To invoke the methods from String, you invoke from the String variable. Not the String class.
You probably wanted:
else if(userInput.trim().length() == 0)
where userInput is the string object you are interested to check whether it is empty.
Similar to what Danny said.
Before your if/else branches you should have a string variable already. Then you simply call trim on that variable.
String s = "Hey this isn't empty!! ";
if(false){
// never runs
else if(s.trim().length() == 0){
response = "Say something please";
}
You need first to create an instance of String
String Str = new String();
Then invocke trim methid
str.trim();

In java, how do I check if a string contains only 1 or 0 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Also, how would I prompt the user to try again until they enter something with only 1 or 0 in it?
I realize I must use a for, or a while loop, but I'm not sure what to put as the condition.
I'm trying to have it so the user is prompted to enter something in binary, and if they don't enter something in binary, to be asked again to enter something in binary, and repeated until they do.
Thanks in advance!
You can do this by a simple regular expression matching:
if (inputString.matches("^[01]+$")) {
// accept this input
}
Simply use Integer.parseInt (str, 2);
it will throw a NumberFormatException if not binary
You can inspect every character of the String like so:
String s;//user input
boolean bad=false;//Starts false-will change to true if the input is bad
for(char c:s.toCharArray())
if(!(c=='0'||c=='1')){//if c isn't 0 or 1
bad=true;
break;//break out of loop because we've already found a problem
}
You may want to use the pattern below. The concept is to provide a "regular expression" that provides the rules for a conforming string, along with the message to prompt the user for input and the source to read the user's input from. The loop continues until a conforming string is found, or the user breaks out with "exit". The function would return the conforming string, or a null if the user wants to exit.
public String getConformingString(Scanner source, String message, String pattern) {
String result = null;
boolean isConformingString = false;
System.out.println(message);
String trialString = source.mextLine();
while (!isConformingString) {
if (trialString.matches(pattern) {
isConformingString = true;
result = isConformingString;
} else if ("exit".equalsIgnoreString(trialString)) {
isConformingString = true;
} else {
System.out.println(message);
trialString = source.nextline();
}
}
return result;
}

Using while loops and if conditions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Write a program that keeps reading strings until it reads the string “xyz”. If your first name is
among the entered strings, the program prints “My name is there.” Otherwise, it prints “My
name is not listed. Please add it.”
import java.util.*;
public class problem1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name,name2="xyz";
Scanner input=new Scanner(System.in);
name=input.next();
while(name!="xyz")
name=input.next();
}
{
if (name.equals("rania"))
System.out.println("my name is there");
else
System.out.println("please enter your name");
}
}
Your problem is about understanding how block of code works. This is, you open a block of code using { and close it by using }. By doing this, all the code wrapped in { ... } will be a block, and this block will belong as a body for a statement. You can easily detect problems related to block of code if you indent the code properly. You can find more info about indentation here.
Also, you have a problem when comparing Strings. You should use equals method. There's a deeper explanation here: How do I compare strings in Java?
This is how your code should look like:
while(!name.equals("xyz")) {
if (name.equals("rania")) {
System.out.println("my name is there");
} else {
System.out.println("please enter your name");
}
name=input.next();
}
Note: This code is not meant to solve the text stated in your homework. It is only a guide to make your code able to compile and run with no problems. How to solve your exact homework... that's your work, not from us.
Actually if you had you tested out your code snippet (which was fairly close) you would have got it working in a couple of iterations.
Here is a fully tested code snippet that works as per problem statement:
public static void main(String[] args)
{
// TODO Auto-generated method stub
String name = "rania";
String endString = "xyz";
Scanner input= new Scanner(System.in);
String aString =input.next();
// Assume name will not be found6
Boolean isNameFound = false;
while(!aString.equals(endString))
{
if (aString.equals(name))
{
isNameFound = true;
// This is to ensure program does not quit when the name is found
// break;
}
aString = input.next();
}
if(isNameFound)
{
System.out.println("My name FOUND");
}
else
{
System.out.println("My name NOT FOUND");
}
}
Here is output for case 1: none of the string entered matched the desired name until the end string "xyz" was entered
sjhsa
sdkhfds
khds;kuf
xyz
My name NOT FOUND
Here is output for case 2: one of the string entered matched the desired name and the program ended.
afkhds
kjfdsgaks
fdgkjfd
gvkjfd
rania
My name FOUND

Categories

Resources