short way to ask for confirmation Java - java

I'm trying to find a way to ask the user a yes/no question that validates that the input is only yes (y/Y) or no (n/N). I'm trying to cut down on variables, while still keeping it readable. So far this is what I've come up with:
import java.util.Scanner;
public class InputValidation
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String answer;
do
{
System.out.print("Do you wish to proceed? (Y/N): ");
answer = input.next().trim().toUpperCase();
yesAnswer = answer.equals("Y");
} while (answer.matches("[YN]"));
if (yesAnswer)
{
// Do something
}
else
{
// Do something else
}
}
}
I'm not necessarily looking for the least amount of characters; more something that's short and flexible. Any ideas?

Depending on what you want to achieve, I would probably simply evaluate the input directly, before determing the actual result, for example
do {
System.out.print("Do you wish to proceed? (Y/N): ");
answer = input.next().trim().toUpperCase();
} while (!answer.matches("[YN]"));
boolean yesAnswer = answer.equalsIgnoreCase("Y");
This basically waits until the answer matches Y, N, y, n before determine yesAnswer. The next thing I might do is wrap it in method...
if (askYesNo("Do you wish to proceed? (Y/N): ")) {...
You could then go onto providing optional exit conditions to the method..
askYesNo("Delete all files [Ok/Cancel]", "(ok)?", "(cancel)?")
For example...
public class YesNo {
public static void main(String[] args) {
if (askYesNo("Do you wish to proceed? (Y/N): ")) {
System.out.println("Okay...");
}
if (askYesNo("Delete all Files? (Okay/Cancel): ", "okay", "cancel")) {
System.out.println("Make it so");
}
}
public static boolean askYesNo(String question) {
return askYesNo(question, "[Y]", "[N]");
}
public static boolean askYesNo(String question, String positive, String negative) {
Scanner input = new Scanner(System.in);
// Convert everything to upper case for simplicity...
positive = postive.toUpperCase();
negative = negative.toUpperCase();
String answer;
do {
System.out.print(question);
answer = input.next().trim().toUpperCase();
} while (!answer.matches(positive) && !answer.matches(negative));
// Assess if we match a positive response
return answer.matches(positive);
}
}

Related

Boolean method with an incorrect input

I'm a bit stuck on an exercice I have to make and I can't figure out the best way to do it.
I have to make a method that asks a question and expects Y or N. So I thought I would make a boolean method to return true or false, but the problem is that it would also return false if the user puts something other than Y or N. If I'm not mistaken, a boolean method cannot return null.
I'm very new to java and I'm not very far in my course so this problem will probably have a very simple solution. I also tried looking for an answer but didn't seem to find what I was looking for.
This is what I have with the boolean method but i'm not quite happy with it:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
if (reponse.equalsIgnoreCase("Y")) {
return true;
}
else if (reponse.equalsIgnoreCase("N")) {
return false;
}
else {
return false;
}
}
You need only one condition equalsIgnoreCase("Y"), result of its evaluation is basically the return value. All the if-statements in your code are redundant.
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
return reponse.equalsIgnoreCase("Y"));
}
Going by your comment you want your program to ask for input again if the input is neither "y" nor "n". You can achieve that behavior by adding an extra loop:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String response = sc.next();
while(!response.equalsIgnoreCase("Y") && !response.equalsIgnoreCase("N")) {
// loop as long as input is neither "y" nor "n" (ignoring case)
System.out.println("Please enter 'y' or 'n'");
reponse = sc.next();
}
// if the loop is done input has to be either "y" or "n" at this point
return reponse.equalsIgnoreCase("y");
}
The problem is at the end you are explicitly telling java to return false when neither a Y or N is entered. I would try putting in another else statement to have the user re-enter the data or just notify them that they have entered the wrong value.
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
while(!response.equalsIgnoreCase("Y") ||!response.equalsIgnoreCase("N"){
#Do something here until
the user inputs the correct value.
}
}

Java if (Yes or No Statement)

Hey there I got into some trouble with my java Code.
I try to code a bit around with java for a few hours and I dont know much thats why im asking. I learn best by trying but I get into so many problems.
So: I want the scanner to scan the next Statement and if its "ja" it should do the if thing etc.
The problem is, when i try to compile it it has an error with the = s.nextInt thing. In the console it says: "cannot find symbole". I tried so many things I dont know what to do. Allready tried so much.
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = s.NextInt();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
thanks in advance.
EDIT: Problem solved. Thank you for every awnser. I try my best to Tag my posts better and to format my code better
Here:
String a = s.NextInt();
You want a to be String (which makes sense, as you want to compare it against other Strings later on); so you better use:
String a = s.nextLine();
instead!
The other method a) does not exist and b) nextInt() ... returns a number, not a string
I can see two errors, firstly you are taking a string input from the command line user so your scanner must be "scanner.nextLine()" which takes a string, as it stands you are expecting an integer value.
Second your "s.scanner" is not calling anything, you have declared your scanner with the name "scan", so you need to change that to "scan".
import java.util.Scanner;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("A flag has more than one colour?");
String input = scan.nextLine();
if (input.equals("yes")) {
System.out.println("well done");
} else {
System.out.println("wrong answer");
}
}
Try:
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = scan.nextLine();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
You have got a compilation error that should be
String a = scan.next();
Since scan is your scanner object where you are using String a = s.NextInt(); which is not at all an object of scanner.
Two issues, one is a is a String not an int and the second is Scanner.nextLine() (or nextInt() or next()). And, the local reference is scan (not s). Like,
String a = scan.nextLine();
You can use like this.
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
refrence: http://www.javatpoint.com/Scanner-class

Jumping to lines in Java

I have just now started learning Java and one of the differences I noticed from C++ and VB is that Java has no goto statements, which I tend to use a lot while programming.
Is there any way I could jump between lines using another statement? I tried to use break and continue but to no avail (I might be doing something wrong).
Here is the code with goto statements and how I want it to operate:
public class HelloWorld {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
jump1:
System.out.print("What do you want to calculate? ");
String method = sc.nextLine();
if (method.equals("tax")) tax();
else {
System.out.print("Please input a valid method. \n\n");
goto jump1;
}
}
What is a good replacement for the goto commands?
A while loop in this instance.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html
For this (very specific) instance you could put
System.out.print("What do you want to calculate? ");
String method = sc.nextLine();
while (!method.equals("tax"))
{
System.out.print("Please input a valid method. \n\n");
method = sc.nextLine();
}
tax();
Obviously this only works if your only expected correct input is "tax", but it's a structure to build on.
You would want to put your if-statement in a while-loop by using the hasNextLine() function, which will loop until theres no more lines left to iterate over:
while(sc.hasNextLine()) {
// Your code..
}
For more info regarding the function check Scanner::hasNextLine documentation.
You should avoid "goto" statements in all languages, according to the rules of "structured programming", instead using if-then-else or do or while or for loops to control program flow.
Java DOES have a sort of "goto" statement that you COULD use to only slightly modify your code, but consider the while loop below and the break statement, which jumps out of the loop.
public static void main(String[] args) {
String method = "";
while(! method.equals("tax")){
System.out.print("What do you want to calculate? ");
method = sc.nextLine();
if(method.equals("tax"))
break;
System.out.print("Please input a valid method. \n\n");
}
tax();
}
The break statement enables your "Please ... valid" statement to display. You could also use this:
public static void main(String[] args) {
String method = "";
while(! method.equals("tax")){
System.out.print("What do you want to calculate? ");
method = sc.nextLine();
}
tax();
}
I also kind of like this:
public static void main(String[] args) {
String method = "";
while(1==1){
System.out.print("What do you want to calculate? ");
method = sc.nextLine();
if(method.equals("tax")
break;
System.out.print("Please input a valid method. \n\n");
}
tax();
}
You might go to the Java tutorials; they're good.
In this case you can use a do-while-loop, which will do the statement first and will only repeat if the statement is true:
public class HelloWorld {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
boolean right = true;
do {
if(right)
System.out.print("What do you want to calculate? ");
else
System.out.print("Please input a valid method. \n\n");
String method = sc.nextLine();
boolean right = false;
} while (!method.equals("tax"));
tax();
}
}

Scanning Basics Java

So the loop works but I have to press enter twice for it to print out the next input, I know it's with my loop and I know it's because the new input is set after the method scanz but I can't put it before/ eliminate it outside the loop because then the creation of the object Scanning doesn't work. Help is appreciated!
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to terminate");
Scanner keyboard = new Scanner(System.in);
String scannedString=keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
do
{
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
scannedString=keyboard.nextLine();
}
while(!keyboard.nextLine().equals("."));
keyboard.close();
}
}
Change your loop to the following pattern:
String scannedString = keyboard.nextLine();
do {
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
} while (!(scannedString = keyboard.nextLine()).equals("."));
This way condition check is done together with reading a new line. There is even more readable approach available:
String scannedString = null;
while (!(scannedString = keyboard.nextLine()).equals(".")) {
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
}

Scanner looping headache

I have a homework assignment which requires input from the user and stores it in various data structures (arrays of linked-lists, stacks, etc.). However, I've been writing the main class of my previous homework assignments and this one in a very similar fashion. I have a very tiny main method. All the main method does is instantiate a new object which I don't want to be destroyed and then loop through the program forever until the user chooses otherwise. I then have a menu() method which prints a list of selections and reads the user's selection. And then from there, I pass that selection to another method which interprets the selection and performs accordingly.
The problem I have been having in the past assignments and now I've never really gotten a good answer for. The problem seems to lie with my menu() method and more specifically, the Scanner object. There always seems to be some junk left in the stream after I call the nextLine() method on a scanner object. So the next time the menu() method is called, it reads in that junk and loops though the rest of the program with that junk until menu() is called a third time. In the past, I would remedy this by calling the next() method right after I received my input and ignoring it. However, I seem to be having issues with that now as well.
In this program in particular, I have a method which request's a user enter a city name. Now, city names can be more than one word (Palm City, West Palm Beach, Satellite Beach, New York, etc.). Now, when the scanner reads in one of those multi-word cities, it does the same thing as before, reads in some junk the next time the menu() method is called and goes though the whole program with it until menu() is called again. In this case, it prints an string "Invalid Selection" and then prints the menu again. I can't for the life of me figure out what's going on. any help would be appreciated.
import java.util.Scanner;
public class CSAir
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
CityList flightLog = new CityList();
boolean loop = true;
while(loop)
{
loop = actions(menu(),flightLog);
}
}
private static String menu()
{
System.out.print("Please Make a Selection\n" +
"I) Insert a city\n" +
"A)Add a flight path (One Way)\n" +
"R) Request a flight\n" +
"L) Load from a text file\n" +
"Q) Quit\n" +
"\nSelection: ");
String in = input.next();
//input.next();
System.out.println();
return in;
}
private static boolean actions(String selection, CityList flightLog)
{
if(selection.equalsIgnoreCase("I"))
{
insert(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("A"))
{
add(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("R"))
{
request(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("L"))
{
return true;
}
else if(selection.equalsIgnoreCase("Q")) return false;
else
{
System.out.println("Invalid Selection!\n");
return true;
}
}
private static void request(CityList flightLog)
{
System.out.print("Origin: ");
String origin = input.nextLine();
System.out.print("\nDestination: ");
try
{
flightLog.isPath(origin, input.next());
}
catch (AllDestinationsVisitedException e)
{
e.getMessage();
}
}
private static void add(CityList flightLog)
{
System.out.print("Origin: ");
String origin = input.nextLine();
System.out.print("\nDestination: ");
flightLog.addPath(origin, input.next());
}
private static void insert(CityList flightLog)
{
System.out.print("Enter a City: ");
try
{
flightLog.addCity(input.next());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println();
}
}
Default Deliminator for scanner is white space. So when you enter New York since it has white space now scanner treats it as two tokens if you call next().
A better option would be to use nextLine() method for reading such values.

Categories