No such element exception - java

The ch variable is not recognised by the while loop although it is declared outside the loop. Why? There is no compilation error.
package calculator;
import java.util.Scanner;
public class Calculation {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.print("ENTER YOUR CHOICE : ");
ch = s.nextInt();
switch (ch) {
case 1: {
}
.....
default: {
System.out.println("\n!!!ENTER VALID CHOICE !!!");
break;
}
}
} while (ch != 9);
s.close();
}
}

put your break statement of default case outside the braces. I think that is your problem. I tried the below code and gives me the output.
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.print("ENTER YOUR CHOICE : ");
ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("one");
break;
default:
System.out.println("\n!!!ENTER VALID CHOICE !!!");
break;
}
}while(ch!=9);
s.close();
}
}

This code is working fine. elements of parent block are always visible.
Don't use break in default case
Your code :
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.print("ENTER YOUR CHOICE : ");
ch = s.nextInt();
switch (ch) {
case 1:
System.out.println("one");
break;
default:
System.out.println("\n!!!ENTER VALID CHOICE !!!");
}
} while (ch != 9);
s.close();
}
}
*Only the edit I made was I removed break from default block.
Running Example :
ENTER YOUR CHOICE : 1
one
ENTER YOUR CHOICE : 2
!!!ENTER VALID CHOICE !!!
ENTER YOUR CHOICE : 3
!!!ENTER VALID CHOICE !!!
ENTER YOUR CHOICE : 9
!!!ENTER VALID CHOICE !!!

Related

How to switch order of output?

How do I switch the order of the outcome? I would liked to be asked to enter output after the menu.
Welcome to the Library! Please make a selection from the menu:
1. View.
2. Show.
Enter a choice: 1
However, I am made to enter input first, and I see:
Enter a choice: 1
Welcome to the Library! Please make a selection from the menu:
1. View.
2. Show.
This is my code:
import java.util.*;
public class Store {
public static void main(String[] args) {
new Store().use();
}
public void use() {
char choice;
while ((choice = readChoice()) != 'X') {
switch (choice) {
case 1: view(); break;
case 2: show(); break;
default: help(); break;
}
}
}
private char readChoice() {
return In.nextChar();
}
private String view() {
return "";
}
private String show() {
return "";
}
}
private void help() {
System.out.println("Welcome! Please make a selection from the menu:");
System.out.println("1. View.");
System.out.println("2. Show."); }
Just add help() on top of the use() method:
public void use() {
help();
char choice;
while ((choice = readChoice()) != 'X') {
switch (choice) {
case 1: view(); break;
case 2: show(); break;
default: help(); break;
}
}
}
You also need to change 1 and 2 into '1' and '2' respectively, because you are switching over a char. The fact that this compiles is because the compiler applies a narrowing primitive conversion to convert int to char.
I think there are three reasons that the code does not do what you expect.
You are made to enter input first, because before printing anything on the console, the readChoice() function is called. Which waits until it reads one character from the console and then returns. So you must call Help() function once before the while loop.
I guess the switch-case will not do what you expect. I mean the view() and show() functions are not called when you enter 1 or 2. The reason is that you read 1 and 2 as characters not integers. So the switch-case should change to this:
switch (choice) {
case '1': view(); break; //1 changed to '1'
case '2': show(); break; //2 changed to '2'
default: help(); break;
}
I think you might have forgotten to print "Enter a choice:" before reading the character. (I used System.out.print() rather than System.out.println() because it seems that "Enter a choice:" and the choice entered should be in the same line)
private char readChoice() {
System.out.print("Enter a choice:");
return In.nextChar();
}
this is the entire code, hope it works correctly (I put comments so you see what changes I made):
import java.util.*;
public class Store {
public static void main(String[] args) {
new Store().use();
}
public void use() {
char choice;
help();//called help() once before the loop
while ((choice = readChoice()) != 'X') {
switch (choice) { //cases changed
case '1': view(); break;
case '2': show(); break;
default: help(); break;
}
}
}
private char readChoice() {
//printing "Enter a choice:"
System.out.print("Enter a choice: ");
//I used Scanner class to read the next char, because I don't have 'In' class to use.
//you might write "return In.nextChar();" insead of the following lines
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
return c;
}
private String view() {
System.out.println("you selected view"); //to see this function is called
return "";
}
private String show() {
System.out.println("you selected show"); //to see this function is called
return "";
}
private void help() {
System.out.println("Welcome! Please make a selection from the menu:");
System.out.println("1. View.");
System.out.println("2. Show.");
}
};

switch case in implementation of stack using array in java

import java.io.*;
import java.util.*;
public class Stack1{
static final int MAX=100;
int top=-1;
int[] stack=new int[MAX];
public static void main(String args[])
{
Stack1 s1=new Stack1();
int opt, val;
System.out.println("1. PUSH ");
System.out.println("2. POP ");
System.out.println("3. PEEP ");
System.out.println("4. DISPLAY STACK ");
System.out.println("5. EXIT ");
System.out.println("\n Enter Your Option: ");
Scanner s=new Scanner(System.in);
opt=s.nextInt();
do{
switch(opt)
{
case 1: System.out.println("Enter the value to be added to the stack: ");
val=s.nextInt();
s1.push(val);
break;
case 2: s1.pop();
break;
/*
case 3: s1.peep();
break; */
case 4: s1.display();
break;
}
}while(opt!=5);
}
public void push(int val)
{
if(top==MAX-1)
{
System.out.println("Stack is FULL!");
}
else
{
top++;
stack[top]=val;
System.out.println("Element added to the stack is: "+val);
display();
}
}
public void pop()
{
int x;
if(top==-1)
{
System.out.println("Stack is EMPTY!");
}
else
{
x=stack[top];
System.out.println("The element deleted from the stack is: "+x);
top--;
display();
}
}
public void peep()
{
int n;
n=stack[top];
System.out.println("The value at the top of the stack is: "+n);
}
public void display()
{
int i;
if(top==-1)
System.out.println("STACK IS EMPTY!");
else
{
for(i=0; i<=top; i++)
System.out.println("The elements in the stack are: "+stack[i]);
}
}
}
I wrote this java code to implement stack. But once I select any option, only that method gets executed and the program ends. I want the program to provide me to enter another option once the current method is executed. What should I do?
As #LordWilmore pointed out in his comment, the opt value will be set just once causing program to spin forever in a corresponding case (unless the value is 5). Moving opt = s.nextInt(); inside loop will fix the issue.
do {
System.out.println("Enter Your Option: ");
opt = s.nextInt();
switch(opt) {
//...
}
} while (opt != 5);
You can modify your main method in a manner like this:
public static void main(String args[]){
int option;
Scanner sc = new Scanner(System.in);
MyStack1 s = new MyStack1();
while(true){
System.out.println("Enter the choice You want to perform on the stack: ");
System.out.println(" 1. push \n 2. Pop \n 3. Display \n 4. peep \n 5. Exit");
System.out.println("Enter your option: ");
option = sc.nextInt();
switch(option){
case 1: System.out.println("Enter the element you want to push into the stack: ");
s.push(sc.nextInt());
break;
case 2: s.pop();
break;
case 3: System.out.println("Displaying the stack contents: ");
s.display();
break;
case 4: System.out.println("The top element in the stack is: ");
s.peek();
break;
case 5: System.out.println("You selected Exit!!");
break;
default: System.out.println("Wrong choice!! Please enter a valid option!!");
return;
}
}
}

Creating a Basic Java phone book

I'm just learning Java and trying to make a simple phone book. For this part I'm trying to prompt the user to choose one of the 3 options below.
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n': enterNumber;
system.out.println();
case 's':showNumber;
system.out.println();
case 'c': closeBook;
break;
default: System.out.println("Invalid Entry");
}
}
}
}
When I compile it i get errors on lines 37, 39, and 41 saying "Error: not a statement". I feel like something is missing. If anyone can help it would be greatly appreciated.
I am assuming that with the following lines you want to achieve to print the letter n for enterNumber in the console?
case 'n': enterNumber;
system.out.println();
This is not correct Java syntax. You will have to pass the variable value to the System.out.println method call:
case 'n': System.out.println(enterNumber);
Also note that Java is case sensitive, so you have to spell System with a capital letter.
On a side note, you will want to break; after each of your case statements, otherwise the code of the following cases will be executed as well:
switch (choice) {
case 'n': System.out.println(enterNumber);
break;
case 's': System.out.println(showNumber);
break;
case 'c': System.out.println(closeBook);
break;
default: System.out.println("Invalid Entry");
}
you do not have to write variable after 'cast' statement.
Refer below code.
import java.util.Scanner;
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n':
System.out.println();
case 's':
System.out.println();
case 'c':
break;
default: System.out.println("Invalid Entry");
}
}
}
}
I have made a special answer for you. I don't add additional explanation. It's a large answer. I tell more than you ask, but I've done my best to make a readable code, so that you can analyse step-by-step to understand what you need at least when trying to make a Phone Book (console test drive application). If you need more explanation, write under comments.
First make a PhoneEntry class:
import java.util.Objects;
public class PhoneEntry implements Comparable<PhoneEntry> {
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5Ba-zA-Z%5D%7B2%2C%7D((-%7C%5Cs)%5Ba-zA-Z%5D%7B2%2C%7D)*%24
private static final String NAME_PATTERN = "^[a-zA-Z]{2,}((\\-|\\s)[a-zA-Z]{2,})*$";
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5C%2B%3F%5Cd%2B((%5Cs%7C%5C-)%3F%5Cd%2B)%2B%24
private static final String NUMBER_PATTERN = "^\\+?\\d+((\\s|\\-)?\\d+)+$"; //^\+?\d+((\s|\-)?\d+)+$
private final String name;
private final String number;
public PhoneEntry(String name, String number) {
if (!name.matches(NAME_PATTERN) || !number.matches(NUMBER_PATTERN)) {
throw new IllegalArgumentException();
}
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public boolean nameContainsIgnoreCase(String keyword) {
return (keyword != null)
? name.toLowerCase().contains(keyword.toLowerCase())
: true;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof PhoneEntry)) {
return false;
}
PhoneEntry phoneEntry = (PhoneEntry) obj;
return name.equalsIgnoreCase(phoneEntry.name)
&& number.equalsIgnoreCase(phoneEntry.number);
}
#Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + Objects.hashCode(this.name.toLowerCase());
hash = 17 * hash + Objects.hashCode(this.number.toLowerCase());
return hash;
}
#Override
public int compareTo(PhoneEntry phoneEntry) {
return name.compareToIgnoreCase(phoneEntry.name);
}
}
Then the test drive
public class TestDrive {
private static final String choices = "nspc";
enum Choice {
CREATE, READ, PRINT, CLOSE;
static Choice getChoice(char c) {
switch (c) {
case 'n':
return Choice.CREATE;
case 's':
return Choice.READ;
case 'p':
return Choice.PRINT;
case 'c':
return Choice.CLOSE;
}
return null;
}
}
// Main
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
final Set<PhoneEntry> entries = new TreeSet<>();
Choice choice;
while ((choice = getChoice(kbd)) != Choice.CLOSE) {
switch (choice) {
case CREATE:
PhoneEntry entry = getPhoneEntry(kbd);
if (entry != null) {
entries.add(entry);
}
break;
case READ:
print(readEntries(entries, kbd));
break;
case PRINT:
print(entries);
break;
}
}
}
private static Choice getChoice(Scanner kbd) {
System.out.println("\nPlease select from the following");
System.out.println("\tn to Enter the number");
System.out.println("\ts to Show numbers by keyword ");
System.out.println("\tp to Show all numbers ");
System.out.println("\tc to Close the Phone book");
System.out.print("> ");
String input = kbd.nextLine();
Choice choice = null;
if (!input.isEmpty()
&& choices.contains(input.toLowerCase())
&& ((choice = Choice.getChoice(input.toLowerCase().charAt(0))) != null)) {
return choice;
}
System.out.println("ERR: INVALID ENTRY. TRY AGAIN");
return getChoice(kbd);
}
private static PhoneEntry getPhoneEntry(Scanner kbd) {
System.out.print("Type contact name: ");
String name = kbd.nextLine();
System.out.print("Type phone number: ");
String number = kbd.nextLine();
try {
return new PhoneEntry(name, number);
} catch (IllegalArgumentException ex) {
System.out.println("\nERR: WRONG ENTRY");
}
return null;
}
private static void print(Set<PhoneEntry> entries) {
System.out.println("\nPHONE NUMBERS\n");
entries.stream().forEach(entry -> {
System.out.printf("Name: %s%nPhone: %s%n%n",
entry.getName(), entry.getNumber());
});
}
private static Set<PhoneEntry> readEntries(Set<PhoneEntry> entries, Scanner kbd) {
System.out.print("Type keyword: ");
return entries.stream().filter(entry
-> entry.nameContainsIgnoreCase(kbd.nextLine()))
.collect(Collectors.toCollection(TreeSet::new));
}
}
Instead of enterNumber;, you have to write enterNumber();.
The parentheses mean: Call the method.

Code efficiency. Effective way of using loops

I am building a framework for a web application and would like to perform certain simple tasks like input retrieval and displaying them. Below is have the code, I feel the code can be improved and isn't efficient. Note:All three methods have the same implementation.
The Switch needs to be implemented twice one within the IF loop and the other for general case.
public class selector8
{
public static void main (String [] args){
selector8 obj1 = new selector8();
Scanner inputString = new Scanner (System.in);
Scanner inputYN = new Scanner (System.in);
String input, A,B,C;
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
char contLoop1 = 'y';
do{
if(input.equalsIgnoreCase("y")) {
input = "";
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
switch (input){
case("a"):
obj1.startMethod1(input);
break;
case("b"):
obj1.startMethod2(input);
break;
case("c"):
obj1.startMethod3(input);
break;
case("x"):
System.out.println("Goodbye");
break;
case ("n"):
System.out.println("See ya");
break;
default:
System.out.println("Invalid argument. Try again");
break;
}
} else
switch (input){
case("a"):
obj1.startMethod1(input);
break;
case("b"):
obj1.startMethod2(input);
break;
case("c"):
obj1.startMethod3(input);
break;
case("x"):
System.out.println("Goodbye");
break;
case ("n"):
System.out.println("See ya");
break;
default:
System.out.println("Invalid argument. Try again");
break;
}
System.out.println("Do want to try again " +"Y/N" );
input = inputYN.nextLine();
contLoop1 = input.charAt(0);
}while(contLoop1 != 'n');
}
public void startMethod1(String A){
String input;
Scanner inputString = new Scanner (System.in);
System.out.println("Enter a or b");
input = inputString.nextLine();
switch (input){
case("a"):
System.out.println("output parsed");
break;
case("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
}
}
public void startMethod2(String B){
String input;
Scanner inputString = new Scanner (System.in);
System.out.println("Enter a or b");
input = inputString.nextLine();
switch (input){
case("a"):
System.out.println("output parsed");
break;
case("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
break;
}
}
public void startMethod3(String C){
String input;
Scanner inputString = new Scanner (System.in);
System.out.println("Enter a or b");
input = inputString.nextLine();
switch (input){
case("a"):
System.out.println("output parsed");
break;
case("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
}
}
}
On a side note could you also tell me why can static classes be called without an object?
public class StaticImplementation{
public static void main (String [] args){
StaticImplementation obj1 = new StaticImplementation();
obj1.stat(); //is invalid
stat(); //is valid
}
static void stat(){
System.out.println("Static class");
}
Thanks a bunch. Have a good day!
using Java you'd probably take a more "Object Oriented" approach and leave those switches to C programming :)
do something like:
interface Action {
void start();
}
class Jumper implements Action {
public void start() {
System.out.println("Jump!");
}
}
class Sitter implements Action {
public void start() {
System.out.println("Sit!");
}
}
class Runner implements Action {
public void start() {
System.out.println("Run!");
}
}
class Test {
public static void main(String[] args) {
// init phase
Map<String, Action> map = new HashMap<String, Action>();
map.put("a", new Jumper());
map.put("b", new Runner());
// usage
map.get("a").start();
}
}
you can have two Maps one for Y and the other for the rest, you can also have a key composed from the two strings Pair
Oh yes, it can. You don't need two scanners, and I would extract your switch into a method (let's call it startMethods) like so -
private static void startMethods(selector8 obj1,
String input) {
switch (input) {
case ("a"):
obj1.startMethod1(input);
break;
case ("b"):
obj1.startMethod2(input);
break;
case ("c"):
obj1.startMethod3(input);
break;
case ("x"):
System.out.println("Goodbye");
break;
case ("n"):
System.out.println("See ya");
break;
default:
System.out.println("Invalid argument. Try again");
break;
}
}
public static void main(String[] args) {
selector8 obj1 = new selector8();
Scanner inputString = new Scanner(System.in);
String input, A, B, C;
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
char contLoop1 = 'y';
do {
if (input.equalsIgnoreCase("y")) {
input = "";
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
startMethods(obj1, input);
} else
startMethods(obj1, input);
System.out.println("Do want to try again "
+ "Y/N");
input = inputString.nextLine();
contLoop1 = input.charAt(0);
} while (contLoop1 != 'n');
}
Try this:
public class Selector8 {
public static void main(String[] args) {
Selector8 obj1 = new Selector8();
Scanner inputString = new Scanner(System.in);
Scanner inputYN = new Scanner(System.in);
String input, A, B, C;
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
char contLoop1 = 'y';
while (contLoop1 != 'n') {
if (input.equalsIgnoreCase("y")) {
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
}
switch (input) {
case ("a"):
case ("b"):
case ("c"):
obj1.startMethod();
break;
default:
System.out.println(validate(input));
break;
}
System.out.println("Do want to try again " + "Y/N");
input = inputYN.nextLine();
contLoop1 = input.charAt(0);
}
}
public static String validate(String input) {
if (input.equalsIgnoreCase("x"))
return "Goodbye";
if (input.equalsIgnoreCase("n"))
return "See ya";
return "Invalid argument. Try again";
}
public void startMethod() {
Scanner inputString = new Scanner(System.in);
System.out.println("Enter a or b");
String input = inputString.nextLine();
switch (input) {
case ("a"):
case ("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
}
}
}

Exception handling infinite loop

my question is short and sweet. I do not understand why my program infinitely loops when catching an error. I made a fresh try-catch statement but it looped and even copied, pasted and modified the appropriate variables from a previous program that worked. Below is the statement itself and below that will be the entire program. Thank you for your help!
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
Program:
public class Blanco {
public static int input;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
nameInput();
}
/**
*
* #param name
*/
public static void nameInput() {
System.out.println("What is the name of the cartoon character : ");
Scanner keyboard = new Scanner(System.in);
CartoonStar star = new CartoonStar();
String name = keyboard.next();
star.setName(name);
typeInput(keyboard, star);
}
public static void typeInput(Scanner keyboard, CartoonStar star) {
boolean again = true;
while(again){
System.out.println("What is the cartoon character type: 1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n"
+ "6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT");
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
switch (input) {
case 1:
star.setType(CartoonType.FOX);
break;
case 2:
star.setType(CartoonType.CHICKEN);
break;
case 3:
star.setType(CartoonType.RABBIT);
break;
case 4:
star.setType(CartoonType.MOUSE);
break;
case 5:
star.setType(CartoonType.DOG);
break;
case 6:
star.setType(CartoonType.CAT);
break;
case 7:
star.setType(CartoonType.BIRD);
break;
case 8:
star.setType(CartoonType.FISH);
break;
case 9:
star.setType(CartoonType.DUCK);
break;
case 10:
star.setType(CartoonType.RAT);
break;
}
popularityNumber(keyboard, star);
}
public static void popularityNumber(Scanner keyboard, CartoonStar star) {
System.out.println("What is the cartoon popularity number?");
int popularity = keyboard.nextInt();
star.setPopularityIndex(popularity);
System.out.println(star.getName() + star.getType() + star.getPopularityIndex());
}
}
Your program runs forever because calling nextInt without changing the state of the scanner is going to cause an exception again and again: if the user did not enter an int, calling keyboard.nextInt() will not change what the scanner is looking at, so when you call keyboard.nextInt() in the next iteration, you'll get an exception.
You need to add some code to read the garbage the user entered after servicing an exception to fix this problem:
try {
...
} catch(Exception e) {
System.out.println("Error: invalid input:" + e.getMessage());
again = true;
keyboard.next(); // Ignore whatever is entered
}
Note: you do not need to rely on exceptions in this situation: rather than calling nextInt(), you could call hasNextInt(), and check if the scanner is looking at an integer or not.

Categories

Resources