Stuck in Vector in Java - java

I created a string vector and I want to store the selected type of coffee in the vector, for example if I choose number 3,4,5 and 1, store them in Vector1 the variables ("LATTE", "AMERICAN", "CAPUCCINO" and "MOKA") and print those stored names, but the problem is that it just prints, number 6 "BLACK", always.
import java.io.*;
class Exercise{
public static void main (String[] args) throws java.io.IOException {
DataInputStream receivedata= new DataInputStream(System.in);
String keyboard;
int seleccafe,n=0,contvector=0;
String []Vector1=new String[200];
do{
System.out.println("\n1. MOKA");
System.out.println("2. EXPRESO");
System.out.println("3. LATTE");
System.out.println("4. AMERICAN");
System.out.println("5. CAPUCCINO");
System.out.println("6. BLACK");
System.out.println("0. OUT");
System.out.print("\nTYPE THE NUMBER: ");
seleccafe=Read_Da("");
SelectCo(Vector1,seleccafe,n);
contvector++;
n++;
if(seleccafe==0) break;
}while(true);
for(int i=0; i<contvector-1; i++){
System.out.println(Vector1[i]);
}
}
public static int Read_Da (String TxtMsg) throws java.io.IOException{
int X=0;
String keyboard;
DataInputStream reveivedata= new DataInputStream(System.in);
do{
System.out.print("");
keyboard=reveivedata.readLine();
try{
X=Integer.parseInt(keyboard);
if(X<0){
System.out.println("SELECT JUST 0+");
continue;
}
return X;
}catch(NumberFormatException e){
System.out.println("JUST NUMBERS");
}
}while(true);
}
public static void SelectCo(String xVector[], int xseleccafe, int xi){
switch(xseleccafe){
case 1:
xVector[xi]= "MOKA";
case 2:
xVector[xi]="EXPRESSO";
case 3:
xVector[xi]="LATE";
case 4:
xVector[xi]="AMERICAN ";
case 5:
xVector[xi]="CAPUCCINO";
case 6:
xVector[xi]="BLACK";
}
}
}
Any help? Thanks!

Your problem is that you are missing the word break; after each case clause in SelectCo, so each case is "falling through" to the one below, and finishing with case 6:.
It should look like this.
switch(xseleccafe){
case 1:
xVector[xi]= "MOKA";
break;
case 2:
xVector[xi]="EXPRESSO";
break;
case 3:
xVector[xi]="LATE";
break;
case 4:
xVector[xi]="AMERICAN ";
break;
case 5:
xVector[xi]="CAPUCCINO";
break;
case 6:
xVector[xi]="BLACK";
break;
default:
xVector[xi]="UNKNOWN";
}
More detail here

Related

Execution keeps timing out with this is 'do while' loop

I try to run this on the IDE and it just won't run.
Only inputting the number zero will run it.
Is it unable to leave the loop?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
do {
switch(number) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check account balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
}
while(number != 0);
System.out.println("Exit");
}
}
The initialization number should be done earlier. Here is the code:
import java.util.Scanner;
public class Main1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
number = scanner.nextInt();
switch(number) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check account balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
}
while(number != 0);
System.out.println("Exit");
}
}
Two changes: Move the scanner.nextInt() line inside do and change the while condition from number != 0 to number < 1 || number > 4:
Scanner scanner = new Scanner(System.in);
int number;
do {
number = scanner.nextInt();
switch(number) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check account balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
}
while(number < 1 || number > 4);
System.out.println("Exit");

How to fix my do while loop in order to have the menu appear again and again until the user presses Letter 'Q'?

Here's my code:
import java.util.Scanner;
// I want to call the menu function in my driver class and in a do while loop .
public class Driver {
public static void main(String[] args) {
do {
Scanner scanner = new Scanner(System.in);
char choice = scanner.next().charAt(0);
} while (choice == 'Q');// How to exit the menue
}
static void createNewEmployee() {
System.out.println("What is the name of employee?");
}
static void process() {
char choice;
switch (choice) {
case 'N':
System.out.println("new employee");
createNewEmployee();
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
default:
System.out.println("Error");
}
}
}
Change while (choice == 'q') into while (choice != 'q'). Think of it like "if the user presses anything apart from 'q', carry on".
I think this will help you!!
public static void main(String[] args) {
char choice;
do {
Scanner scanner = new Scanner(System.in) ;
System.out.print("Press Any Key: N -- New, P -- Paycheck, R -- Raise Wages,-- List Employee, Q -- Quit: ");
choice = scanner.next().charAt(0);
process(choice);
} while(choice !='Q');
}
static void process(char choice) {
switch (choice) {
case 'N':
System.out.println("new employee");
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
case 'Q':
System.out.println("Thanks!!");
break;
default:
System.out.println("Error");
}
}

How to switchcases inside if loop

I'm stuck at a question that requests me if the user insert something else instead "e" "x" nums between 1 to 10, then it's returning "incorrect"
here's the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try{
int Num = 0;
Num = sc.nextInt();
String str = sc.nextLine();
switch (Num) {
case 1: case 2: case 3: case 4:
case 5: case 6: case 7: case 8:
case 9: case 10:
System.out.println("this is a volume");
break;
case : if((Num>10)||(Num <0))
System.out.println("this is incorrect");
break;
}
switch (str) {
case "e": case "E":
System.out.println("Shutting Down");
break;
case "x" : case "X":
System.out.println("Mute");
break;
case "a":case "b":case "c":case "d":case "f":case "g":case "h":case "i":case "j":
case "k":case "l":case "m":case "n":case "o":case "p":case "q":case "r":case "s":
case "t":case "u":case "v":case "w":case "y":case "z":
System.out.println("this is incorrect");
break;
default:
break;
}
}
catch(Exception e) {
System.out.println("stopped");
}
}
}
thank you
If I understand your question properly, as you did not specify how many time the user should enter the input. However, you can have a look at this example, take the idea of the approach and then create your own one.
import java.util.Scanner;
public class ParseInput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert E for Shutdown, X for Mute and Numbers between 1 to 10 for Volume");
String input = in.nextLine().trim(); // read the entire line after removing spaces if any, then parse it
if(input.length()>0){ // that means the user entered something
try{
int volumeValue = Integer.parseInt(input); // if it's not a number, it will throw exception that will be handled in the catch block
if(volumeValue>=1 && volumeValue<=10){// then evaluate the value
System.out.println("This is a Volume");
}
else{
System.out.println("Incorrect Volume Value");
}
}catch(NumberFormatException e){ // if you reach this block that means it's not a number
if(input.equalsIgnoreCase("e")){ // to accept both uppercase and lowercase
System.out.println("Shutting Down");
}
else if(input.equalsIgnoreCase("x")){
System.out.println("Mute");
}
else{
System.out.println("Incorrect Input");
}
}
}
else{
System.out.println("You have NOT entered anything!");
}
}
}
Test
Insert E for Shutdown, X for Mute and Numbers between 1 to 10 for Volume
e -> Shutting Down
x -> Mute
5 -> This is a Volume
12 -> Incorrect Volume Value
ZzZ -> Incorrect Input
-> You have NOT entered anything!
Please try the below code
switch (Num)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
System.out.println("this is a volume");
break;
default:
{
if ((Num > 10) || (Num < 0))
{
System.out.println("this is incorrect");
}
break;
}
}

Java How can I break a while loop under a switch statement?

I have a homework to implement a simple testing application, below is my current code:
import java.util.*;
public class Test{
private static int typing;
public static void main(String argv[]){
Scanner sc = new Scanner(System.in);
System.out.println("Testing starts");
while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
break; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
System.out.println("Test is done");
}
}
What I want to do now is that when 0 is pressed, it means that the user wants to quit the test, then I break the while loop and print Test is done, but it doesn't work like that, I know the reason might be that the "break" breaks the switch, how can I let it break the while loop instead?
You can label your while loop, and break the labeled loop, which should be like this:
loop: while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
break loop;
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
And the label can be any word you want, for example "loop1".
You need a boolean variable e.g. shouldBreak.
boolean shouldBreak = false;
switch(typing){
case 0:
shouldBreak = true;
break; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
if (shouldBreak) break;
Put the while inside a function and when you press 0 instead of break just return. For example :
import java.util.*;
public class Test{
private static int typing;
public static void main(String argv[]){
Scanner sc = new Scanner(System.in);
func(sc);
System.out.println("Test is done");
}
}
public static void func(Scanner sc) {
System.out.println("Testing starts");
while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
return; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
}
}
How to terminate inner menu ?
Example Code :
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //used to get input
int option1, option2 = 0;
boolean loop_terminate = true; //flag used to terminate inner while loop
//Main Menu
while (true) {
//Main Menu options
System.out.println("1.Option 1");
System.out.println("2.Option 2");
System.out.println("3.Option 3");
System.out.println("4.Option 4");
System.out.println("5.Exit main menu");
System.out.print("Please enter your choice : ");
option1 = input.nextInt();
switch (option1) {
case 1:
//do something here
break;
case 2:
//do something here
break;
case 3:
while (loop_terminate) {
//Inner menu options
System.out.println("1.Inner Menu option 1");
System.out.println("2.Inner Menu option 2");
System.out.println("3.Inner Menu option 3");
System.out.println("4.Return to Main Menu");
System.out.print("Please enter your choice : ");
option2 = input.nextInt();
switch (option2) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
loop_terminate = false; //this will terminate inner menu
break;
default:
System.out.println("Invalid option");
break;
}
}
break; //never forget to add this break statement
case 4:
break;
case 5:
return; //terminate outer menu
default:
System.out.println("Invalid option");
}
}
}
}

ArrayList java program without using generics

I had been given an assignment to implement ArrayList and LinkedList without using generics. The problem is with the insertnode() method. Though I try to read from commandline using a scanner, the method returns without waiting.
import static java.lang.System.out;
import java.util.Scanner;
class Arraylist
{
public static final int LIST_SIZE=30;
static Scanner input = new Scanner(System.in);
static Object list[];
static int top = -1;
static int typeoflist;
public static void displaymenu()
{
int choice;
do{
out.print("\n Basic operations on a linked list:");
out.print("\n 1. Create list \n 2. Insert node \n 3. Delete node \n 4. Modify node \n 5. Search value \n 6. Print list\n Else. Exit \n Choice:");
choice = input.nextInt();
switch(choice)
{
case 1:
list = createlist();
break;
case 2:
insertnode();
break;
case 3:
//deletenode();
break;
case 4:
//modifynode();
break;
case 5:
//searchnode();
break;
case 6:
printlist();
break;
default:
return;
}
}while(true);
}
public static Object[] createlist()
{
int typeoflist;
out.println("Enter your choice of list datatype: \n 1. int \n 2. float \n 3. char \n 4. String \n 5. UserDefined \n Choice:");
typeoflist = input.nextInt();
switch(typeoflist)
{
case 1:
list = new Integer[LIST_SIZE];
break;
case 2:
list = new Float[LIST_SIZE];
break;
case 3:
list = new Character[LIST_SIZE];
break;
case 4:
list = new String[LIST_SIZE];
break;
}
return (Object[])list;
}
public static void insertnode()
{
Object o;
top++;
out.println("Enter the value to insert:");
switch(typeoflist)
{
case 1:
o = (Integer)input.nextInt();
list[top] = o;
break;
case 2:
o = (Float)input.nextFloat();
list[top] = o;
break;
case 3:
//o = (Character)input.next(); //
//list[top] = o;
break;
case 4:
o = (String)input.next();
list[top] = o;
break;
}
}
public static void printlist()
{
for(int i =0; i<top; i++)
{
out.println(list[i]);
}
}
public static void main(String[] args)
{
displaymenu();
}
}
Hint: typeoflist in createList() is hiding the static member variable.

Categories