Trying to setup break statement - java

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.

Related

Unable to break out of For Loop in Java

I am a beginner and was making a small program to practice what i have learnt.
I was writing code to check the grade of a student.
This is the code :
import java.util.*;
public class Grader {
public static void main(String[] args) {
String studentName;
int rollNo = 0;
Scanner inputter = new Scanner(System.in);
System.out.println("Please enter the roll number of the student: ");
rollNo = inputter.nextInt();
System.out.println("Thank you. Now, please enter the student's name: " );
studentName = inputter.next();
for(int i=0; ; i++){
System.out.println("Please enter a valid examination type, i.e FA or SA: ");
String examType = inputter.next();
examType = examType.toUpperCase();
if(examType == "FA" || examType == "SA"){
break;
}
}
}
}
The problem I am facing is that even though I enter a valid examType, the For loop doesn't break.
You need to use String.equals().
Scanner.next() returns a String. Using == on a string doesn't give any errors but will test reference equality instead of value equality. It won't return true even if the strings are equal in value.
Correct code:
if(examType.equals("FA") || examType.equals("SA")){
break;
}
EDIT
OP mentioned in a comment that the loop is to run without ending until hitting break. You can create an infinite loop in either of these two ways:
for(;;){
//runs infinitely
}
OR
while(true){
//runs infinitely
}
Both of these infinite loops are broken with break. Also, you use less memory (albeit a small and almost insignificant difference) because you don't have a counter variable. In the next-to-impossible case that the user enters invalid input so many times that the integer overflows, not having a variable eliminates this risk. You also save processor time because there isn't an instruction to allocate memory or add one to the number.
public static void main(String args[]) {
String studentName;
int rollNo = 0;
Scanner inputter = new Scanner(System.in);
System.out.println("Please enter the roll number of the student: ");
rollNo = inputter.nextInt();
System.out.println("Thank you. Now, please enter the student's name: " );
studentName = inputter.next();
for(int i=0; ; i++){
System.out.println("Please enter a valid examination type, i.e FA or SA: ");
String examType = inputter.next();
examType = examType.toUpperCase();
if(examType.equals("FA") || examType.equals("SA")){
break;
}
}
}
This is working fine.
You haven't set a limit, for example
for(int i = 0; i < somevalue; i++)
otherwise a while loop might be a better choice like:
while(examType.equals("FA") || examType.equals("SA")
For best coding practice the usage of equals operation for Strings like below code snippet as per Sonar compliance standard.
("SA".equals (examType))

Why is my for loop printing 2 of my prompts at one time while using (scanner).nextLine();

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

Why nothing gets printed after while loop?

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 ;

Do while loop not printing correctly after 1st loop

I am trying to do a do-while loop that makes the program iterate again after the user inputs "y" or "Y", but everytime i run the program, It prints out something like this:
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box] (I enter y)
Are you a student? (no input box is shown, and it skips it)
Are you a member of staff or faculty? [DrJava Input Box] (i enter yes or no)
How many tickets do you need? [DrJava Input Box] (I enter an int, but it doesnt complete that part where it shows how many tickets sold or how much it costs)
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box]
this is what my program looks like:
import java.util.Scanner;
public class Ticket
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double ticketprice = 12.00;
double result;
double result2;
double result3;
char repeat;
String input;
String student;
String staff;
int ticket;
do
{
System.out.println("Are you a student?");
student = keyboard.nextLine();
System.out.println("Are you a member of staff or faculty?");
staff = keyboard.nextLine();
System.out.println("How many tickets do you need?");
ticket = keyboard.nextInt();
if(student.equals("yes"))
{
System.out.println("Here is your " + ticket + " tickets for $0.00");
}
if(staff.equals("yes"))
{
result = ticketprice * .85;
result2 = ticket * result;
System.out.printf("Here are your " + ticket + " tickets for $%.2f\n", result2);
}
if(student.equals("no") && staff.equals("no"))
{
result3 = ticket * ticketprice;
System.out.printf("Here are your " + ticket + " tickets, for $%.2f\n", result3);
}
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
}
while(repeat == 'y' || repeat == 'Y');
}
}
i am a beginner to programming, so any help would be good. Thank you.
At the end of the loop you call next() to read the "try again" response. This reads the next token, but still leaves the line ending on the input stream.
Next time through the loop, when you call nextLine() to read the "are you a student" response, it simply reads the remainder of that line immediately.
The easiest solution is:
Use nextLine() instead of next() for your "try again" prompt, but then this means you'll have to take care of the line ending left by nextInt() in the "tickets" question, so then you'll also have to...
Use nextLine() instead of nextInt() for your "tickets" question, then use Integer.parseInt() to parse the string into an int.
An alternate option, since all your responses seem to be just single-word responses, is to use next()/nextInt() everywhere and not use nextLine() at all. The point is, when you mix the two, you have to be aware of how they interact.
The issue lies in this block of code:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
When you call keyboard.next(), it doesn't read the entire line, so when your program loops again, the next time you call keyboard.nextLine(), it takes in part of what you entered previously in the loop and it gets ahead of itself.
The best solution would be to add a keyboard.nextLine() after you call keyboard.next() so that the remainder of the line will be consumed and won't be left over to mess up future iterations of the loop.
So for example you could change it like this:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
keyboard.nextLine();
repeat = input.charAt(0);

How would I break the loop in this piece of my program?

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.

Categories