I am a freshman in college, currently in my first semester of my Computer Programming course; we have started by working with pseudo code and Java simultaneously.
We had been tasked with the creation of a java application that totals, and creates an average, of a series of numbers that have been input by the user. The user may input as many numbers as they wish until the number 0 is input, in which case the program outputs the total and the average, and then prompts the user to start over or exit the program.
I accomplished this task using two while loops, one of which is nested. When attempting to break the nested loop, however, I receive the error "Error: break outside switch or loop". Afterwards, I spent much time browsing this forum looking for answers and information concerning the problem, but none seemed relevant to my problem, and fixes did not work. Among the list was using labeled breaks and correcting curly brackets; because these did not seem to work, I'm convinced the problem lies deeper in the code.
Because my course is online, it is very difficult to communicate with the professor or other students in a timely manner, which is why I have turned to this community!
Below I will attach the pseudo code that the professor wanted us to base our application off of.
Start
Declarations
Num sumTotal = 0 // Initialize for clarity
Num numEntered
Num averageNum
Num loopCounter
Num answer
String endProgram = “Y” // Initialize so that outer loop will work
End declarations
// Greet the user
Output “Welcome to our calculator. “
Output “Enter as many numbers as you want.”
Output “When you are done entering numbers, enter 0 (zero) to display the sum.”
Output “Do you want to start the calculator? (Y/N): “ // Let the user decide to start
input endProgram
// Note: if the user enters anything but Y or y, the loop will not execute.
While endProgram <> “Y” OR endProgram <> “y” // Allows the user to perform multiple calculations
//Enter the first number (sentinel value)
Output “Please enter your first number.”
Input numEntered
While numEntered <> 0 // Allows the user to enter numbers for the current calculation
Output “You entered the number “ + numEntered // echo input
sumTotal = sumTotal + numEntered // Add number entered to total
loopCounter++ // Increment the number of entries
Output “Please enter the next number”
Input numEntered // If 0, the loop will end here
endWhile // the nested inner loop code stops here
// Output section
Output “The total numbers entered is: “ + loopCounter
Output “The total of the numbers entered is: “ + sumTotal
Output “The average of the numbers entered is: “ + averageNum
Output “Would you like to do a new set of calculations? Y/N
Input endProgram
End While // End outer While statement when endProgram = Y
Output “Thank you for using the calculator. The program will now end.”
Stop // Stop the program
Below I will attach my Java code
/* Module 4 Assignment 1 Part 1
* Aaron Field
* Submitted March 26, 2016
* Using DrJava */
import javax.swing.JOptionPane;
public class Calculator {
public static void main(String[] args) {
//variable declarations
int numEntered;
int sumTotal = 0;
int averageNum = sumTotal / numEntered;
int loopCounter;
String endProgram = "Y";
//end declarations
System.out.println("Welcome to the Totaling Calculator");
System.out.println("This program will accept integer inputs until 0 is entered" + '\n' + "When 0 is entered, a sum and an average will be displayed.");
endProgram = JOptionPane.showInputDialog(
"Do you want to start the calculator? (Y/N): ");
while(endProgram != "Y" || endProgram != "y"); {
numEntered = Integer.parseInt(JOptionPane.showInputDialog(
"Please enter your first number."));
while(numEntered != 0); {
System.out.println("You entered the number " + numEntered);
sumTotal = sumTotal + numEntered;
loopCounter++;
numEntered = Integer.parseInt(JOptionPane.showInputDialog(
"Please enter the next number"));
break;}
System.out.println("The total numbers entered is: " + loopCounter + '\n' + "The total of the numbers entered is: " + sumTotal + '\n' + "The average of the numbers entered is: " + averageNum);
endProgram = JOptionPane.showInputDialog(
"Would you like to do a new set of calculations? (Y/N): ");
break;
}
System.out.println("Thank you for using the calculator. The program will now end.");
}
}
I understand the code may be sloppy or strange, but I've only been working with Java for since mid-February, so excuse any sloppy formatting or incorrect use of code.
To my untrained eyes, the break statements seem to be within the loops; I am rather confused as to why my compiler would suggest they aren't. Any help would be GREATLY appreciated, thank you.
while(...); it's a bad practice :P. Your break commands are in fact all outside the while loops.
Remove the semicolons after your while statements.
Example: change
while(endProgram != "Y" || endProgram != “y”); {
//...
}
to
while(endProgram != "Y" || endProgram != “y”) {
//...
}
A while statement followed by a semicolon is actually interpreted as this
while(condition) {}
Related
I keep trying to get this to work but when I enter in the numbers and enter them into the console it does not finish. I have to terminate myself.
import java.util.Scanner;
public static void main(String[] args) {
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (keyboard.hasNextInt());
System.out.println(outputSum);
}
Well, yes. The keyboard.hasNextInt() call will return false for two reasons.
The next token is a NOT an integer.
You have reached the end-of-input.
What is (most likely) happening is that you have stopped entering numbers. The program is (patiently) waiting for you to enter ... something.
Solutions:
Tell the user to enter the (OS specific) terminal "end of file" character. On Linux it is CTRL-D. On Windows CTRL-Z.
Tell the user to enter something that isn't an integer.
Pick an integer as meaning that there are no more numbers, and test for that.
You also need to instruct the user how to "end" the sequence; e.g.
System.out.println("Enter sequence of numbers. Enter a non-number to stop.");
This is actually a problem with your application's "user interface" design. If the user is expected to type an arbitrarily long sequence of numbers (or something else), then there needs to be some way for the user to tell the program that the sequence is finished. The program cannot magically distinguish the cases of "there are no more" and "hang on, I'm taking a break from typing".
The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.
In this case hasNext() won't return true because there is neither any integer nor any whitespace. Therefore the program waits for the next input. Besides use a specific integer to break the loop.
for instance,
System.out.println("Input -1 will end the program!";
do{
int x = keyboard.nextInt();
if(x == -1){
break;
}
//do something
}while(true);
Your code is ok. There is no issue.
But before writing code, we need to think about it. The workflow of your code below:
1st time when we enter do loop, keyboard.nextInt() takes input from us.
Then it calculates the sum and performs string operation.
After that, while's keyboard.hasNextInt() takes next input from you.
Checks your input. If your input is not an integer, while loop will terminate(break).
If your input is an integer then, code loop back to keyboard.nextInt(). But this time, it does not take input from you.
It pases the buffered input(keyboard.hasNextInt()) to keyboard.nextInt() and assign the value to inputNum
So, when you want to terminate while loop, you should input any character like a, b, c, etc.
You haven't specified when the loop will end. Have a condition such as inputting a certain number that will end the program once entered, as currently your program is just going to wait for more input. Something like :
System.out.println("Enter sequence of numbers to add. Enter '0' to end the program");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (inputNum != 0);//Keeps going as long as 0 is not entered
//When zero is entered, program shows the total sum and terminates
if (inputNum == 0) {
System.out.println("The sum of all total numbers: ");
System.out.println(outputSum);
System.exit(0);//Terminates program
}
Basic syntax of do-while Loop:
do{
// do something
}while(terminating condition);
If you are using hasNextInt() method of Scanner object for terminating condition in do-while loop then loop will be terminated once it get input other than an integer value (e.g float, double, char, String etc.. ) as shown in below complete program.
import java.util.Scanner;
public class Cumulative{
public static void main(String[] args){
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do{
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
}while (keyboard.hasNextInt()); // loop will terminated whenever get any value other than valid integer such as float char or String etc..
System.out.println(outputSum);
}
}
here is my code
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] data = new int[10];
int count = 0;
do {
System.out.print("Enter a number or ctrl + z when you are done: ");
data[count] = input.nextInt();
}
while (input.hasNextDouble());
}
}
output
Enter a number or ctrl + z when you are done: 2
4
Enter a number or ctrl + z when you are done: 6
Enter a number or ctrl + z when you are done: 8
My question is i don't know why the code jumps the System.out.print("Enter a number or ctrl + z when you are done: "); after do { when entering the loop the second time. This can be seen in second line of the output. Please what are my doing wrong?
I have searched for cases where my question might have already been answered but was only able to find solutions relating to code skipping nextLine()
The reason is first time do block is executed and then check for condition in while.
About hasNextDouble() in orcale doc:
Returns true if the next token in this scanner's input can be
interpreted as a double value using the nextDouble() method. The
scanner does not advance past any input.
As a solution you can change the condition like below:
do {
System.out.print("Enter a number or ctrl + z when you are done: ");
data[count] = input.nextInt();
count++;
}
while (count < 10);
Also:
If you are using input.nextInt();, better to check using hasNextInt().
ah your while loop is waiting to see if input hasNextDouble()
how can it know until your user has entered the next double or hit ctrl-z?
you'll have to do something Ugly like
System.out.print("Enter a number or ctrl + z when you are done: ");
do {
data[count++] = input.nextInt();
System.out.print("Enter a number or ctrl + z when you are done: ");
}
while (input.hasNextDouble());
note the count++ above as well i think it fixes another bug.
This happens because the first call to input.hasNextDouble() waits for a number to be entered before proceeding.
So the message in the second iteration of the loop won't appear until input.hasNextDouble() at the end of the first iteration of the loop has run - which of course fetches the second number.
You need to print the message before you call either hasNextDouble or hasNextInt.
Trying to design a simple lottery program. Everything works except checking if the numbers entered are between 1 to 59.
Exercise says the numbers must be stored in a String variable.
so
if(num<0 || num>59) //wont work for me
Tried making another variable
int numConverted = Integer.parseInt(num)
We haven't covered converting String to int in class though so I don't think this is what expected. Got confused trying that way anyway so probably this is wrong.
Here is the code I have currently.
{
Scanner scan = new Scanner(System.in);
String num=""; //num variable is empty untill user inputs numbers
for(int i =0; i<6; i++)
{
System.out.println("Enter your number between 1-59");
num = num +" "+ scan.nextLine();
}
System.out.println("Ticket printed £2. Your numbers are " + num);
}
In your posted code it's obvious that you want the User to supply 6 specific numerical values. These values are appended to the String variable named num (space delimited). You need to obviously do a few things here:
1) Make sure the value supplied by the user is indeed a numerical value;
2) Make sure the numerical values supplied fall within the minimum and maximum scope of the lottery itself (which you have stated is: 1 to 59);
3) Make sure the number entered by the User hasn't been supplied already.
You've been tasked to store the entered values into a String data type variable and that is all fine but at some point you want to carry out value comparisons to make sure that all the entered values actually play within the limits of the lottery.
When the User completes his/her entries, you end up with a space delimited string held in the num string variable. You now need to make sure that these values entered are indeed....numbers from 1 to 59 and none contain alpha characters.
In my opinion (and this is only because you need to store entered values into a String variable), it's best to use your String variable to gather User input, then test the input to make sure it is indeed a string representation of an actual integer number. Once this is established then we test to make sure if falls within the value min/max limits (1-59). Now we need to test to make sure the number entered hasn't already been entered before for this ticket.
Of course with each test described above, if one fails then the User should be prompted to re-enter a proper value. You can do this by utilizing a while loop. Plenty examples of this in StackOverflow but here's a quick example:
Scanner scan = new Scanner(System.in);
String ticketNumbers = "";
for(int i = 0; i < 6; i++) {
Boolean isOK = false;
while (!isOK) {
System.out.println("\nPlease enter your desired 6 ticket numbers:\n"
+ "(from 1 to 59 only)");
String num = scan.nextLine();
//Is the string entered an actual integer number?
//We use the String.matches() method for this with
//a regular expression.
if(!num.matches("\\d+")) {
System.out.println("You must supply a numerical value! "
+ "Try Again...");
continue;
}
if (ticketNumbers.contains(num + " ")) {
System.out.println("The number you supplied has already been chosen!"
+ " Try Again...");
continue;
}
if (Integer.parseInt(num) >= 1 && Integer.parseInt(num) <= 59) {
ticketNumbers+= num + " ";
isOK = true;
}
else {
System.out.println("The number you supply must be from "
+ "1 to 59! Try Again...");
}
}
}
System.out.println("Ticket printed £2. Your numbers are " + ticketNumbers);
How about -
if(Integer.parseInt(num) < 0 || Integer.parseInt(num) > 59)
This should work, place it after the input.
If it works, please mark this as correct, I need the rep!!!
Easy way would be add available numbers (suppose it wont grow more than 60. You can use a loop to add to this as well)
String numbers[] = {"1","2","3", "..."};
Then inside the loop
Arrays.asList(numbers).contains(num);
You can remove prefixing zero in order avoid conflicts with values like '02'
Here everything is String related.
If you don't want to explicitly convert to int, you could use a regular expression.
if (num.matches("[1-5]?[0-9]")) {
...
This checks whether the String consists of (1) maybe a digit from 1 to 5, followed by (2) definitely a digit from 0 to 9. That'll match any number in the range 0-59.
If you've got a whole series of numbers separated by spaces, you could expand this to cover a whole series like this.
if (num.matches("([1-5]?[0-9]\\s+)*[1-5]?[0-9]")) {
This matches any number of repetitions (including zero) of "a number followed by spaces", followed by a single repetition without a space. The "\\s" means "any whitespace character", the "+" after it means "one or more of what precedes", and the "*" means "zero more of what precedes" - which in this case is the term in parentheses.
Oh I see what you are trying to do
This is what you want
Scanner scan = new Scanner(System.in);
String allNums = "";
for(int i =0; i<6; i++)
{
System.out.println("Enter your number between 1-59");
int num = scan.nextInt();//Take the number in as an int
if(num >0 && num < 59)//Check if it is in range
{
allNums += num + " ";//if it is add it to a string
}
else
{
System.out.println("Number not in range");
i--;//go back one iteration if its not in range
}
}
System.out.println("Ticket printed £2. Your numbers are " + allNums);
So I'm new to java programming, coming from Python, and there's a few concepts that I can't quite understand.
I'm writing a program which allows the user to enter as many numbers as they want and the program should output the average of all of the numbers. I used a while loop to loop through the inputs by the user as many times as they wanted, but I needed a way of exiting the loop so that the program could proceed with calculating the average of all of the inputs. I decided that if the user enters an "=" sign instead of a number, then the program would break out of the loop, but since the Scanner variable was looking for a double, and the "=" sign is not a number, I would have to make it a String. But because the Scanner is looking for a double, the program threw an error when it encountered the "=".
How can I get the program to exit the loop when the user types "="? I know I could just allow the user to enter a number that breaks the loop, but if it was a real world program and the user entered a number, it would count that number along with the previous ones when calculating the average. The code I have so far is as follows:
import java.util.Scanner;
// imports the Scanner class
public class Average{
public static void main(String[] args){
double num, total = 0, noOfInputs = 0, answer;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.print("Enter number: ");
//Prompts the user to enter a number
num = scanner.nextDouble();
/*Adds the number inputted to the "num" variable. This is the
source of my problem*/
if(num.equals("=")){
break;}
/*The if statement breaks the loop if a certain character is
entered*/
total = total + num;
//Adds the number inputted to the sum of all previous inputs
noOfInputs++;
/*This will be divided by the sum of all of the numbers because
Number of inputs = Number of numbers*/
}
answer = total / noOfInputs;
System.out.print(answer);
}
}
Several ways to do this.
You could read every number as a string, and then if it is a number, parse it to get the value.
Integer.parseInt(String s)
Or you could check what comes next and read accordingly:
while (scanner.hasNext()) {
if (sc.hasNextInt()) {
int a = scanner.nextInt();
} else if (scanner.hasNextLong()) {
//...
}
}
Or you could just catch the InputMismatchException, and work from there.
try{
...
} catch(InputMismatchException e){
//check if '=' ...
}
Im trying to write code for a school project, the main objective is to get the average gpa of a students semester depending on how many Subjects and Units you input, however, if I try typing 0, the program goes into an infinite try-catch loop with "You can only type positive numbers" Im using valueOf() because I want the user to be able to type "salir" which means exit, to exit the program.
Scanner LeerTeclado = new Scanner(System.in);
int n=0, i=0, suma=0, promedio=0;
String materia, cadena;
//---------------------------------------------------------------------------
out.println("---------------------------");
out.println("-- School Grades --");
out.println("---------------------------");
//---------------------------------------------------------------------------
out.println("\nType 'salir' to terminate the program");
out.println("-----------------------------------------");
out.print("Type the number of subjects to grade: ");
cadena = LeerTeclado.nextLine();
int z = 0;
if("salir".equals(cadena)){
System.exit(0);
}
if("Salir".equals(cadena)){
System.exit(0);
}
///////////////////////////////////////////////////////////////////
do{
try{
z = Integer.valueOf(cadena);
if(z <= 0){
out.println("...............................................");
out.println(" You can only type positive numbers ");
out.println("...............................................");
out.println("\n");
continue;
}
break;
}catch(NumberFormatException ex){
out.println("\n*You have entered non-numeric characters*");
out.print("\nPlease type the number of subjects again: ");
LeerTeclado.nextLine();
}
}while(true);
In the try block, before you write
continue;
but after "You can only type positive numbers," you should prompt the User for another line of input, and wait for the user to enter that.
The "continue" statement skips to the end of the loop and causes the 2nd part of the loop not to run. That is why the loop is running indefinitely.
Move reading cadena into the try block
int z = 0;
do {
try {
cadena = LeerTeclado.nextLine(); // <-- re-read
if ("salir".equalsIgnoreCase(cadena)) { // <-- you might test once.
System.exit(0);
}
// if ("Salir".equals(cadena)) {
// System.exit(0);
// }
z = Integer.valueOf(cadena); // <-- or this loops forever.
Alberto,
There are a few things that need to be changed in order to get this program to work the way you wish. Since you are a student I'm not going to solve it for you. I will answer your question, however.
When you type zero on the command line your program will execute from the z<=0 test down to the continue statement. The continue statement tells the code to ignore everything after and return to the beginning of the loop so it goes back to the beginning of the do statement and repeats. You need some way to end the loop.
May I suggest writing the program a little at a time and test as you go along. That is, write the part that's not in the loop. Once that works write a little something in the loop and test. Keep doing this until the programs works the way you want it to.
Good Luck
do{
try{
z = Integer.valueOf(cadena);
if(z <= 0){
out.println("...............................................");
out.println(" You can only type positive numbers ");
out.println("...............................................");
out.println("\n");
continue;
}
You want to use break
if(z <= 0){
System.out.println("...............................................");
System.out.println(" You can only type positive numbers ");
System.out.println("...............................................");
System.out.println("\n");
break;
}
continue just hops to the top of the if and keeps at it, same thing.