public static void date1() {
int x = 0 ; //integer for looping
do // process to follow if length == 5
{
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please enter the first date ");
System.out.println("Please enter the year: ");
y1 = scanner.nextInt();
System.out.println("Please enter the month: ");
m1 = scanner.nextInt();
System.out.println("Please enter the day: ");
d1 = scanner.nextInt();
} catch (InputMismatchException inputMismatchException) {
scanner.nextLine();
System.err.println("You must enter intergers. Please try again. ");
}
x = x + 1 ; // set loop to three attempts
} while (x < 3) ; //do process occurs while attempts are under < 4
}
i want to break the loop if the all the inputs are proper (integers entered). I am not too sure what command to use to break the loop i created.
thanks in advance everybody!
Put a break command before you close your try{} block. If no exception is thrown, the break command will be executed and exit the loop.
A better way to do it, though, is to make a separate method that accepts a single input from the user, then call it three times. This way, you don't have to make the user input the first two numbers again if only the third one wasn't valid:
private static int getIntInput(){
while(true){
try{
return scanner.nextInt();
} catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
}
}
}
public static void date1(){
int x=0;
System.out.println("Please enter the first date ");
System.out.println("Please enter the year: ");
y1 = getIntInput();
System.out.println("Please enter the month: ");
m1 = getIntInput();
System.out.println("Please enter the day: ");
d1 = getIntInput();
}
You could, of course, make things more fancy... we could add a String input to the getIntInput() method, and then print that string every time we are accepting an input, so the user doesn't forget what he's trying to enter. Or you could clean up the syntax so it works (I think the compiler will complain that getIntInput needs to return an int, the way I typed it up right now...)
You could add a variable boolean stop = false and then modify your while to be while( x < 3 || stop == true). Then add some code to set stop = true once you are satisfied with your inputs.
Here's a hint: "break" out of the loop when all the inputs are proper.
Related
I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...
Is there a problem in my while or for loops by chance or am I missing something? First run through works fine but on the second I get this:
Enter course NAME: class name
Enter course HOURS: 4
Enter course GRADE: 4.0
You have entered class: jeff graves, class hours: 4 and, class grade 4.0
Do you want to continue:
y
Enter course NAME: Enter course HOURS:
It works just fine using (scanner).next(); but then I can only take one word from the user and it will throw an error from the nextInt when it rolls over.
public class GetGrades { //open class GetGrades
public static void main(String[] args) {
/**creating new instance of scanner named input to read user input*/
Scanner input = new Scanner(System.in); // create new instance of scanner object
boolean repeat = true; //boolean value for while loop holding array input
String s; // create string to store user input value for exiting loops
/** create 3 arrays to store course name, hours, and grades*/
String[] name = new String[20]; //type string array for class name
int[] hours = new int[20]; // type int array for class hours
float[] grade = new float[20]; //type float array for class grade
outerloop: // set break point for nested for loops exit on user input
while(repeat != false) {// while loop with boolean value to let user exit array input
for (int i=0; i<name.length; i++) { //for loop for name array
System.out.print("Enter course NAME: "); //prompt user for input
name[i] = input.nextLine(); //read next line value and store in array name
System.out.print("Enter course HOURS: "); //prompt user for input
hours[i] = input.nextInt(); //read the next int and store in array hours
System.out.print("Enter course GRADE: "); //prompt user for input
grade[i] = input.nextFloat(); //read the next float value and store in array grade
/**Print line to console summing um what the user has entered*/
System.out.println("You have entered class: " + name[i] + ", class hours: " + hours[i] +
" and, class grade " + grade[i]);
/**prompt user if wanted to enter more grades, break loop on n or N*/
System.out.println("Do you want to continue:");
s = input.next();
if ( s.equals("y") || s.equals("Y")) { //open if statement
repeat = true;
} else { //close if and open else
break outerloop;
} //close else statement
}//close for loop with i as count
}//close while
input.next() will read the next word. input.nextLine() will read up until the next time you press enter.
This means that when you write "y" and hit enter, you've input both a word "y", as well as the next enter, filling in both prompts at the same time and causing the next prompt to be written.
You can simply replace your next() with nextLine() when you ask to continue:
System.out.println("Do you want to continue:");
s = input.next();
becomes
System.out.println("Do you want to continue:");
s = input.nextLine();
thereby reading both the "y" and the enter. The next prompt is now free to accept new input.
When you input the grade, for example 12.3 and enter, "input.nextFloat();" will only take "12.3" but not "enter", so "enter" will be taken by the next scanner.
In my opinion,
first, change "s = input.next()" to "s = input.nextLine()", but it will take the "enter" of previous scanner "grade[i] = input.nextFloat();", so, second, put it into a while loop as a condition. like this
while((s = input.nextLine()).equals("")) {}
therefore, it won't stop til get the expect input.
try this..
System.out.print("Do you want to continue:");
while((s = input.nextLine()).equals("")) {}
if (s.equals("y") || s.equals("Y")) { // open if statement
repeat = true;
} else { // close if and open else
break outerloop;
} // close else statement
I am writing a simple bank application. In my program I have used a while loop. In case a user enters wrong input it will re-prompt to enter again.
Now the problem is I am not able to write any system.out.print statement after the loop. It always shows error (says: unreachable statement), and eventually the line doesn't get printed out.
HOW CAN I FIX THIS?
[The reason I need to use system.out.print because I want to print all the info the user has input.]
The program I am working on:
package bankapplication;
import java.util.Scanner;
public class BankApplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("WELCOME TO OUR BANK!\n\nPlease give all the inofrmation correctly.");
System.out.println("Enter your name: ");
String name = input.nextLine();
System.out.println("");
System.out.println("Enter your SSN: ");
String ssn = input.next();
System.out.println("");
System.out.println("Enter your Address: ");
String address = input.next();
System.out.println("");
System.out.println("Enter your telephone nr: ");
String teleNum = input.next();
System.out.println("");
while (true) {
System.out.println("Choose an account number for you (Between 5 and 10 positive numbers): ");
int accNum = input.nextInt();
System.out.println("");
if (accNum < 0 && accNum > 10 && accNum < 6) {
System.out.println("Invalid choise!");
} else {
System.exit(0);
}
}
System.out.println("Congratulation! Your new account has been created!");
System.out.println("The following is your account info:\n");
System.out.println("name: " + name + "SSN: " + ssn + "Address: " + address + "Tele. Num: " + teleNum + "Acc num: " + accNum);
}
}
When you invoke System.exit the entire program exits and the process is terminated. Instead you could replace the else statement with:
else { break; }
That will break the current loop and the rest of the statements will be printed. The keyword break simply breaks the loop.
You have a while (true) loop - a loop which is infinite unless something in the loop breaks out of it. The only line you have that breaks out of the loop is System.exit(0), which will end your program entirely. Therefore it is impossible to reach the code after your loop.
If you mean to break out of the loop in your else clause, use a break statement instead of exiting the program.
Note however that your if condition will never be true.
if (accNum < 0 && accNum > 10 && accNum < 6) {
accNum can never be less than zero and greater than 10.
You need to figure out what condition you actually want to check.
the condition
(accNum < 0 && accNum > 10 && accNum < 6)
can never be acheived , there is no way a number can be negative and >10 at the same time...the System.exit(0) will always be called on first loop.
That and when u call System.exit(0) you are exiting the program not the loop, therefor you will never reach the statement you are talking about .
you should either use
break;
or if you would like more prestige, put the right condition in the while(condition) ... try not to get used to using break ;
If you do enter a value that isn't correct it prompts you to enter the right amount but after entering the right or wrong amount it simply ends the program. Sorry I should have mentioned earlier that the program goes on for 12 months. My problem is that once I've been prompted to enter the right amount for any given month after I've entered the wrong amount, the program takes my answer and ends, rather than taking the correct answer and moving on to the next month.
System.out.print("Please enter monthly kWh usage for month 1: ");
month1 = scan.nextInt();
do {
System.out.print(" Please enter a valid amount: ");
month1 = scan.nextInt();
} while (month1>10000 || month1<0);
System.out.print("Please enter monthly kWh usage for month 2: ");
month2 = scan.nextInt();
do {
System.out.print(" Please enter a valid amount: ");
month2 = scan.nextInt();
} while (month2>10000 || month2<0);
Your code is totally correct to "simply end the program" because there are no other lines of code to execute!
The first do while loop will take an input and store it in the variable month1 and then check if it is between 0 and 10000. If so, it will go out of the loop, otherwise it will run the loop again and again till you enter the value between 0 and 10000. Then the second loop will do the same with month2 variable.
After storing both the variables, the program will exit without doing anything, because there are no lines of code to execute. You will need to write some lines of code after this to do something.
P.S. Also, it is good practice to surround the nextInt() with try-catch block because entering a non-numeric value will cause the program to crash.
Edit:
Also, you need to remove the month1 = scan.nextInt(); and month2 = scan.nextInt(); lines because the do-while loop takes care of initialising the variables for the first time.
Maybe something like this is what you want. The do is what's messing you up, because if the first input meets your condition, the loops will still occur at least once. Just use a while loop
System.out.print("Please enter monthly kWh usage for month 1: ");
month1 = scan.nextInt();
while (month1 > 10000 || month1 < 0) {
System.out.print(" Please enter a valid amount: ");
month1 = scan.nextInt();
}
System.out.print("Please enter monthly kWh usage for month 2: ");
month2 = scan.nextInt();
while (month2 > 10000 || month2 < 0) {
System.out.print(" Please enter a valid amount: ");
month2 = scan.nextInt();
}
Edit: Running code
import java.util.Scanner;
public class Month {
public static void main(String[] args) {
int month1;
int month2;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter monthly kWh usage for month 1: ");
month1 = scan.nextInt();
while (month1 > 10000 || month1 < 0) {
System.out.print(" Please enter a valid amount: ");
month1 = scan.nextInt();
}
System.out.print("Please enter monthly kWh usage for month 2: ");
month2 = scan.nextInt();
while (month2 > 10000 || month2 < 0) {
System.out.print(" Please enter a valid amount: ");
month2 = scan.nextInt();
}
}
}
nextint() will throw an exception if the next characters aren't ints:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
Try using an exception block:
try {
...
}
catch( InputMismatchException e ) {
System.out.println( e.getMessage() );
e.printStackTrace();
}
First of all, when do you use do..while, you would not need to capture input outside the loop. This force you to enter the input twice, you can remove redundant statement.
Secondly, do you have any statement to executed after second do..while?
I suggest you to provide more details what do you want to achieve here?
I have this java code I created for a course. I have tried and continue to fail implement a break statement.
Can someone point me in the right direction?
import java.util.Scanner;
public class gradeAverage {
public static void main( String[] args ){
Scanner input = new Scanner(System.in);
int input1;
int input2;
int input3;
//Calculate
int studentAvg;
//Prompt for first user input or break if input = q
System.out.print( "Enter first student grade or q to quit: ");
if {
(input1=input.nextInt() = q)
break;
else
input1=input.nextInt() =;
}
//Prompt for second user input or break if input = q
System.out.print( "Enter second student grade or q to quit: ");
input2=input.nextInt();
//Prompt for third user input or break if input = q
System.out.print( "Enter third student grade or q to quit: ");
input3=input.nextInt();
studentAvg=(input1+input2+input3)/3;
System.out.printf( "The Student's grade average is %d\n" , studentAvg);
}
}
A break statement needs to be inside a loop or some sort (for, while, or do), you cannot break out of an if conditional.
If you put your code inside this:
while(true) {
...
}
Then your break would work fine.
Also the format of an if statement is:
if (condition) {
...
} else {
}
You seem to have a if { (condition) in your code...
Oh and = is an assignment of a value to a variable, == is an equality check, you have them mixed up.
First of all your syntax of If statement is totally wrong . That needs to be corrected.
Second this is that , Break statement is used to break a loop in between. So it should be used like
while{
................
Break;
................
}
or
For(.........){
Break;
........
}
//Assuming input is a scanner object.
System.out.print( "Enter first student grade or q to quit: ");
if ((input1=input.nextline()).equalsIgnoreCase("q")) //do you want to use == or =?
break;
else{
//do something
}
This should do the trick for you. Cheers.