Clearing the console screen to accept a new value from the user - java

Hi please in a switch case program that I am developing, I am using a do..while loop to handle the case when a user enters a value that does not meet the condition but got stuck with what I should put in the "while" brackets as an error is shown on the "while" line..
package assignment;
import java.util.*;
public class Assignment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("1)Monday\n2)Tuesday\n3)Wednesday\n4)Thursday\n5)Friday\n6)Saturday\n7)Sunday");
System.out.println("");
int day = input.nextInt();
System.out.println(" ");
do {
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Oh oh, that's not an accepted number, kindly try again");
break;
}
for (int clear = 0; clear < 1000; clear++) {
System.out.println("\b");
}
} while (!(day.equals("1") || day.equals("2") || day.equals("3") || day.equals("4") || day.equals("5") || day.equals("6") || day.equals("7")));
}
}

Instead of checking day as a String, simply check it as an integer which it already is. No need to allocate extra memory when creating a new String to check with an integer.
When you begin your while loop, it seems that there is no way to check for new input. How would you be able to get new input EACH time in your loop?
There is no reliable way to clear your console cross platform as depending on the IDE you are using or which terminal UNIX or PowerShell or CMD. Take a look at this answer Java: Clear the console
Since this seems like a homework assignment, I suggest that you think about how your while loop conditions could be simplified.
Hint: Is there any way to check a range of numbers? What if you had to check 1000 different numbers, would you check each number with OR conditions?

Related

button action leading to seemingly random action performed [duplicate]

I have this code with the switch statement which I got from this post, and it works absolutely fine:
String getOrdinal(final int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
But if I change it to something like the following, it breaks, as all the cases besides case 1 gets executed:
static String getOrdinal(final int day) {
StringBuilder ordinalBuilder = new StringBuilder();
ordinalBuilder.append("<sup>");
if (day >= 11 && day <= 13) {
ordinalBuilder.append("th") ;
}
switch (day % 10) {
case 1: ordinalBuilder.append("st");
case 2: ordinalBuilder.append("nd");
case 3: ordinalBuilder.append("rd");
default: ordinalBuilder.append("th");
}
ordinalBuilder.append("</sup>");
return ordinalBuilder.toString();
}
This prints 2<sup>ndrdth</sup> when I pass in 2. I tried changing the builder to buffer but I got the same response... Could this be a bug or am I making some mistake?
It's a bug in your code. You forgot to put in a break after each case:
switch (day % 10) {
case 1: ordinalBuilder.append("st"); break;
case 2: ordinalBuilder.append("nd"); break;
case 3: ordinalBuilder.append("rd"); break;
default: ordinalBuilder.append("th"); break;
}
I don't see any bug here, at least not in the way the language is working. The behavior of a switch statement, by design, is that it will start executing statements at the case label which matches the argument, and then continue until the end of the block. So
switch (x) {
case 1:
// do thing 1
case 2:
// do thing 2
case 3:
// do thing 3
default:
// do nothing
}
will do both things 2 and 3 if x is 2, and will do things 1, 2, and 3 if x is 1.
To get the behavior you're probably looking for, end each case with a break:
switch (x) {
case 1:
// do thing 1
break;
case 2:
// do thing 2
break;
case 3:
// do thing 3
break;
default:
// do nothing
break;
}
(strictly speaking the break at the very end is unnecessary, but I often put it in out of habit).
The reason you didn't have this problem in the first code example is that return is like a super-break: it has the same effect as break, namely ending execution within the switch block, but it also ends execution of the whole method.
you need to add a 'break' statement in every switch case.
It was worked previously because you made a return from method...
A "break;" statement separates the cases from one another so in order to execute the statements in a specific case just break the case as soon as it comes to an end.
If you don't use break the compiler thinks that it can continue execution of all the cases up to the end of the program.
The first version returns before continuing on in the case statement. The second version needs a break; statement to get the same behavior.
Luckily with the introduction of switch statements on Java 12 which also introduced
"arrow case" labels that eliminate the need for break statements to
prevent fall through (source).
Therefore the modern version of your code looks like the following:
String getOrdinal(final int day) {
if (day >= 11 && day <= 13) {
return "th";
}
return switch (day % 10) {
case 1 -> "st";
case 2 -> "nd";
case 3 -> "rd";
default -> "th";
};
}
I see this question is over 8 years old, but this answer should help anyone landing on this page.
Firstly lets's understand how switch cases work. In C, C++, Java, JavaScript, and PHP while executing switch statements all the cases following the satisfactory case are executed, unlike in Go where only selected case is executed.
For example:
public class Main
{
public static void main(String[] args) {
int day = 11;
switch (day % 10) {
case 1: System.out.println("st");
case 2: System.out.println("nd");
case 3: System.out.println("rd");
default: System.out.println("th");
}
}
}
Currently, day value is set to 11 and hence very first case satisfy the condition, and hence all below cases would be executed. The output should look like the one below:
st
nd
rd
th
Now let's change day value to 13 resulting in the third case to satisfy the condition and hence below output is obtained:
rd
th
Hence if you want to break the code after first satisfactory case is found then put break; condition in the end. In the code mentioned in the question return; does the job of breaking the code.
Also, most of the novice java programmers believe that SWITCH statements are syntactical sugar to IF statements wherein programmers don't have to repetitively mention conditions. But that's not the case as IF's are meant to exit after the execution of satisfactory condition while SWITCH still continues execution.
Switch cases can be utilized to achieve the purpose like one mentioned in below example:
wherein
for Grade A "Excellent!" should be printed
for Grade B and C "Well done" should be printed
for Grade D "You passed \n Try hard next time" should be printed
for Grade F "Try hard next time" should be printed
and if not a valid case i.e grade is found than "Invalid Grade" should be printed.
public class Test {
public static void main(String args[]) {
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Try hard next time");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Add a break statement at the end of the every line in each case or just use the return statement.

Trying to use a For-Loop with a 'menu'

Beginner here, please be as explanatory as possible!
A course question asked me to create a menu (done).
Have multiple option on the menu give different one-time result (done).
Now it wants me to implement a for, while and do...while loop (CANNOT UNDERSTAND)
I have genuinely tried all of my rudimentary knowledge, including creating and populating an array inside the for loop (which in hindsight was a stupid idea).
public void displayMenu()
{
System.out.println("A. Option #A");
System.out.println("B. Option #B");
System.out.println("C. Option #C");
System.out.println("D. Option #D");
System.out.println("X. Exit!");
System.out.println();
System.out.println("Please enter your choice:");
}
public void start()
{
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();
switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}
public void startFor()
{
/*Each of these methods will modify the original start() method, each
*will add a loop of the specific type so that the menu is displayed
*repeatedly, until the last option is selected. When the last option
*is selected, exit the method (i.e. stop the loop).
*/
}
As you asked for an example with for in the comments.
The point of the exercise seems to be to iterate on the menu until an exit condition is met ("X".equals(input)). That means than between the three conditions in the for statement, that's the only one you need to specify. This is because the general form of a (basic) for statement is
for ( [ForInit] ; [Expression] ; [ForUpdate] )
Where none of those terms between brackets are mandatory, so we can as well get rid of [ForInit] and [ForUpdate] (but keeping the semicolons). This has the effect of not initializing anything with [ForInit] and doing nothing at the end of each iteration of the loop with [ForUpdate], leaving us only checking for the exit condition that is given by the [Expression] expression (when it's evaluated to false, the loop exits).
Notice that the console is declared outside the loop, since it would be wasteful to allocate one at each iteration. And also input, since you need it in the for statement's condition.
Scanner console = new Scanner(System.in);
String input = "";
for (;!"X".equals(input);) { // notice, the first and last part of the for loop are absent
displayMenu();
input = console.nextLine().toUpperCase();
System.out.println();
switch (input) {
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}
You may notice this is a bit awkward, as this is not what you usually use a for loop for.
Anyway, at this point, the while version becomes trivial (while (!"X".equals(input))) and, in this case, the do...while is equivalent as well, (do { ... } while (!"X".equals(input))) as the same condition applies both at the end of the current loop and at the beginning of the next one, and there are no side effects between them.
As an aside, you may notice that while (condition) and for (; condition ;) are functionally equivalent and you may wander why you should use one instead of the other. The answer is readability. It's a lot more clear what you want to do when you do while (condition).
All arguments in for loop is not mandatory.
Define a stopflag and check whether is input is "X" or not.
Whenever input is "X" just change stopFlag or just simply you can break loop using break statement;
public void startFor()
{
boolean stopFlag = false;
for(; stopFlag == false ;) {
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();
switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
if(input.contentEquals("X"))
stopFlag = true;
}
}

how to use a range in switch case [duplicate]

This question already has answers here:
Using switch statement with a range of value in each case?
(20 answers)
Closed 5 years ago.
I use the switch case to get a large range:
class New {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Your Marks:");
int x = scan.nextInt();
switch(x){
case [100-0]:
/*
* getting a large range
*
*/
System.out.println("good");
break;
/**
*rang between 100-0 or some large range
*other ways to get the range in switch case
*/
default:
System.out.println("Invalid input");
break;
}
}
}
//**
*need to switch between large range in switch case is it posible on switch
*case
*
*/
You can't do it for large range.
But you can try like this (even though it is not a good practice):
switch(x){
case 1:
case 2:
case 3:
case 4:
case 5:
System.Out.Println("cases are between 1 to 5");
break;
}
I suggest you to use if else statements.
if you want more details see these:
java - switch statement with range of int
In Java,Using switch statement with a range of value in each case?
To start with, No. Switch is a wrong choice here. Go with traditional if's.
if(x>0 && x <100){
// do something
}..
..
..

New to Java trying to make a switch

I am trying to make a switch that will step through the code like in Javascript by adding "jedi++" at the end but it won't let me do that any suggestions on how I can accomplish that? Here is a snippet of the code.
switch(jedi){
case 1:
while(!input.equalsIgnoreCase("guardian") && !input.equalsIgnoreCase("sentinel") && !input.equalsIgnoreCase("consular")){
System.out.println("Please enter the path followed by this Jedi.");
System.out.println("(Guardian, Sentinel or Consular)");
}
registrant.setPath(input);
break;
case 2:
while(!input.equalsIgnoreCase("master") && !input.equalsIgnoreCase("knight") && !input.equalsIgnoreCase("padawan")
&& !input.equalsIgnoreCase("youngling")){
System.out.println("Please enter the Jedi's Rank.");
System.out.println("(Master, Knight, Padawan, Youngling)");
input = keyboard.nextLine();
}
registrant.setRank(input);
break;
jedi++;
}
Do you want to jedi++ in all the cases or just in case 2?
If it's just for case 2, you could do
case 2:
....
jedi++;
break;
case 3:
....
if it's for all the cases, you could do jedi++ after the switch block.
Statements can exist only within the case. since jedi++ is not part of case, its throwing error. Putting the increment statement under required case statement will solve the issue.

Loop a Switch case

I'm attempting to write code for a user menu. Put simply the user is given a menu of 5 options to input exam scores. Each option runs a method from a class. Once the method is done it will prompt the menu once more, and continue to loop until the user selects option 5, which will terminate the program. Though I am not sure how I can get this switch case to loop.
prof1.menu();
choice = console.nextInt();
do
{
switch(choice)
{
case 1: prof1.inputExamScore();
break;
case 2: prof1.modifyExam();
break;
case 3: prof1.displayExamScores();
break;
case 4:
case 5:
default:
System.out.println("That is not a valid input.");
}
}while (choice < 1 || choice > 4);
You can try infinite loop where you can break it from switch block as shown below:
Sample code :
loop: while (true) {
switch (choice) {
case 1:
...
case 5:
break loop;
default:
System.out.println("That is not a valid input.");
}
}
Hint:
increment a counter for a valid input and break the loop if 5 is chosen after accepting all valid inputs
move the code for accepting the user input in the loop at the beginning.

Categories