I need my array to be dynamic, as long as the user enters/deletes elements. The array can't have the length already defined or ask the user the length. For example the user decides to add 5, the array would be: {5}, then the user adds 34 {5,34}, then deletes 5, {34}.
Is there a way of doing it? i've been trying with list but when i used if the remove one didn't work and when i use switch with this code it says "unreachable statement".
Here's the code so far:
List<String> list = new ArrayList<>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current " + list);
System.out.println("Add more? (1) delete one? (2) exit (3)");
int a= stdin.nextInt();
switch(a){
case 1:
System.out.println("Enter: ");
list.add(stdin.next());
break;
case 2:
System.out.println("Enter: ");
list.remove(stdin.next());
break;
case 3:
break;
default:
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
You can try to use label.
So basically the break in your case 3 only breaks outside switch statement but not outside the do while loop.
You can add a statement before do as below:
outerloop:
do{
switch(a){
// rest of your logic
case 3:
break outerloop;
}
}
while(true)
where outerloop is a label. Please try this.
I think there's a problem with your while statement.
When you use the break keyword, it refers to your switch statement.
So you'll never reach the end of your loop.
Try something to implement something to break the loop
Related
As the title states, right now I have something that looks like this:
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
string input = scanner.nextLine();
switch(input){
case 1:
do stuff;
break;
case 2:
do stuff;
break;
case 3;
printf("we're done here");
scanner.close();
System.exit(1);
}
}
Obviously, my actual code isn't this simple, but the general idea is the same.
The loops work, and it'll process every line until the last.
And here's the problem, it won't process the last line, the one that actually exits the program....
The answer is probably very simple, but I can't really think of it from the top of my head. How can I process the last line?
Try the below code it works, Use System.exit(0) should come outside switch.
Scanner scanner = new Scanner(System.in);
boolean flag = false;
while(scanner.hasNextLine()){
string input = scanner.nextLine();
switch(input){
case 1:
do stuff;
break;
case 2:
do stuff;
break;
case 3;
printf("we're done here");
flag = true;
break;
}
if(flag) {
System.exit(0); //try 'break' too.
}
}
You need to move the code for the last case statement to the outside of the while loop. The scanner won't have another line and the loop will break.
first question:
There is a do while loop, within the do section there is a switch. After selection case 1, some calculations are done, two options can result as shown in the If statement. My problem is code runs until the break; then just goes straight back to the menu loop. My question: how do i get the program to print the output for the user, then continue the menu loop?
Second question:
In case 1 there are two resulting options, the first being a failed response. from here, how do i get the program to loop back to the start of case 1 to ask for user input again? Even back to the main menu would be fine.
public static void showMenu() {
System.out.print('\u000c');
System.out.println("1 - Compute Change \n");
System.out.println("2 - Estimate Feast \n");
System.out.println("3 - \n");
System.out.println("4 - \n");
System.out.println("5 - I'm broke, get me out of here\n");
System.out.println("Select Option:\n");
}
public StackPost() {
System.out.println("Welcome to the Bank of Winterfell");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection) {
case 1:
// get input, compute then decision:
if (something<somethingElse) {
// false response -
} else {
// correct response - system prints out some stuff back to user, back to main
// menu loop
}
break;
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
You could print "Press enter to continue" (or whatever you want to give notice of before locking the program), and add a call to Scanner#nextLine() before your break. This will lock the progression 'till user presses enter.
case 2:
// Some code here...
// Done, now show result and tell user to press any key to continue
System.out.println("Some fancy result from case handle code");
System.out.println("Press enter to continue...");
in.nextLine();
break;
You could add a while-loop that won't let the code continue 'till whatever input is expected in the first case is acceptable.
case 1:
System.out.println("Some handle that tells user to input something, and what is acceptable");
String input = null;
while(!(input = in.nextLine()).equals("something")) {
System.out.println("Wrong input, try again...");
}
// Input is acceptable, now do something with it...
System.out.println(input);
System.out.println("Press enter to continue...");
in.nextLine();
break;
Be aware, in your code, you call Scanner#nextInt(), and #nextInt doesn't consume the \n from pressing enter, and will thus be transferred into the switch case's usage of #nextLine(). You could avoid this with selection = Integer.parseInt(in.nextLine()).
You can use achieve it by:
For First question: Using return statement in case of correct response.
For Second question: Using while loop in case 1
After implementaing the proposed solution the StackPost() method will look like following. You can see the complete working code here:
public static void StackPost()
{
System.out.println("Welcome to the Bank of Winterfell");
try(Scanner in = new Scanner(System.in))
{
int selection;
do
{
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
// get input, compute then decision:
while(true)
{
int something = in.nextInt();
int somethingElse = in.nextInt();
if (!(something<somethingElse)) {
// correct response - system prints out some stuff back to user, back to main
System.out.println("Print here the result");
// menu loop
return;
}
// false response - continue for next iteration in while-loop
}
//No need of 'break;' here
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
}
Note: It is best practice to use try-with-resources while handling system resources which implements AutoCloseable interface.
I'm kinda new to this but? can anyone correct my first switch statement? I dont know what expression to use to start the case a:
and im not even sure if the starting declarations are even correct
import java.io.*;
public class SwitchDemo {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input= br.readLine();
System.out.println("Press Enter");
System.out.println("a.Hello: Asks the name of the user.");
System.out.println("b.Array: Input elements and search for a specified key and prints a message.");
System.out.println("c.MagicSquare: Displays [7][7] magic square.");
System.out.println("d.Bubble Sort: Alphabetically sorts 20 employees using bubble sort.");
System.out.println("e.Selection Sort: Alphabetically sorts 20 employees using selection sort");
System.out.println("f.Insertion Sort: Alphabetically sorts 20 employees using Insertion sort");
System.out.println("g.Factorial: Run the Factorial application");
System.out.println("h.Triangle: Run the Triangle application.");
System.out.println("i.MergeSort: Performs the mergesort of a two class databasse.");
System.out.println("j.Stack_1: Perform reversal of string.");
System.out.println("k.Stack_2: Perform Infix Notation");
System.out.println("l.Postfix: Perform Postfix Notation");
System.out.println("m.Linked List");
System.out.println("n.Queue:");
System.out.println("o.Exit:");
switch (input) {
case a:
String usersName;
String upperCaseName;
TextIO.put("Please enter your name: ");
usersName = TextIO.getln();
upperCaseName = usersName.toUpperCase();
TextIO.putln("Hello, " + upperCaseName + ", nice to meet you!");
break;
case b:
// Code for b execution here. Run array.
break;
case c:
// Code for c execution here. magicsquare.
break;
case d:
// Code for d execution here. Bubble sort.
break;
case e:
// Code for e execution here. selection sort.
break;
case f:
// Code for f execution here. insertion sort.
break;
case g:
// Code for g execution here. recursion.
break;
case h:
// Code for h execution here. mergesort.
break;
case i:
// Code for b execution here. stack1.
break;
case j:
// Code for b execution here. stack2.
break;
case k:
// Code for b execution here. link list.
break;
default:
System.out.println("Please input selection from a-o");
break;
}
}
}
As others have mentioned, using
switch(input) {
case "a":
// do stuff
break;
case "b":
// do more stuff
break;
}
will work.
Just another thing, if you are working in java 7 (java -version), you should be able to get rid of
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
and replace it with
Scanner in = new Scanner(System.in);
String input = in.nextLine();
Which at least to me is a lot easier to use. Just import
import java.util.Scanner;
A couple of points here
case statements are like this (pre 1.7)
char input = 'a';
switch (input) {
case 'a':
break;
default :
System.out.println("default");
}
for Java 1.7 and onwards you can also switch on Strings
String input = "a";
switch (input) {
case "a":
printHelloUser();
break;
default :
System.out.println("default");
}
void printHelloUser () {
String usersName;
String upperCaseName;
TextIO.put("Please enter your name: ");
usersName = TextIO.getln();
upperCaseName = usersName.toUpperCase();
TextIO.putln("Hello, " + upperCaseName + ", nice to meet you!");
}
you may also want to consider prompting the user first before reading her input.
You aren't checking the cases as Strings (you declare input as a String). You are calling variables called a, b, etc. Try putting them into quotation marks, as in case: "a".
I am trying to make a simple calculator program where a user can opt to do an operation and enter the numbers as long as he/she wishes to.
I just have problem because whenever I would reach inside my loop and ask the user if he/she want to continue and whenever I would run the program, I would have an "Exception in thread "main" java.lang.NullPointerException"
Scanner myInput=new Scanner(System.in);
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
while ((ans=='Y')||(ans=='y'))
{
//get the numbers
//provide the menu
//get the user's choice
switch (calc)
{
case 1: out.println("Sum is: " +(num1+num2)); break;
case 2: out.println("Difference is: " +(num1-num2)); break;
case 3: out.println("Product is: " +(num1*num2)); break;
case 4: out.println("Quotient is: " +(num1/num2)); break;
case 5: out.println("Modulo is is: " +(num1%num2)); break;
case 6: out.println("Sum is: " +(num1+num2));
out.println("Difference is: " +(num1-num2));
out.println("Product is: " +(num1*num2));
out.println("Quotient is: " +(num1/num2));
out.println("Modulo is is: " +(num1%num2)); break;
default: out.println("Invalid."); break;
}
out.println("Compute another?");
ans=myInput.findInLine(".").charAt(0);
}
May I humbly ask what can I do with this program so that it will ask again for the user's input whether to continue or not? Thanks in advance for your help.
in this palce, best way is to use do-while
do{
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
//
//
//
}while ((ans=='Y')||(ans=='y'));
This will keep asking till the user's answer is 'Y' or 'y'.
I hope you can take care of other thing.
for using while loop.
System.out.print("Do you have numbers to compute?");
char ans=myInput.findInLine(".").charAt(0);
while((ans=='Y')||(ans=='y')){
//
//
//
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
}
The NullPointerException is being thrown as Scanner.findInLine() can return null if it does not find the requested String/Pattern. The code invokes the method charAt(0) on the null String. Changing the code to the following will resolve this:
Scanner myInput=new Scanner(System.in);
char ans;
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
while ((ans=='Y')||(ans=='y'))
{
// Code omitted
System.out.print("Compute another?");
myInput.nextLine();
String s = myInput.findInLine(".");
ans = (null == s) ? 'n' : s.charAt(0);
}
So I'm guessing that the solution to this is going to be really simple but I have no idea what I'm looking for so I'd like some help. What happens is that when I run the program, and choose case 1. It prints both "dog's name" and "dogs race" without giving me a chance to fill in the dogs name. So when I choose case 1 I start out only getting to fill in dogs race, how heavy, and how old it is! here is the code I'm using...
do {
System.out.println("(1 - reg\n2 - tail\n3- delete\n4-exit\nEnter number: ");
// so this is where the switch stuff starts
int option=sc.nextInt();
switch (option) {
case 1: System.out.println("Dog's Name: ");
String na=sc.nextLine();
System.out.println("Dog Race: ");
String ra=sc.nextLine();
System.out.println("How heavy?");
double wey=sc.nextDouble();
System.out.println("How old?");
double ag=sc.nextDouble();
dog doggy= new dog(na, ra, wey, ag);
kennel.add(doggy);
break;
case 2: System.out.println("its a tail");
break;
case 3: System.out.println("you delete");
break;
case 4: System.out.println("QUITTING\n(Data was not saved srry.)");
play = false;
default: System.out.println("try again");
}
}while(play);
I believe you need to call nextLine() after your call to nextInt(), because that hasn't advanced the scanner to the next line yet.
There's a newline reminder from your first sc.nextInt, you can change the delimiter to \n or just call nextLine(); just after reading the option (Using sc.useDelimiter("\n") )
Try:
int option=Integer.parseInt(sc.nextLine());
This has both the effect of advancing the cursor to the next line and getting the typed number.