Have loop repeat after invalid entry - loops

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: ");
}
}
}
}

Related

It should continue to accept a price of an item and displays the current total while the user input is not equals to zero

/* I need some help. I'm stuck with this code. It should continue to accept a price of an item and displays the current total while the user input is not equal to zero. However, output for the current total won't show the current amount. */
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String customerName;
char promtSenior;
int num = 1;
double itemPrice;
double currentTotal = 0;
ArrayList<Double> amounts = new ArrayList<Double>();
System.out.print("Please enter customer name: ");
customerName = scanner.nextLine();
while (true) {
System.out.print("Please enter item " + num++ + " price or 0 to quit: ");
itemPrice = scanner.nextDouble();
amounts.add(itemPrice);
scanner.nextLine();
for (double i : amounts) {
currentTotal = currentTotal + i ;
}
System.out.println(currentTotal);
if (itemPrice == 0) {
System.out.println("Are you a Senior Citizen? [Y/N]: " + customerName);
promtSenior = scanner.next().charAt(0);
if (promtSenior == 'N') {
System.out.println("No Discount");
}
}
}
}
}
while (true) {
System.out.print("Please enter item " + num++ + " price or 0 to quit: ");
itemPrice = scanner.nextDouble();
amounts.add(itemPrice);
scanner.nextLine();
for (double i : amounts) {
currentTotal = currentTotal + i ;
System.out.println(currentTotal);
}
should be this as previously you where printing the total after the for loop not during
i think you accidentally messed up your curly brackets and indented before

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)

My program wont catch an exception

Why wont this code catch the error if the user inputs a negative number?
public class Lab12 {
public static void main(String[] args) {
Course[] course1 = courses();
print(course1);
}//end main
public static Course[] courses() throws IllegalArgumentException{
Scanner input = new Scanner(System.in);
System.out.println("How many courses?");
int numCourses = input.nextInt();
Course[] array = new Course[numCourses];
int s = 0;
boolean b = true;
for(int i = 0; i<numCourses; i++){
System.out.println("Enter the course title.");
String t = input.nextLine();
t = input.nextLine();
System.out.println("Enter the corresponding major.");
String m = input.nextLine();
do{
try{
System.out.println("Enter the number of students taking this course.");
s = input.nextInt();
b = false;
}//end try block
catch(IllegalArgumentException ex){
System.out.println("Input error."+
"\nPlese enter a positive number for students.");}//end catch
}while(b);
//Right here I dont see why my try catch wont work
Course c = new Course(t,m,s);
array[i] = c;
}//end for loop
input.close();
return array;
}//end courses method
public static void print(Course[] c){
for(int i = 0; i<c.length; i++){
System.out.println("Course title: "+c[i].getTitle()+
"\nMajor: "+c[i].getMajor()+
"\nNumber of Students: "+c[i].getStudents());
}//end for loop
}//end
}//end lab12
Here is the class associated with the main:
public class Course {
private String title;
private String major;
private int students;
public Course(String t, String m, int s){
title = t;
major = m;
students = s;
if(students<0){
throw new IllegalArgumentException("Wrong Argument.");
}
//my instruction were to throw an exception in the constructor is this correct
}//end constructor method
public String getTitle(){
return title;
}//end get title
public String getMajor(){
return major;
}//end get major
public int getStudents(){
return students;
}//end get students
public void setTitle(String t){
title = t;
}//end set title
public void setMajor(String m){
major = m;
}//end set major
public void setStudents(int s){
students = s;
}//end set students
}//end Class Course
In order to catch an exception in Java, you need to surround the code that throws the exception in a try/catch block.
Change your main for loop to something like this:
for(int i = 0; i<numCourses; i++){
System.out.println("Enter the course title.");
String t = input.nextLine();
t = input.nextLine();
System.out.println("Enter the corresponding major.");
String m = input.nextLine();
// Need to declare the Course object outside of the do/while so that it stays
// in scope afterwards
Course c = null;
do{
try{
System.out.println("Enter the number of students taking this course.");
s = input.nextInt();
b = false;
// Create the Course here so that the try/catch will correctly catch
// the IllegalArgumentException
c = new Course(t,m,s);
}//end try block
catch(IllegalArgumentException ex){
System.out.println("Input error."+
"\nPlease enter a positive number for students.");
}//end catch
} while(b);
array[i] = c;
}//end for loop

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