in try and catch when Enter invalid thing back from beginning i want correct the error and go to next - try-catch

import java.util.*;
public class TestBakery{
public static void main (String [] args)
{
Scanner read=new Scanner(System.in);
boolean OK=true;
int choice=0;
//loop and try-catch
while(OK)
{
try{
System.out.println("ِEnter name of bakery");
String nameBak=read.next();
System.out.println("Enter the max number of cookie");
int nm=read.nextInt();
Bakery b=new Bakery(nameBak,nm);
System.out.println("\n menue :");
System.out.println(" \n 1- To add \n 2- To sell Cookie \n 3-to disply");
System.out.println("Enter choice:");
choice=read.nextInt();
if (choice==1)
{
System.out.println("Enter number of calories:");
double calories=read.nextDouble();
System.out.println("Enter number quantity:");
int quantity=read.nextInt();
System.out.println("Enter Price: ");
double price=read.nextDouble();
System.out.println("Enter flavor:");
char flavor=read.next().charAt(0);
Cookie C1=new Cookie(flavor,calories,quantity,price);
if (b.addCookie(C1))
OK=false;
}
if (choice==2)
{
System.out.println("Enter flavor:");
char f=read.next().charAt(0);
System.out.println("Enter number quantity:");
int q=read.nextInt();
System.out.println("sellCookie is:");
if (b.sellCookie(f,q))
System.out.println(" OK");
}
if (choice==2)
{
System.out.println("Enter number of calories:");
double c=read.nextDouble();
b.displayByCalories (c);
}
}
catch(IllegalArgumentException e)
{
System.out.println(e);
read.next();
}
catch(InputMismatchException e)
{
System.out.println(e);
read.next();
}
}
}
}
//the problem is that when Enter invalid thing back from beginning
but i want correct the error and go to next
(for example ) this sample run :
ِEnter name of bakery
sss
Enter the max number of cookie
30
menue :
1- To add
2- To sell Cookie
3-to disply
Enter choice:
1
Enter number of calories:
30
Enter number quantity:
3
Enter Price:
4
Enter flavor:
g
java.lang.IllegalArgumentException: please Enter valid flavor V ,C or P
P
ِEnter name of bakery:
...

If I understand your question properly, you are trying to use exceptions as a flow control mechanism. Which is, not to put too fine a point on it, wrong.
Even if you succeeded, it would be ugly.
That being said, if you insist, you need to wrap each question section with a try catch and a loop separately.

Related

Have loop repeat after invalid entry

All calculating is fine. I run into a problem when I get an invalid entry and the user enters a new positive integer. It doesn't start the loop over again. Any advice is greatly appreciated!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int start;
int i;
double squareRoot;
System.out.println("Please enter a positive integer: ");
start = in.nextInt();
if (start > 0){
do {
squareRoot = Math.sqrt(start);
start--;
System.out.printf("%.4f", squareRoot);
System.out.println();
}
while (start >= 0);
}
else {
System.out.println("The number you entered is not a postive integer.");
System.out.println("Please enter an integer greater than zero: ");
start = in.nextInt();
}
}
}
If you need to go over the same steps over and over, you need a loop. So add a while loop with a simple condition and get it going over and over.
Here is a sample code. I had to give an option to quit, so took -1 as the cue.
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int start;
int i;
double squareRoot;
System.out.println("Please enter a positive integer: ");
boolean quit = false;
while (!quit) {
System.out.println("Enter the integer");
start = in.nextInt();
if (start > 0){
do {
squareRoot = Math.sqrt(start);
start--;
System.out.printf("%.4f", squareRoot);
System.out.println();
}
while (start >= 0);
}
else if (start == -1) {
quit = true;
}
else {
System.out.println("The number you entered is not a postive integer.");
System.out.println("Please enter an integer greater than zero: ");
}
}
}
}

This loop to modify a arraylist of numbers based on arraylist of strings isnt working

So, in my program you input employee information and the salary you input depends on what you input for designation. If temporary, yo input how much they make per hour, if permanent you input what they make per year. At the end, you have the option to sort by salary, so if they choose that then I must multiply the temporary's per-hour by a set number (1920) in order to convert it to what they make per year. I tried this but I got the messages
" The type of the expression must be an array type but it resolved to java.util.ArrayList"
and "The type of the expression must be an array type but it resolved to java.util.ArrayList", I got that second one twice.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String Continue = "y";
int Count = 0;
int SortingChoice;
ArrayList<String> Names = new ArrayList<String>();
ArrayList<String> Department = new ArrayList<String>();
ArrayList<String> Designation = new ArrayList<String>();
ArrayList<Float> Salary = new ArrayList<Float>();
//******************************************************//
do
{
System.out.println("Enter Employee Name: ");
String x = in.next();
Names.add(x);
System.out.println("Enter Employee Designation ('temporary or permanent'): ");
String y = in.next();
Designation.add(y);
System.out.println("Enter Employee Department: ");
String z = in.next();
Department.add(z);
System.out.println("Enter Employee Salary: ");
float i = in.nextFloat();
Salary.add(i);
System.out.println("Do you wish to add another employee? ('y'/'n'): ");
Continue = in.next();
Count = Count + 1;
}
while(Continue.equals("y"));
//***********************************************************************//
System.out.println("Enter sorting Criterion Number: 1. Name, 2.Department, 3. Salary. ");
SortingChoice = in.nextInt();
if(SortingChoice == 1)
{
Collections.sort(Names);
for(int i=0; i<Names.size(); i++)
{
System.out.println(Names.get(i));
}
}
if(SortingChoice == 2)
{
Collections.sort(Department);
for(int i=0; i<Department.size(); i++)
{
System.out.println(Department.get(i));
}
}
if(SortingChoice == 3)
{
for(int k=0; k<Salary.size(); k++)
{
if(Designation[k].equals("temporary"))
{
Salary[k] = Salary[k]*1920;
}
}
Collections.sort(Salary);
for(int i=0; i<Salary.size(); i++)
{
System.out.println(Salary.get(i));
}
}
}
What I am most concered about if the loop under if(SortingChoice==3)

Create for loop in Java to take in information

I want to use a for loop to ask the user for a movie title, genre and rating and get for it to iterate three times and store in an array and display the information back to the user.
In the for loop in the code, I am not sure what to insert as "Movie 1" and how to get it to change to "Movie 2" and "Movie 3" after each iteration.
This is what I have so far :
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Creates a Movie array of size three.
Movie[] movies = new Movie[3];
for (int i=0; i < movies.length; i++) {
// Initialises the 3 movie objects in the array.
movies[i] = new Movie();
}
// Loop will execute 3 times.
for (int x = 0; x < 3; x += 1){
System.out.println("Please enter the title of Movie 1: ");
System.out.println("Please enter the genre of Movie 1: ");
System.out.println("Please enter the rating of Movie 1: ");
}
}
Please post your Movie class to help us suggest a more detailed answer.
you can try something like this ...
Scanner sc=new Scanner(system.in);
for (int x = 0; x < 3; x++){
System.out.println("Please enter the title of Movie 1: ");
movies[i].title=sc.next();
System.out.println("Please enter the genre of Movie 1: ");
movies[i].genre=sc.next();
System.out.println("Please enter the rating of Movie 1: ");
movies[i].genre=sc.nextInt();
}
Use x++ instead of x+=1 , try using enhanced for loop in Java , and import java.util.* for the Scanner to work
You did most of the stuff right, just that you need to figure out what to do when as explained in comments below:
Scanner input = new Scanner(System.in);
// Creates a Movie array of size three.
//here you are declaring your array of movies of size 3
Movie[] movies = new Movie[3];
String name;
//lets ask user to enter movie name three times and simultaneously populate movie object and store them in an array.
for (int i=0; i < movies.length; i++) {
System.out.println("Please enter the title of Movie " + (i+1));
name = input.nextLine();
movies[i] = new Movie(name);
}
// Loop will execute 3 times and just print out the movie names that we populated.
for (int x = 0; x < movies.length; x += 1){
System.out.println("movie " + (x+1) + " is " + movies[x].name);
}

reached end of file while parsing,

what is wrong with this , i am getting an error that states: reached end of file while parsing. what do i do to fix this?
i have tried several thing with no result
public class FindMin
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int smallest = 9999999;
String userInput;
boolean quit = false;
System.out.println("This program finds the smallest number"
+ " in a series of numbers");
System.out.println("When you want to exit, type Q");
while(quit != true)
{
System.out.print("Enter a number: ");
userInput = keyboard.next();
if(userInput.equals("Q")) userInput.equals("q");
{
if(quit == true) {
}
else
{
int userNumber = Integer.parseInt(userInput);
if(UserNumber < smallest)
smallest = userNumber;
}
}
System.out.println("The smallest number is " + smallest);
System.exit(0);
}
Check your braces: they don't match up, which is why the compiler complains:
FindMin.java:35: reached end of file while parsing
Besides there's a typo and some other issues with that program. See other answers for reference :)
It was just too messy, try this
import java.util.Scanner;
public class FindMin{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int smallest = 9999999;
String userInput;
boolean quit = false;
System.out.println("This program finds the smallest number"
+ " in a series of numbers");
System.out.println("When you want to exit, type Q");
while(true)
{
System.out.print("Enter a number: ");
userInput = keyboard.next();
if(userInput.equalsIgnoreCase("q"))
break;
else{
int userNumber = Integer.parseInt(userInput);
if(userNumber < smallest)
smallest = userNumber;
}
}
System.out.println("The smallest number is " + smallest);
}
}

Else-If / While Loop stuck

I'm trying to make a program that takes input of a minimum and a maximum number and then generates a random number in that range. Then the user guesses a number and if it's too high, it outputs a messege.. If it's too low, it outputs a message. The part that i'm stuck at is when you guess the number correctly, the user inputs "Y" or "N" to run the program again.
My code is as follows:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame_V2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print('\u000C');
int min;
int max;
int userGuess;
int numberGuesses = 1;
System.out.println("Enter the minimum number: ");
min = in.nextInt();
System.out.println("Enter the maximum number: ");
max = in.nextInt();
Random r = new Random();
int randomNumber = r.nextInt(max - min + 1) + min;
System.out.println("Enter your guess: ");
userGuess = in.nextInt();
String guessAgain = ("Y");
while(!guessAgain.equalsIgnoreCase("N"))
{
if( userGuess > randomNumber ){
System.out.println("Your guess was to high! Guess again!");
System.out.println("Input your new guess: ");
userGuess = in.nextInt();
numberGuesses++;
}
else if (userGuess < randomNumber ){
System.out.println("Your guess was to low! Guess again!");
System.out.println("Input your new guess: ");
userGuess = in.nextInt();
numberGuesses++;
}
else
{
System.out.println("Congratulations, you guessed the number!");
System.out.println("It took " + numberGuesses + " tries");
System.out.println("Guess another number? (Y/N)");
guessAgain = in.next();
}
}
System.out.println("Thank's for playing!");
}
}
The problem comes when the user hits "Y" to restart the program. It doesn't restart and just displays the final message again. (print statement, number of guesses, and Y/N). I need the program to restart when the user types "Y"
I'm new to posting on the site.. so forgive me if I messed up putting in the code -
Thanks in advance for the help -
*Changes - 11/13/13 10:58 Changed the code to take more than one input and to
keep taking input until the user gets it right.
You need nested loops because you are doing two repetitive actions--first is repeating the game and second is prompting for guesses within one game.
So use nested loops. One loop prompts the user if he or she wants to play and prompts the user again with the same question at the end. The nested loop should be as you have it.
Your code should be along the lines of
while (stillPlaying) {
while (stillGuessing) {
}
}
Hope that helps.

Resources