Program terminating before if statement [closed] - java

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 9 years ago.
Improve this question
I'm having trouble initializing an if statement in this program. The program terminates before running the if statement every time. Can anyone tell me what exactly I'm doing wrong?
import java.util.Scanner;
public class attempt1 {
public static void main (String [] args) {
Scanner console = new Scanner(System.in);
String userInput;
boolean done=false;
System.out.println("say something");
userInput=console.nextLine();
if (userInput.equals("stop")) {
done=true;
}
while(done=false) {
System.out.println("it worked!");
}
}
}

I think you want something like this:
public static void main (String [] args) {
Scanner console = new Scanner(System.in);
String userInput;
boolean done=false;
while(done==false) {
System.out.println("say something");
userInput=console.nextLine();
if (userInput.equals("stop")) {
done=true;
}
}
System.out.println("it worked!");
}
This code asks the user to keep saying something until they say stop at which point it prints out "it worked!"
The program will wait for your input every time you call userInput=console.nextLine(); It's not terminating, but just waiting for input.
Also, you want == in your while comparison. == compares values while = assigns

Use do-while here, it would be easier:
Scanner console = new Scanner(System.in);
String userInput;
do {
System.out.println("say something");
userInput=console.nextLine();
if(userInput.equals("stop"))
break;
} while(console.hasNextLine());

Instead of this construct
if (userInput.equals("stop")) {
done=true;
}
while(done=false) {
System.out.println("it worked!");
}
I suppose you wanted to say:
done = userInput.equals("stop")
if (!done) {
System.out.println("it worked!");
}
I'm not sure what was the purpose of while but you certainly didn't want to use a loop in this case.

You are using a scanner. If the user doesn't enter any data, the program won't run. Try running it with a preset string or int or whatever you need. The code looks fine

I see a couple of problems here.
Are you certain that there is a next line? To be sure:
System.out.println(console.hasNextLine())
Also, your boolean is incorrect. Remember that a single '=' is an assignment, and '==' means "is equal to".

You have an infinite loop.
while(done=false) {
System.out.println("it worked!");
}
This crashes the program. Just simply change while(done=false) to "else if (!done)".

Related

Print the integers from 1 to a number given by user [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm doing the Java MOOC by Helsinki University. Stuck on the following problem:
Write a program which prints the integers from 1 to a number given by the user.
Sample output
Where to? 3
1
2
3
The code below outputs the expected results but is not accepted as valid. Any suggestions or pointers are welcome, thank you!
import java.util.Scanner;
public class FromWhereToWhere {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = Integer.valueOf(scanner.nextLine());
int start = 1;
while (start <= userInput) {
System.out.println(start);
start++;
}
}
}
Most likely the system that tests your program is stuffing values into standard input (System.in) with spaces, and assumes that you will read with .nextInt().
If that's not it, double check the program description; what is supposed to happen if I enter -1? 0? 1985985410395831490583440958230598? FOOBAR?
If it doesn't say, then presumably the verifier won't throw those inputs at you (if it does, file a bug with the MOOC provider, the course itself needs fixing if that is the case), but if it does, you're going to have to code those rules in, probably.
This shouldn't be it, but to exactly mirror the desired result, it's System.out.print("Where to? "); - note, no ln, and a trailing space.
You did not check if the user input is valid, I would suggest starting off with the following:
check if userInput is a valid number (includes numeric characters).
check if userInput is larger or equal to 1.
your answer is ok but can be optimized to the beginners levels if that is what your teacher is expecting because:
you can get an int directly from scanner, no need to use the wrapper class Integer.
you can use another loop ... a for loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = scanner.nextInt();
System.out.println("ok!");
for (int i = 1; i <= userInput; i++)
{
System.out.println(i);
}
}
Just try by Removing
System.out.println("Where to?");
with
System.out.print("Where to?");

I have no idea why this java code doesn't work [closed]

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 2 years ago.
Improve this question
Ok SO I made an escape the room program and the boolean for light doesn't work
class Main {
public static void main(String[] args) {
System.out.println("Welcome To The Hogwarts Escape Room");
System.out.println("To Play The Hogwarts Escape Room Press Y");
Scanner sc = new Scanner(System.in);
String useranswer = sc.nextLine();
boolean light = false;
// This is not my entire code but the part that was necessary.
System.out.println("Press U to look up");
useranswer = sc.nextLine();
if (usernaswer.equals("U"){
System.out.println(" You look above you and see nothing as the ceiling is too dark to see in.");
System.out.println("Would you like to: \n Look Closer press A \n Return To Your Original Position press B");
useranswer = sc.nextLine();
System.out.println(light);
// this part doesn't work.. I checked and made sure the useranswer was A and the boolean does equal to false.
if (useranswer.equals("A")&&(light = false)){
ceilingCloserlightFalse(sc, useranswer, inventory, light);
}
else if (useranswer.equals("B")){
original(sc, useranswer, inventory, light);
}
// this was the setup to the constructor
public static void ceilingCloserlightFalse(Scanner sc, String useranswer, String [] inventory, boolean light){
System.out.println("You go closer and see something faintly but cant tell what it is without a light");
System.out.println("You returned to the original position because there was nothing else to do there.");
original(sc, useranswer, inventory, light);
}
}
}
Ok So I wonder if I am doing something wrong with the method or the && operator. I checked to make sure that useranswer was a and I also checked to make sure that
Here you are assigning false to the variable, not comparing it:
if (useranswer.equals("A")&&(light = false)){
ceilingCloserlightFalse(sc, useranswer, inventory, light);
}
You want to use ==, not =. Also, consider that useranswer might be null, so you should be doing "A".equals(useranswer) to avoid a NullPointerException
Some developers use Yoda speak to avoid the common mistake we have here.
Instead of:
if (useranswer.equals("A")&&(light = false)){
ceilingCloserlightFalse(sc, useranswer, inventory, light);
}
Write your comparison backward like
if (useranswer.equals("A")&&(false = light)){
ceilingCloserlightFalse(sc, useranswer, inventory, light);
}
Then you'd get a compiler error pointing you to the fact you're using = instead of ==.

I want to print the output using method but then i cant print it. WHY? [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 3 years ago.
Improve this question
This is my code.
What I think my error is that method code.
import java.util.Scanner;
public class Question1 {
public static void main (String[]args){
String major;
Scanner read = new Scanner (System.in);
System.out.print("Enter character : " );
major=read.next();
}
}
public static void mn(){ //method
if (major==M){
System.out.println("Mathematic");
}
else if (major==C){
System.out.println("Computer Science");
}
else if (major==I){ technology
System.out.println("Information Technology");
}
else {
System.out.println("Invalid Input");
}
}
A couple of things are wrong with your code.
Your method mn lies outside of your class. This is invalid.
Strings should be compared with equals
Your method doesn't take any arguments but requires one in this case.
M, C and I need to be String literals, otherwise Java can interpret them as something different.
You actually need to call the method mn to see its output.
So all in all, your code should look like this
import java.util.Scanner;
public class Question1 {
public static void main (String[]args){
String major;
Scanner read = new Scanner(System.in);
System.out.print("Enter character : " );
major=read.nextLine(); // better nextLine, because otherwise the press of "Enter" will not be registered.
mn(major);
}
public static void mn(String major){ //method
if (major.equals("M")){
System.out.println("Mathematic");
}
else if (major.equals("C")){
System.out.println("Computer Science");
}
else if (major.equals("I")){
System.out.println("Information Technology");
}
else {
System.out.println("Invalid Input");
}
}
}
You don't have any calls to mn() in your main function, so the code inside the function won't run. Add the following line to the end of your main function to make the mn() function run, and add "String major" inside the parenthesis of your mn() function declaration:
mn(major);
I hope this helps!

Don't know why my while loop doesn't work (Java) ..? [closed]

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
The purpose of my code is to enter a pin, and it'll check if it's right or not. If it isn't, the question will loop.
For some reason, my code doesn't loop properly, and a lot of the code is underlined. Specifically the while loop itself and the second JOptionPane
// package loop;
import javax.swing.JOptionPane;
public class loop {
public static void main(String[] args) {
int correctPin = 3333;
int count = 0;
String maybePin = JOptionPane.showInputDialog("Please enter the PIN");
int sMaybePin = Integer.parseInt(maybePin);
while(correctPin != sMaybePin);{
maybePin = JOptionPane.showInputDialog("Please enter the PIN");
count = count-1;
}
JOptionPane.showMessageDialog(null, count);
}
}
while(correctPin != sMaybePin); <--
Look at that ; that terminates the loop right there. You need to remove that.
You never update sMabyPin which is the variable you are checking against. If you do what #John and #ANS suggested you'll be stuck in an infinite loop.
Remove the ; after the while statement and correct set the value of the variable sMaybePin to the input vlaue and ot works
public static void main(String[] args) {
int correctPin = 3333;
int count = 0;
String maybePin = JOptionPane.showInputDialog("Please enter the PIN");
int sMaybePin = Integer.parseInt(maybePin);
while(correctPin != sMaybePin){
sMaybePin = Integer.parseInt(JOptionPane.showInputDialog("Please enter the PIN"));
count = count-1;
}
JOptionPane.showMessageDialog(null, count);
}

If statement isn't taking my string values and evaluating them as a boolean (java beginner problems) [closed]

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 6 years ago.
Improve this question
//Program always prints the line written in the if statement.
//Also, eclipse returns an error every time I try to add an else statement
import java.util.Scanner;
import java.util.Arrays;
public class Practice {
public static void main(String[] args)
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of artists you would like to search: ");
int number = input.nextInt();
String junk = input.nextLine();
String []artist = new String[number];
for(int i=0; i < number ; i++)
{
artist[i]= input.nextLine();
}
System.out.println("Here is the list of artists you searched for: " + Arrays.toString(artist) + ". Is this correct?");
String check = input.nextLine();
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false); //this continually returns both print statements in and out of the if statement even if I input something other than yes or y and I have no idea why
{
System.out.println("Cool! Enjoy your search!"); //this always prints no matter what
}
System.out.println("Please try again! Sorry for the inconvenience!"); //won't let me add an else statement
You have a dangling ; at the end of your condition
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false) // ; was here
{
}
Remove it. This is known as an empty statement. You could rewrite it as
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false)
;
{
System.out.println("Cool! Enjoy your search!"); //this always prints no matter what
}
Since a block { /* ... */ } is valid code, it will get executed no matter what.
Your "if-then" statement is being treated as a regular end statement since there is a semicolon ";" added before the scope of your "if-then" block "{ }" begins.
Oracle shows that before you start writing the body of the statement, use brackets
int choice = input.nextInt(); //How does the steak taste?
if(choice == 1) {
String Steak = "Amazing"
System.out.println(choice);
}
The variable "choice" ends with a semicolon and is now declared with a value that the user will input. Since the if-then statement is not finished after the header, brackets containing the body with further statements (each ending with a semicolon) can be executed.

Categories