I'm making an application that quizzes you on politics or astronomy.
My problem is that when you say "politics" or you say "astronomy", it will ask you again 2 more times for your input, before giving the desired output of "test".
Here's the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
do {
if (getAnswer().equalsIgnoreCase("neither")) {
System.out.println("Please enter \'astronomy\' or \'politics\'.");
}
getAnswer();
}
while(getAnswer().equalsIgnoreCase("neither"));
System.out.println("test");
}
public static String getAnswer() {
Scanner quizType = new Scanner(System.in);
System.out.println("Would you like to be quizzed on politics or astronomy?");
String typeAnswer = quizType.next();
if (typeAnswer.equalsIgnoreCase("politics")) {
return "politics";
}
else if (typeAnswer.equalsIgnoreCase("astronomy")) {
return "astronomy";
}
else {
return "neither";
}
}
}
Any ideas?
Thanks
There no need to getAnswer() 3 times, just getAnswer() into a String variable and you are good to go.
Like this:
public static void main(String[] args) {
String answer = "";
do {
answer = getAnswer();
if (answer.equalsIgnoreCase("neither")) {
System.out.println("Please enter \'astronomy\' or \'politics\'.");
}
} while (answer.equalsIgnoreCase("neither"));
System.out.println("test");
}
public static String getAnswer() {
Scanner quizType = new Scanner(System.in);
System.out.println("Would you like to be quizzed on politics or astronomy?");
String typeAnswer = quizType.next();
if (typeAnswer.equalsIgnoreCase("politics")) {
return "politics";
} else if (typeAnswer.equalsIgnoreCase("astronomy")) {
return "astronomy";
} else {
return "neither";
}
}
If you're learning do-while, then you only need to prompt inside your do. Currently you're calling getAnswer three times, which forces the repeated prompt.
Here is a quick way to solve it using do-while
public static void main(String[] args) {
List<String> validAnswers = Arrays.asList("neither","politics","astronomy");
String answer;
do {
answer = promptForAnswer();
} while(!validAnswers.contains(answer));
System.out.println("test");
}
public static String promptForAnswer() {
System.out.println("Would you like to be quizzed on politics or astronomy?");
return new Scanner(System.in).next();
}
Or you can go with the while loop...
public static void main(String[] args) {
List<String> validAnswers = Arrays.asList("neither","politics","astronomy");
while(!validAnswers.contains(promptForAnswer())) {
System.out.println("That was not a valid response, try again!");
}
System.out.println("test");
}
public static String promptForAnswer() {
System.out.println("Would you like to be quizzed on politics or astronomy?");
return new Scanner(System.in).next();
}
Related
i am new to java and currently trying to learn it!
I have a question about methods, here are my code example bellow.
import java.util.*;
public class test
{
public static void main(String[] args)
{
char key;
Scanner info = new Scanner(System.in);
System.out.print("Enter Keyword: ");
key = info.next().charAt(0);
while(key!='W'&&key!='w'&&key!='M'&&key!='m')
{
System.out.println("Invalid Keyword");
System.out.print("Enter Keyword");
key = info.next().charAt(0);
}
System.out.print("Valid key");
}
public static char validKey(char key)
{
///i want the while validation to go here instead of in the main
}
}
As i wrote in the code, is there a way to validate the key in the validKey method instead of in the main?
Is there a way so i dont have to specify between 'w' and 'W' in the while condition?
Sorry if i couldnt explain it well, thanks in advance!
If you want to check is key correctly, you can do something like this:
import java.util.*;
public class test
{
public static void main(String[] args)
{
char key;
Scanner info = new Scanner(System.in);
System.out.print("Enter Keyword: ");
key = info.next().charAt(0);
while(!validKey(key))
{
System.out.println("Invalid Keyword");
System.out.print("Enter Keyword");
key = info.next().charAt(0);
}
System.out.print("Valid key");
}
public static boolean validKey(char key)
{
if(Character.toLowerCase(key)!='w' && Character.toLowerCase(key)!='m') {
return true;
} else {
return false;
}
}
}
It depends. If case size is not important you can try this:
while(Character.toLowerCase(key)!='w' && Character.toLowerCase(key)!='m')
{
...
}
Write back if my answer will be helpfully for you ;)
As I understand, the contentEquals() method only accepts one argument to be compared with.
In the following program, what if I wanted to pass in more?
like:
(1)YES
(2)Yes
(3)Y
(4)y
import java.util.Scanner;
public class ifStatement1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Want some pizza?");
String userInput = input.nextLine();
boolean answer = **userInput.contentEquals("yes");**
if(answer) {
System.out.println("so go take a break from all this code");
}
else {
System.out.println("so keep writing code");
}
}
}
Set.of("YES", "Yes", "Y", "y").contains(userInput)
String.equals would be more normal than using String.contentEquals with a String.
import java.util.Scanner;
import java.util.Set;
public class example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextLine();
boolean answer;
if(Set.of("yes","y").contains(userInput.toLowerCase())){
answer = true;
} else {
answer = false;
}
System.out.print(answer);
}
}
I guess my title isn't very clear and needs a code example so here you go:
public class ATM {
public static void main(String[] args) {
Keypad K=new Keypad();
K.mypin(pin);
}
}
That is the main method, now here is a method in another class:
public class Keypad{
public void mypin(int pin) {
System.out.print("Please enter your pin");
pin=scan.nextInt();
System.out.print(pin);
}
}
How to include pin=scan.nextInt(); in my main method and make this work normally?
You might ask me why I want it this way and it is just because that is what I was asked to do.
If I understood you correctly, you want something along those lines :
public class ATM {
public static void main(String[] args) {
System.out.print("Please enter your pin");
Scanner sc = new Scanner(System.in);
Keypad K=new Keypad();
K.mypin(sc.nextInt());
}
}
public class Keypad{
public void mypin(int pin) {
System.out.print(pin);
}
}
You can use Scanner class with input stream System.in.
It is ATM class:
package user.input;
public class ATM {
public static void main(String[] args) {
Keypad keypad = new Keypad();
try {
int userPin = keypad.enterPin();
System.out.printf("User Pin: %s", userPin);
} catch (Exception e) {
System.err.println("Occured error while entering user's PIN.");
e.printStackTrace();
}
}
}
It is Keypad class:
package user.input;
import java.util.Scanner;
public class Keypad {
public int enterPin() throws Exception {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.print("Please enter your pin: ");
int inputNum = scanner.nextInt(); // Read user input
return inputNum;
} catch (Exception e) {
throw e;
} finally {
if (scanner != null) {
scanner.close();
}
}
}
}
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
String q = null, s = "nul";
userName(q);
userGender(s);
print(userName(q));
print(userGender(s)); // how to achieve something like this?
}
public static void userName(String x) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String n = sc.nextLine();
}
public static void userGender(String y) {
Scanner sd = new Scanner(System.in);
System.out.print("Enter Gender: ");
String v = sd.next().toString();
}
public static void print(String a) {
System.out.println(a);
}
So I was trying to make it so that a method would be used to print another method after they were done executing but I couldn't get the desired result and it gave an error.
The method print works fine, it takes a String and return nothing
public static void print(String a)
{
System.out.println(a);
}
However, your method userGender and userName returns nothing, so when you are feeding print with a method that isn't returning a string, it will produce an compile-time error. You want to do something similar to:
public static String userGender(String y){
Scanner sd = new Scanner(System.in);
System.out.print("Enter Gender: ");
return sd.next().toString();
}
I haven't tested it, as your logic is unclear to me, but this is probably why your IDE is complaining.
Your method needs to return something. You are declaring your method like this: public static void userGender(String y) the void means that your method won't return anything. But since you want that the method returns a String you need to tell this in the method signature.
Your code could look like this:
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
print(userName());
print(userGender());
}
public static String userName() {
try(Scanner sc = new Scanner(System.in)){ // this is try resource see which will close your resource once you are done in the try block see https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
System.out.print("Enter name: ");
return sc.next();
}
}
public static String userGender() {
try(Scanner sc = new Scanner(System.in)) {
System.out.print("Enter Gender: ");
return sc.next();
}
}
public static void print(String a) {
System.out.println(a);
}
You don't need to use toString() since the next returns already a String. Also you can use the same variable name in different methods. And really important you need to close the Scanner again, otherwise it will consume endless resources.
Like #reebow and #Kerry Gougeon both pointed out that your method is looking to return something so you make it public static String userName() or public static String userName(String s).
If you're wanting to user Scanner then you're going to have to declare Scanner globally, otherwise it will throw a NoSuchElementExcpetion
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
print(userName());
print(userGender());
}
public static String userName() {
System.out.print("Enter name: ");
return sc.next();
}
public static String userGender() {
System.out.print("Enter Gender: ");
return sc.next();
}
public static void print(String a) {
System.out.println(a);
}
If you're not using Scanner then you can just return the String that you passed to the method.
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
String a = null, b ="nul";
print(userName(a));
print(userGender(b));
}
public static String userName(String a) {
System.out.print("Enter name: ");
return a;
}
public static String userGender(String b) {
System.out.print("Enter Gender: ");
return b;
}
public static void print(String a) {
System.out.println(a);
}
I need to know how to fetch the input for the operator for this simple program I am making that does this; the person enters a number, and if it's greater than 10, it displays the message "it worked". Where it says "NEED INPUT" is where I need the system scanner entry to go.
Operators class:
class Classes {
private int Numbers;
public Classes() {}
Classes(String namez) {
Numbers = Numbers;
}
public int getNumbers() {
return Numbers;
}
public void setNumbers(int numberz) {
if((Integer.parseInt(INPUT HERE.getText().toString()) )<=10) {
System.out.print("It worked.");
}
}
}
Main class:
import java.util.Scanner;
public class OneTwoThree {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
Classes.Numbers(keyboard.nextLine());
}
}
package mavens.dais.test;
public class ClassesTest {
private int Numbers;
public ClassesTest() {}
ClassesTest(String namez) {
Numbers = Integer.parseInt(namez);
}
public int getNumbers() {
return Numbers;
}
public void setNumbers(int numberz) {
if(numberz > 10){
System.out.print("It is worked.");
}else{
System.out.print("It is not worked.");
}
}
}
package mavens.dais.test;
import java.util.Scanner;
public class OneTwoThre {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
new ClassesTest().setNumbers(Integer.parseInt(keyboard.nextLine()));
}
}
Firstly
Classes.Numbers(keyboard.nextLine());
this should be replaced by Classes(keyboard.nextLine()); to begin with, in your class named OneTwoThree
Secondly
Classes(String namez) {
Numbers = Numbers;
}
this seems pretty much wrong.
Should be replaced by something like
Classes(String namez) {
Numbers = Integer.parseInt(namez); //if you are entering integers only through keyboard
}
As far as I could understand your question,
you can go like this then,
Classes(String namez) {
Numbers = Integer.parseInt(namez); //if you are entering integers only through keyboard
performOperation(Numbers);// call a method you want,pass number as arg
}
public static void performOperation(int num){
if(Numbers >10){
//do stuff
}
else{
//else part
}
}
}
Also ,just as a good practice you should name your variable Numbers to number.
I Hope it helped.
You just need to pass the String.
public static void testScanner() {
try (Scanner keyboard = new Scanner(System.in);) {
System.out.print("Enter a number: ");
while (true) {
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("exit")) {
break;
}
Handler.handleInput(input);
}
System.out.println("Done.");
}
}
static class Handler {
public Handler() {
}
public static void handleInput(String input) {
try {
int x = Integer.parseInt(input);
if (x <= 10) {
System.out.println("It worked!");
} else {
System.out.println("Aw, Id didn't work.");
}
} catch (Exception ex) {
System.out.println("Hey, watch it buddy. Don't throw any letters in there, I don't like them.");
}
}
}