Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Hi here is just a fun number guesser where someone inputs a number and my while loop will run until it hits the number inputed. Its just a while loop practice because I am relatively new to Java and wanted more practice. Here is my code. (I am using IntelliJ IDEA)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean password = false;
int passwordGuess = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Password to be guessed");
int Password = sc.nextInt();
while (password) {
System.out.println("Test");
if (passwordGuess == Password){
System.out.println("Your Password is " + passwordGuess);
password = true;
}
else{
System.out.println(passwordGuess);
passwordGuess++;
}
}
}
}
It prints Enter a Password to be guessed, then I input a number and it prints "Process finished with exit code 0". Any Ideas, Thanks
You have initialized your password variable as false:
boolean password = false;
and then you try to use it in your while
while (password){/*...*/}
It won't work if password is false.
You have a variable password which you set to false.
You never set it to true, so your while loop reads "while (false)" which means it exits before running the block.
I think I must point to the fact that integer casting to boolean is false for any value. Check this question and answer.
So you might try the solution as orhtej2 posted
while (!password)
while loop only loops if expression is true, and you initialize password as false. Hance your loop should read:
while (!password)
set 'boolean password = true' if you want your while loop to start.
while(false) won't start and currently your password is set to false.set boolean password = true if you want your while loop to start.
Related
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();
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.
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;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
i am getting "illegal character '\u600b' in my return statement for the following code:
public static int getNum() {
Scanner in = new Scanner(System.in);
int number;
boolean goodInput = true;
do {
goodInput = true;
try {
System.out.print("Please enter a positive number: "); // prompts the user
number = Integer.parseInt(in.nextLine()); // Tries to make the next input a number
} catch (Exception e) { // if it breaks
System.out.println("The number you entered was invalid."); // it tells the user it was wrong
goodInput = false; // and runs the loop again
}
if(number <= 0) { // makes sure that the number entered was valid
System.out.println("The number you entered was invalid.");
goodInput = false; // or it re runs the loop
}
}while (!goodInput)
return number;
}
any one know how to fix this?
In looking at the Markdown source of your post, I found a stray non-printable character right before the return. You need to delete that entire line and retype it (or delete that character itself).
If you place the cursor between the r and the e, and press <- a few times, you will see that the cursor does not move one of those times.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
when I call the method "getUnknownsAccel" with the problem1 object, for some reason the 'if' statement in the method is not executed to retrieve the value of the variable:
PhysicsProblem problem1 = new PhysicsProblem(accel, vI, vF, t, deltaX);
System.out.println("Which variable are you solving for? ");
String solveFor = scan.next();
// after receiving solveFor input, assesses data accordingly
if (solveFor.equalsIgnoreCase("acceleration"))
{
System.out.println("Solving for Acceleration!");
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.next();
problem1.setMissingVar(missingVar);
do
{
problem1.getUnknownsAccel();
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.next(); //// change all these in the program to scan.next, not scan.nextLine
}
while (!missingVar.equalsIgnoreCase("none") || !missingVar.equalsIgnoreCase("acceleration"));
if (missingVar.equals("none"))
{
// Write code for finding solutions
System.out.println("Assuming you have given correct values, the solution is: ");
}
}
After the do/while loop used to retrieve the name of the other variables that are unknown, I call the getUnknownsAccel method from this class file:
public void getUnknownsAccel()
{
//-----------
// checks for another unknown value that is not accel
//-----------
if (missingVar.equalsIgnoreCase("time"))
{
System.out.println("Please enter the value for time: ");
t = scan.nextDouble();
while (t <= 0 || !scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
t = scan.nextDouble();
}
}
}
Let's assume for the sake of this problem, that the user WILL enter "time" as the unknown when prompted. Any idea why my code isn't executing the scan function to retrieve the time variable value? Instead, the program just repeats the system.out function "Are there any other unknowns..."
After scanning, you set missingVar to scan.next(), but you do not do anything. The loop continues.
After
missingVar = scan.next();
add the line
getUnknownsAccel();
Note, another issue is that you will need to handle later is that missingVar is local - to access it in getUnknownsAccel(), you should change the declaration to
public void getUnknownsAccel(String missingVar){
}
and instead use
getUnknownsAccel(missingVar);