when i type what is stored inside the string variables b and p, it does not respond until I have clicked the enter key several times.
After this point the program only prints out what is inside the else statement.
The only string variable that the program is responding to is j.
The code:
package legit;
import java.util.Scanner;
public class Gamee {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String j = "good, how are you?";
String b = "good";
String p = "bad";
System.out.println("Hello, my name is Julie the Robot");
System.out.println("How Are You?");
if (j.equals(sc.nextLine())) {
System.out.println("Im Doing Great!");
}else if (b.equals(sc.nextLine())) {
System.out.println("Thats Great! :)");
}else if (p.equals(sc.nextLine())){
System.out.println("Thats not good");
}else {
System.out.println("I see...");
}
Do you know that every time you use sc.nextLine() you are asking user for new input?
Try maybe using it once before your ifs and store received input in value, then use that value in conditions.
Related
I am supposed to make a program that asks users for a list of input. Then, from that list, my program is supposed to pick out the third answer and then print it out. It sounds really simple, but how do I assign numbers to each of the user inputs? Do I even do that? I am a beginner, and thank you so much for your help!
This is the code I have so far:
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if(ans.equals(""))
{
break;
}
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}
You can strore the third input in a variable you initialized bevor the loop.
if there is no third input it prints: ""
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int index = 0;
String input3 = "";
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if (index == 2) {
input3 = ans;
}
if(ans.equals("")){
break;
}
index++;
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}
I amm at my very beginning at java and just wanted to ask.
I want to ask the user to put Yes/No to a question and proceed to the next question. How do I do it?
import java.util.Scanner;
public class sff {
public static void main (String args[]) {
System.out.println("Hello There! We want to ask you some questions! but first: ");
System.out.print("Enter your age: ");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int age = num;
if( age == 12){
System.out.println("Hello Dan, I know you very well! ");
}
{
System.out.println("First question: ");
System.out.println("Do you exercise?(Yes/No) ");
// how do i proceed from here??
Use Scanner and get next line, then check if that line is yes or no then handle respectively.
In the example below, I used a while loop to keep asking them to input yes or no in case they enter something different like "maybe".
For example:
Scanner in = new Scanner(System.in);
// Loop until they enter either yes or no.
while(true){
String line = in.nextLine();
// Use this to check if it is yes or no
if(line.equalsIgnoreCase("yes")){
// Process yes
break;
}else if(line.equalsIgnoreCase("no")){
// Process no
break;
}else{
// Tell them to enter yes or no since they entered something else.
}
}
Are you looking for something like this?
//import to use the Scanner
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
//get the user input and store it as a String
String exerciseQuestion = in.nextLine();
//check what the user said.
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do you code when he exercises
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}
System.out.println("Ask your next question so on....");
}//main
}//class
If you want to deal with answers other than yes/no you can use this code:
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
String exerciseQuestion;
while (true){
//get the user input
exerciseQuestion = in.nextLine();
//check if user input is yes or no
if((exerciseQuestion.equalsIgnoreCase("yes")) ||
exerciseQuestion.equalsIgnoreCase("no"))
//if yes break and continue with your code
break;
else
//else loop back to get user input until answer is yes/no
System.out.println("Please answer with yes or no only");
}//while . i.e answer not yes or no
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do your code
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}//else
}//main
}//class
public static int atk = 5;
public static void main(String[] args){
System.out.println("DUNGEONS AND DWAGONS");
Scanner scan = new Scanner(System.in);
help();
String input = scan.next();
// when someone types help first it works, but when they type stats after it shows what would happen if someone typed help.
while(true){
if (input.equals("help")){
help();
scan.next();
}else if(input.equals("stats")){
stats();
scan.next();
}
}
}
static void help() {
System.out.println("type n,s,e,w to move in a direction");
System.out.println("type stats to see your stats");
System.out.println("type look and then a direction n,e,s,w see the sights");
System.out.println("if you wish to see this again type help");
}
static void stats(){
System.out.println("Health " + health);
System.out.println("Armour " + armour);
System.out.println("Attack " + atk);
}
}
// I have tried every thing and if you type anything after the first thig typed it will execute the same thing over and over again.
Just move scan.next outside of if/else and assign it to input variable like:
if (..) {
help();
} else {
stats();
}
input = scan.next();
And expect exit so you can come out of while loop and terminate your program gracefully.
Over here, I have a robot application which consists of mainly three user prompts. Right after the third prompt, and it has to loop back to the first one and this goes on until when the user types QUIT which will then display all the details from the vector elements. Right now, I'm having problem with the application as when I put the first prompt in the while-loop and when the application starts, nothing happens unless I put it out of the loop but this will not be looping back. So could someone give me some guidance here as I'm a newbie in programming. Thanks so much!
class KillerRobot {
private String name;
private String mainWeapon;
private int numberOfKills;
KillerRobot()
{
}
public String getName()
{
return name;
}
public String getMainWeapon()
{
return mainWeapon;
}
public int getNumberOfKills()
{
return numberOfKills;
}
public String toString()
{
return name + " used a " + mainWeapon + " to destroy " + numberOfKills + " enemies ";
}
public void setName(String a)
{
name = a;
}
public void setMainWeapon(String b)
{
mainWeapon = b;
}
public void setNumberOfKills(int c)
{
numberOfKills = c;
}
}
Main method class:
import java.util.Scanner;
import java.util.Vector;
class TestVector2 {
public static void main(String [] args)
{
String prompt = "Please enter the name of the Killer Robot or QUIT to finish";
String prompt2 = "Please enter the main weapon for the robot";
String prompt3 = "Please enter the number of kills for this robot";
System.out.println(prompt); //The first prompt and has to loop back unless QUIT from user
Scanner userInput = new Scanner(System.in);
Vector <KillerRobot> robotDetails = new Vector <KillerRobot>(); //adding object to Vector elements
do {
System.out.println(prompt); //The first prompt and has to loop back unless QUIT from user
robot = new KillerRobot();
String a = userInput.next();
robot.setName(a);
System.out.println(prompt2);
String b = userInput.next();
robot.setMainWeapon(b);
System.out.println(prompt3);
int c = userInput.nextInt();
robot.setNumberOfKills(c);
robotDetails.add(robot);
System.out.println(robot);
} while (!userInput.nextLine().equals("QUIT"));
}
}
The logic of your program is a bit off, and this is giving you problems. You want to keep looping over all three prompts until the user types 'QUIT'. This means that the first prompt must be inside the loop. So the trick is to make your while-condition different. Instead of checking whether there is any input (with hasNext()), check whether the last input was 'QUIT'.
One way to do that is to set a simple boolean flag outside the loop and then use that as your while-condition, like so:
boolean quit = false;
while(!quit) {
System.out.println(prompt);
String a = userInput.next();
quit = "QUIT".equals(a);
...
}
This is actually still not ideal, since this will continue showing all three prompts, even when the user types 'QUIT' on the first one. I assume you want to jump out of the loop immediately when that happens, so you might consider making an infinite loop (using while(true), for example), and just immediately jumping out of the loop (with a break) when the user enters the quit command.
This should in line with what you want. There are a few changes - one your code has the prompt displayed twice, second you want them to be able to QUIT before having any robots so a do-while loop would be a little inconvenient, and lastly at the end of the loop I use prompt1 again and if they quit, print all the robots if there are any instead of printing them out in each iteration of the loop (because at that point if you just print it to the console you aren't using the vector at all.
public static void main(String[] args) {
String prompt1 = "Please enter the name of the Killer Robot or enter QUIT to exit.";
String prompt2 = "Please enter the main weapon for the robot";
String prompt3 = "Please enter the number of kills for this robot";
Scanner userInput = new Scanner(System.in);
Vector <KillerRobot> robotDetails = new Vector <KillerRobot>();
KillerRobot robot;
//prime the loop
System.out.println(prompt1);
String userEntry = userInput.next();
while(!userEntry.equals("QUIT")){
robot = new KillerRobot();
robot.setName(userEntry);
System.out.println(prompt2);
String b = userInput.next();
robot.setMainWeapon(b);
System.out.println(prompt3);
int c = userInput.nextInt();
robot.setNumberOfKills(c);
robotDetails.add(robot);
//verify repeat
System.out.println(prompt1);
userEntry = userInput.next();
}
if(robotDetails.size() < 1){
System.out.println("No robots");
} else {
for(KillerRobot i : robotDetails){
System.out.println(i);
}
}
System.out.println("done");
}
import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}