0

How can i make this better

So im learning Java. I try to think of some code, to do to help me implement the knowlege im getting. I wrote this code (in Intellij, and its working). But i would like to make it better/shorter: 1. I want to make a class "Answer" that will help me shorten this code (so i don have to repeat: Scanner scanner = new Scanner(System.in); String question = scanner.nextLine(); question = question.toLowerCase(); if (question.equals("no")) { System.out.println(notduck); 2. Could i use boolean for the questions? 3. for now if somebody will write something else then "no" it will work as if the answer was "yes" This is the code: import java.util.Scanner; public class Main { public static void main(String[] args) { String notduck = "It is not a Duck"; System.out.println("Please answer with: yes or no"); System.out.println("Does it quack like a duck"); Scanner scanner = new Scanner(System.in); String question = scanner.nextLine(); question = question.toLowerCase(); if (question.equals("no")) { System.out.println(notduck); } else { System.out.println("Does it swim like a duck?"); Scanner scanner1 = new Scanner(System.in); String question2 = scanner1.nextLine(); question2 = question2.toLowerCase(); if (question2.equals("no")) { System.out.println(notduck); } else { System.out.println("Does it looks like a duck?"); Scanner scanner2 = new Scanner(System.in); String question3 = scanner2.nextLine(); question3 = question3.toLowerCase(); if (question3.equals("no")) { System.out.println(notduck); } else { System.out.println("It is a duck!"); } } } } }

14th May 2022, 2:29 PM
Grzegorz Cymerman
Grzegorz Cymerman - avatar
2 Answers
+ 1
It can be shorten. Learn about loops in next lessons.. There is no need multiple scanners. You can work with single scanner object. edit: 2,3 not understandable. can you elaborate more..!
14th May 2022, 2:43 PM
Jayakrishna šŸ‡®šŸ‡³
0
methods can help import java.util.Scanner; public class DuckAsker { static Scanner scanner = new Scanner(System.in); static boolean likeDuck( String act) { return question( "Does it "+ act +" like a duck ?"); } static boolean question( String text) { System.out.println( text); return answer(); } static boolean answer() { return scanner.nextLine() .toLowerCase() .equals("yes"); } public static void main(String[] args) { // usage if ( likeDuck( "quack") )
16th May 2022, 1:59 AM
zemiak