So I've written a test class to test a program that will allow me to take in number of courses, letter grades, and course credits and then calculate total weighted points, total credits, and GPA within a loop designed for 3 courses max.
However, I need to validate the number of courses and prove that it will run after both an invalid and valid input have been entered.
I've gotten it so that will prompt the user for a valid number of courses after an invalid response, but once the valid response is input the program just stops instead of running like it is supposed to. Can anyone tell me why?
Here's my code:
import java.util.*;
import java.lang.*;
public class ComputeGpa
{
public static void main(String [] args)
{
Gpa grades1 = new Gpa();
Scanner in = new Scanner (System.in);
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
if(courses > 0)
{
int i = 0;
while(i < 3)
{
System.out.println("Please enter a letter grade.");
String letter = in.next();
char result = letter.charAt(0);
System.out.println("How many credits was this class worth?");
int credits = in.nextInt();
grades1.addToTotals(result, credits);
i++;
}
System.out.printf("GPA: %.2f", grades1.calcGpa());
}
else
{
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
}
}
The output for that is as follows:
Enter number of courses:
-2
Number of courses must be greater than 0. Please enter a valid number of courses.
3
And then the program stops running. Where Am I going wrong? I thought the in.next() on the letter String would fix this problem but apparently I was wrong. Any ideas?
Your flow is currently if/else.
int foo = ...;
if(foo > 0) {
//your grade stuff
}
else {
//ask for reinput
}
What ends up happening is you catch the problem input once, but never give your flow the opportunity to check it again.
Instead, use a while loop over an if/else layout, to force re-entry until you get the exact information you want, then continue.
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
while(courses < 0) {
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
int i = 0;
//...
Related
package w3school;
import java.util.Random;
import java.util.Scanner;
public class nyttprogram {
static void indata() {
{
Scanner determinedNumber = new Scanner(System.in);
int user, computer, number, user2;
System.out.println("Input a number from 0-10");
user = determinedNumber.nextInt();
Random random = new Random();
int randomInt = random.nextInt(10);
if (user == randomInt) {
System.out.println("You guessed the correct number!");
} else {
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + randomInt);
}
System.out.println("Input 1 if you want to try again: ");
}
}
public static void main(String[] args) {
indata();
}
}
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
The "start over" logic based on some conditions is usually implemented with while and do/while loops.
First let's extract those conditions. We want to iterate again (start over) if:
The user's guess is wrong.
The user's guess is correct, but they input a number different than 1 when asked if they want to continue.
Since we want to run the program at least once, the natural approach would be with a do/while. This will run one iteration, then check against the conditions wanted.
Here's what it looks like:
private static void inData() {
Scanner userInputScanner = new Scanner(System.in);
Random random = new Random();
// Declare the stop/continue condition
boolean isLoopContinue;
do {
// Generate a random number
int expectedNumber = random.nextInt(10);
// Ask the user to guess a number
System.out.println("Input a number from 0-10");
int givenNumber = userInputScanner.nextInt();
if (givenNumber == expectedNumber) {
// Correct answer, check if the user wants to continue
System.out.println("You guessed the correct number!");
System.out.println("\nInput 1 if you want to try again: ");
// If they input "1", then we continue. Else we stop
isLoopContinue = userInputScanner.nextInt() == 1;
} else {
// Wrong answer, loop again
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + expectedNumber);
isLoopContinue = true;
}
} while (isLoopContinue);
}
I want to enter several numbers for some operations. But i need to add this numbers without stopping. I mean, for example i wanna that program asks me how many integer i want to enter, after for example i yped 5 and click enter, it should give me opportunity to enter my 5 numbers (For example, 12, 34, 54, 23, 9) in the lines. Then i will use this numbers for something in my program.
i am using Scanner class for entering the number. But i wanna to enter several numbers in once input.
package frlr;
import java.util.Scanner;
public class Frlr {
public static void main(String[] args) {
System.out.println("Please enter your numbers: ");
Scanner in = new Scanner(System.in);
int myNumbers = in.nextInt();
System.out.println(myNumbers);
}
}
I need, when program asks me "Please enter your numbers:" if i enter 5 , it should be the count of the numbers which i will enter in the next steps.
You can use for loop, for loop allows you enter the amount of numbers you entered in your first scanner.
For example:
1) you scan the amount of number you want to enter
2) in for loop you use that number as an endpoint
so your for loop is gonna look like this:
for(initialization; condition(your condition is your scan) ; increment/decrement)
{
statement(s);
}
3) you statement is going to be another scan, or as you refer to it as entering several numbers
If you want to use the numbers later you can save them in an Array. First you ask the user how big the array has to be (quantity). Then you initialize an Array with the user input size. You need to watch out that the number is positive. After that you make a for loop, that has the input quantity times of iterations. After each step you save the number in the proper spot. In the end you can output the numbers.
Validation of user inputs can be done with Regular Expressions. Here is a good tutorial on RegEx: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
import java.util.Arrays;
import java.util.Scanner;
public class VariableInputs
{
private Scanner scanner;
private String input;
private boolean isInputBad;
public VariableInputs()
{
this.scanner = new Scanner(System.in);
this.isInputBad = false;
}
public void startInteraction()
{
System.out.println(
"How many Integers would you like to enter? Enter a positive number that is smaller than 100.");
int quantity;
do
{
if (isInputBad) System.out.println("Enter a valid number."); // this gets printed if the user entered a wrong input (f.e. "abc").
input = scanner.next();
isInputBad = true;
}
while (!input.matches("\\d{1,2}")); // this checks if the input contains only number 0-9. The input has to have atleast 1 and max 2 numbers.
isInputBad = false;
quantity = Integer.parseInt(input); // because of the regular expression we know for sure that the input string is a number. So we can parse it.
int[] numbers = new int[quantity]; // init array with input quantity.
System.out.println("Good job my friend. You have entered " + quantity
+ ". Go ahead and enter those numbers.");
for (int i = 0; i < quantity; i++)
{
do
{
if (isInputBad) System.out.println("Enter a valid number.");
input = scanner.next();
isInputBad = true;
}
while (!input.matches("\\d"));
numbers[i] = Integer.parseInt(input);
isInputBad = false;
}
System.out.println("Good job my friend. You have entered " + quantity
+ " numbers.");
System.out.println("The numbers are: " + Arrays.toString(numbers));
scanner.close();
}
public static void main(String[] args)
{
VariableInputs vi = new VariableInputs();
vi.startInteraction();
}
}
You can try this code and see if its useful:
import java.util.Scanner;
import java.util.Arrays;
public class ScannerIn {
public static void main(String[] args) {
System.out.print("Please enter how many numbers (between 1 and 10)? ");
Scanner in = new Scanner(System.in);
int numbersCount = in.nextInt();
System.out.println(numbersCount);
if (numbersCount <= 0 || numbersCount > 10) {
System.out.println("Numbers count must be between 1 and 10. Exit program!");
System.exit(0);
}
int [] myNumbers = new int [numbersCount];
for (int i = 0; i < numbersCount; i++) {
System.out.print("Please enter your number: ");
in = new Scanner(System.in);
myNumbers[i] = in.nextInt();
}
System.out.println("Numbers input: " + Arrays.toString(myNumbers));
}
}
I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}
I am having difficulties with finding all possible odd numbers for my program. I am required to use a while loop to find all the odd numbers but i am not sure how to print it out. I dont know if im doing anything wrong in this block while((num1+num2)%2==0) because that was just a guess. Outline of the program is to get the user to enter 2 numbers that is an even multiple of the other number. I am not sure how that part either. After finding 2 numbers that is an even multiple of the other number, i am supposed to display all the odd numbers between the two numbers. Thanks alot in advance.
import java.util.Scanner; //imports the java utillity scanner
public class MyPrompter{
public static void main(String[] args){
System.out.println("Odd number display");
Scanner input = new Scanner(System.in); //scans for user input and stores in "input"
int num1,num2; //declares the variables i need for the pgrm
try{ //try statement to check for user input errors
System.out.println("Please enter your first number: ");
num1 = input.nextInt(); //stores input for the first number
System.out.println("Please enter your second number: ");
num2 = input.nextInt(); //stores input for the second number
while((num1+num2)%2==0){ //while loop to find all the odd numbers between the 2 numbers
System.out.println();
}
}
catch(java.util.InputMismatchException e){ //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid ROUNDED NUMBER!");
}
}
}
How about something like this:
int num1 = 10;
int num2 = 50;
int current = num1;
while (current < num2) {
if (current % 2 != 0) {
System.out.println(current);
}
current++;
}
Set current to equal num1, continue the loop while current is less than num2. For each iteration check if current is odd and output it if it is. Increment current by one.
Getting a very strange error. When I add
{
while {
System.out.println( "Enter homework grades, Enter -1 when done" );
homeworkGrades += input.nextInt();
}
}
I get about 19 errors. If i remove it, then no errors. I've spent quite a few minutes changing it up, but I can't seem to get it to work. The program simply asks if you want to Average grades or Quit, then asks for your name. Now I want it to allow a user to enter in the Homework grades to average, then it will ask for quiz grades to average, then lastly test grades. Then it will take those 3 averages and average those.
import java.util.Scanner;
public class Assignment3
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int homeworkGrades;
int quizGrades;
int testGrades;
int choice;
int total;
double average;
String name;
total = 0;
System.out.println("Enter 1 or 2: \n 1 - Average grades \n 2 - Quit");
choice = input.nextInt();
if (choice == 1) {
System.out.println("Enter the students name");
name = input.next();
System.out.println("Grades will be entered in this order: \n 1) Homework Grades \n 2) Quiz Grades \n 3) Test Grades ");
//here
{
while {
System.out.println( "Enter homework grades, Enter -1 when done" );
homeworkGrades += input.nextInt();
}
}
}
if (choice == 2) {
System.out.println("Exiting program");
}
else {
System.out.println("Invalid response, exiting program.");
}
}
}
You need to give the while loop a condition, such as:
while (homeworkGrades != something) {
}
You need to tell your while loop when to exit. Without this information, it can not know when to stop. It is also not correct coding to skip the condition.
Based on what you have written, this will give you what you are most likely looking for:
int grade = 0;
while (grade >= 0)
{
homeworkGrades += grade;
System.out.println( "Enter homework grades, Enter -1 when done" );
int grade = input.nextInt();
}
I hope i have helped you to understand this more clearly. :)