I've written a portion of code to take a user input, match it to a string value and then use a related double value to make calculations:
double [] currency = new double[] {0.05,0.10,0.20,0.50,1.00,2.00,5.00,10.00,20.00,50.00,100.00};
String [] currencytext = {"$0.05","$0.10","$0.20","$0.50","$1.00","$2.00","$5.00","$10.00","$20.00","$50.00","$100.00"};
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < currencytext.length; i++) {
boolean valid = false;
while(!valid){
System.out.format("$%.2f remains to be paid. Enter coin or note: ",sum);
String payment = keyboard.next();
if(payment.equals(currencytext[i])){
sum = sum - currency[i];
if(sum == 0) {
System.out.print("You gave " + payment);
System.out.print("Perfect! No change given.");
System.out.print("");
System.out.print("Thank you" + name + ".");
System.out.print("See you next time.");
}
}
if(!(payment.equals(currencytext[i]))) {
System.out.print("Invalid coin or note. Try again. \n");
}
if(payment.equals(currencytext[i]) && currency[i] > sum){
System.out.print("You gave " + payment);
System.out.print("Your change:");
}
}
}
The problem is that when it gets to user input, it doesn't match any string values except for $0.05. It seems to me like its not iterating through the array properly but I can't figure out why. Is anyone able to see a problem here?
This is a possible solution for your problem
Scanner keyboard = new Scanner(System.in);
double [] currency = new double[] {0.05,0.10,0.20,0.50,1.00,2.00,5.00,10.00,20.00,50.00,100.00};
String [] currencytext = {"$0.05","$0.10","$0.20","$0.50","$1.00","$2.00","$5.00","$10.00","$20.00","$50.00","$100.00"};
String payment = keyboard.next();
double sum = 100; // <- Working example - Read sum from keyboard entry
while (sum > 0) {
boolean paymentFound = false;
for (int i = 0; i < currencytext.length; i++) {
if (payment.equals(currencytext[i])) {
sum = sum - currency[i];
paymentFound = true;
if (sum == 0) {
System.out.println("You gave " + payment);
System.out.println("Perfect! No change given.");
// System.out.print("Thank you" + name + ".");
System.out.println("See you next time.");
break;
} else if (sum < 0) {
System.out.println("You gave " + payment);
System.out.println("Your change:" + (-1 * sum));
break;
}
}
}
if (!paymentFound) {
System.out.println("Invalid coin or note. Try again. \n");
}
if (sum > 0) {
System.out.format("$%.2f remains to be paid. Enter coin or note: ", sum);
payment = keyboard.next();
}
}
while-loop will continue until the payment is fullfilled.
for-loop traverse the arrays until a suitable payment is found
If suitable payment is found we substract it from sum. We use break to exit the for-loop in both cases. There is no need to keep searching.
If no suitable payment is found [!paymentFound], we keep on asking.
if (!paymentFound) {
System.out.println("Invalid coin or note. Try again. \n");
}
if (sum > 0) {
System.out.format("$%.2f remains to be paid. Enter coin or note: ", sum);
payment = keyboard.next();
}
The program will end when (sum < 0), in which case the while-loop exits.
I have use println instead of print to improve message legibility.
Too many flaws to point out.
However,
When the currencytext[i] does not match payment, it executes this code:
System.out.print("Invalid coin or note. Try again. \n");
System.out.format("$%.2f remains to be paid. Enter coin or note: ",sum);
payment = keyboard.next();
So, it executes this for all the times that your input does not match currencytext[i].
And, in this block, you have
payment = keyboard.next();
So, it asks for new input, in this block itself. Hence, you get the said output for all inputs except $0.05.
As far as $0.05 is concerned, your first if block executes successfully, and prints no output. So, it moves to the next iteration of the while loop, where again, payment remains the same ($0.05), but currencytext[i] becomes $0.10. SO they do not match, and you get the said output.
How to correct this:
With this code, you need to do a lot of corrections.
I suggest you again start from scratch.
If it doesn't fit, it sets valid to true, so the code just has the chance to check against the first item at currencytext[0], which is $0.05. Then !payment.equals(currencytext[i]) is also true, and your code prints the lines there. Your else ifs are also not properly nested.
I don't know how you are reading input. One improvement you can do is write reading input code in for loop.
Scanner scanner = new Scanner(System.in);
for (... ) {
....
String payment = scanner.nextLine();
....
}
Related
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("\nThe sum of the numbers is: " + getSumOfInput());
}
public static int getSumOfInput () {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
boolean checkValidity = userInput.hasNextInt();
if(checkValidity) {
int userNum = userInput.nextInt();
userInput.nextLine();
System.out.println("Number " + userNum + " added to the total sum.");
sumOfNums += userNum;
counter++;
} else {
System.out.println("Invalid input. Please, enter a number.");
}
}
userInput.close();
return sumOfNums;
}
}
Hello everybody!
I just started java and I learned about control flow and now I moved on to user input, so I don't know much. The problem is this code. Works just fine if you enter valid input as I tested, nothing to get worried about. The problem is that I want to check for wrong input from user, for example when they enter a string like "asdew". I want to display the error from else statement and to move on back to asking the user for another input, but after such an input the program will enter in an infinite loop displaying "Enter the number X: Invalid input. Please, enter a number.".
Can you tell me what's wrong? Please, mind the fact that I have few notions when it comes to what java can offer, so your range of solutions it's a little bit limited.
Call userInput.nextLine(); just after while:
...
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
userInput.nextLine();
...
The issue is, that once you enter intput, which can not be interpreted as an int, userInput.hasNextInt() will return false (as expected). But this call will not clear the input, so for every loop iteration the condition doesn't change. So you get an infinite loop.
From Scanner#hasNextInt():
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
The fix is to clear the input if you came across invalid input. For example:
} else {
System.out.println("Invalid input. Please, enter a number.");
userInput.nextLine();
}
Another approach you could take, which requires less input reads from the scanner, is to always take the next line regardless and then handle the incorrect input while parsing.
public static int getSumOfInput() {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
String input = userInput.nextLine();
try {
int convertedInput = Integer.parseInt(input);
System.out.println("Number " + convertedInput + " added to the total sum.");
sumOfNums += convertedInput;
counter++;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please, enter a number.");
}
}
return sumOfNums;
}
I'm using a while statement in my code, where, inside the while statement, the user inputs a number. To stop the program from looping, the user must input the word "stop". However, once I enter in a number, the output skips to another line without printing the statement I want it to print, and I have to enter my desired input again for the program to start looping.
The only time this problem DOES NOT occur is when the user inputs "stop" FIRST, then the code works fine.
This is to find the max, min, and mean of any amount of user-inputted numbers. I've tried changing the order of the else/if statements and the parameters for the said else/if statements, but nothing seems to work.
boolean stopped = false;
int numberAmount = 0;
int invalidAmount = 0;
double max = Integer.MIN_VALUE;
double min = Integer.MAX_VALUE;
double mean = 0;
while(stopped == false)
{
System.out.print("Enter a number (type "+"\""+"stop"+"\""+" to stop): ");
String originalInput = userInput.nextLine();
if(originalInput.equals("stop"))
{
stopped = true;
invalidAmount ++;
System.out.println(numberAmount+" numbers were entered with "+invalidAmount+" invalid inputs.");
}
else if(userInput.hasNextDouble())
{
double currentValue = Double.parseDouble(originalInput);
max = Math.max(max, currentValue);
min = Math.min(min, currentValue);
mean = currentValue;
numberAmount ++;
}
else if(originalInput.equals("stop") == false)
{
System.out.println("Not a number...");
invalidAmount ++;
}
}
System.out.println("The maximum is "+max+".");
System.out.println("The minimum is "+min+".");
System.out.println("The mean is "+(mean / numberAmount)+".");
userInput.close();
}
}
For example, I expect the output after inputting 7 to be
"Enter a number (type "stop" to stop):" on the next line(since the program loops to keep prompting for number input), where the user could then keep inputting numbers as they like.
Instead, the actual output is a blank line under the original prompt for user input, where the user must input their desired input AGAIN for the program to start looping.
You didn't specify in your code example what userInput is, but from the usage it looks to be an instance of Scanner. If you have a Scanner declared and then call hasNextDouble(), you will get a boolean result which fits with your usage – you have that as the condition in your if statement.
Scanner userInput = new Scanner(System.in);
boolean b = userInput.hasNextDouble();
What's missing from the picture is how hasNextDouble() works. Looking at the Javadoc for Scanner:
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.
In order to answer true/false for whether the next input is a double or not, the scanner has to wait for input from the user before it can proceed.
All of this to say: your code looks like it's behaving normally. If you don't want to wait for user input, you need to write your code to reflect that.
I think you should invert the logic of the code, assuming you are using the Scanner, try something like this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean stopped = false;
int numberAmount = 0;
int invalidAmount = 0;
double max = Integer.MIN_VALUE;
double min = Integer.MAX_VALUE;
double mean = 0;
while (stopped == false) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a number (type " + "\"" + "stop" + "\"" + " to stop): ");
if (userInput.hasNextDouble()) {
double currentValue = userInput.nextDouble();
max = Math.max(max, currentValue);
min = Math.min(min, currentValue);
mean = currentValue;
numberAmount++;
} else {
String originalInput = userInput.nextLine();
if (originalInput.equals("stop")) {
stopped = true;
invalidAmount++;
System.out.println(numberAmount + " numbers were entered with " + invalidAmount + " invalid inputs.");
} else {
System.out.println("Not a number...");
invalidAmount++;
}
}
}
System.out.println("The maximum is " + max + ".");
System.out.println("The minimum is " + min + ".");
System.out.println("The mean is " + (mean / numberAmount) + ".");
// userInput.close();
}
}
Basically you are checking first the input type, and only after you are collecting the value from the console. Doing it the way you have right now, you will always ask for the second input.
I don't really know the API, but I expect hasNextDouble reads another line. Check if originalInput is a double, don't read another line.
I'm working on a project that calculates the value of a bank account based on starting balance(b), interest rate(IR), and quarters to display. My entire code works perfectly, but the very last portion is to make sure the variables like interest rate are within the confines of the boundaries my professor gave me. I do need to display an error message if the user enters a value outside the boundaries and ask for the value again.
For example, the number of quarters to display needs to be greater than zero, and less or equal to 10.
As you can see, pretty much all of my program is in a do-while loop. I know I can have nested loops, but what would I be able to put in my do-while loop that would work in this situation? An if-else statement? Try and catch block? Another while loop?
If I used a try-catch, then could anyone give me an example of how I could do that? Thank you very much for your time, and all help is appreciated! The below is my code for reference.
import java.util.Scanner;
public class InterestCalculator
{
public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
int quartersDisplayed;
double b, IR;
do
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
System.out.println("Next enter the starting balance. ");
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
System.out.println("Finally, enter the interest rate ");
System.out.println("which must be greater than zero and less than or equal to twenty percent: ");
IR = keyboard.nextDouble();
System.out.println("You have entered the following amount of quarters: " + quartersDisplayed);
System.out.println("You also entered the starting balance of: " + b);
System.out.println("Finally, you entered the following of interest rate: " + IR);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = b + (b * IR/100 * .25);
System.out.println("Your ending balance for your quarters is " + quarterlyEndingBalance);
System.out.println("Do you want to continue?");
String yes=keyboard.next("yes");
if (yes.equals(yes))
continue;
else
break;
}
while(true);
}
}
So here's some code to answer your questions and help get you started. However, there are problems with your logic that do not pertain to your question which I will address afterward.
Note: I have added comments to your code. Most of them start with "EDIT:" so that you can tell what I changed. I didn't use this prefix in all cases because some of it is new code and it's obviously my comment
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
// EDIT: you already have a scanner defined below with a more meaningful name so I removed this one
// Scanner scannerObject = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//EDIT: defining userResponse outside the loop so we can use it everywhere inside
String userResponse = null;
do {
//EDIT: moved the variables inside the loop so that they are reset each time we start over.
//EDIT: initialize your variable to a value that is invalid so that you can tell if it has been set or not.
int quartersDisplayed = -1;
//EDIT: gave your variables more meaningful names that conform to java standards
double startingBalance = -1, interestRate = -1;
//EDIT: you don't need a second Scanner, just use the one you already have.
// Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
userResponse = input.next();
try{
quartersDisplayed = Integer.parseInt(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(quartersDisplayed <= 0 || quartersDisplayed > 10){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the starting balance (must be greater than zero): ");
userResponse = input.next();
try{
startingBalance = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
if(startingBalance <= 0){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
do{
System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
userResponse = input.next();
try{
interestRate = Double.parseDouble(userResponse);
}catch(NumberFormatException e){
//nothing to do here, error message handled below.
}
//Note: I assume twenty percent is represented as 20.0 here
if(interestRate <= 0 || interestRate > 20){
System.out.println("Sorry, that value is not valid.");
}else{
break;
}
}while(true);
System.out.println("You have entered the following amount of quarters: "
+ quartersDisplayed);
System.out.println("You also entered the starting balance of: " + startingBalance);
System.out.println("Finally, you entered the following of interest rate: "
+ interestRate);
System.out.println("If this information is not correct, please exit the program and enter the correct information.");
double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
System.out.println("Your ending balance for your quarters is "
+ quarterlyEndingBalance);
System.out.println("Do you want to continue?");
//EDIT: modified your variable name to be more meaningful since the user's response doesn't have to "yes" necessarily
userResponse = input.next();
// EDIT: modified the logic here to compare with "yes" or "y" case insensitively.
// if (userResponse.equals(userResponse))
if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
continue;
else
break;
} while (true);
Now to address other issues - your interest calculation doesn't seem correct to me. Your formula does not make use of the quartersDisplayed variable at all. I assume you're compounding the interest quarterly so you will definitely need to make use of this when calculating your results.
This may be beyond the scope of your project, but you should not use double or float data types to represent money. There is a stackoverflow question about this topic that has good information.
Possible improvements - since you're asking the user for two values of type double you could create a method to ask for a double value and call it twice instead of repeating the code. This is a better approach because it helps reduce the chance of mistakes and makes testing and maintenance easier.
You can do something like this in your do/while loop:
do
{
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
quartersDisplayed = keyboard.nextInt();
}
while (quartersDisplayed < 1 || quartersDisplayed > 10);
System.out.println("Next enter the starting balance. ");
do
{
System.out.println("This input must be greater than zero: ");
b = keyboard.nextDouble();
}
while (b < 1);
// rest of code ...
}
With the Scanner#hasNextInt (and the equivalent for double), you can avoid having exceptions thrown, and thus don't need try-catch clauses. I think in general if you can avoid try-catch, it's good, because they are clumsy - but I might be wrong.
However, my approach is like this. Inside your outer do-while, have three other do-while-loops to get the three values. The reason is that you want to keep looping until you get a correct value. The explanation of why keyboard.nextLine() is important is covered here.
I didn't include all of your code, only the part in question. Here's my take on it:
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int quartersDisplayed = -1;
double b = -1.0;
double IR = -1.0;
do {
do {
System.out.println("Enter the number of quarters.");
if(keyboard.hasNextInt()) {
quartersDisplayed = keyboard.nextInt();
keyboard.nextLine(); //important
} else {
System.out.println("You need to enter an integer.");
continue;
}
} while(quartersDisplayed < 1 || quartersDisplayed > 10);
do {
System.out.println("Enter the starting balance.");
if(keyboard.hasNextDouble()) {
b = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(b <= 0);
do {
System.out.println("Enter the interest rate.");
if(keyboard.hasNextDouble()) {
IR = keyboard.nextDouble();
keyboard.nextLine();
} else {
System.out.println("You must enter a number.");
continue;
}
} while(IR <= 0 || IR > 20.0);
//... rest of code
} while(true);
}
}
Good day guys, I am new in this. I am doing an assignment for my prog unit, so please bear with me.
So what I have to do is to write up a code that can input people's ages, from integers between 1 to 120 inclusive. The user then have to calculate the average age, and should be calculated as a real number. But the user has to input age values until the user enters 0, which is to stop the program then output the average. If the user enters an age that is invalid, then the program should continue to re-prompt the user until they enter a valid age.
So I did my part. I created a code and I come up with this:
public static void main(String[] args)
{
int ageValue = 0;
double getAge;
getAge = inputAge();
System.out.println("Average age is: " + getAge);
}
public static double inputAge()
{
int ageValue = 0;
double avgAge = 0;
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 120; i++)
{
System.out.println("Enter age");
ageValue += sc.nextInt();
avgAge = ageValue / (double) i;
if (ageValue == 0)
{
System.out.println("Average age is: " + avgAge);
System.exit(0);
}
while (ageValue < 0 || ageValue > 120)
{
System.out.println("Invalid input. Try again!");
ageValue = sc.nextInt();
}
}
return avgAge;
}
Now I laid down my code and I got my average formula somehow working. Now, the problem is that when I press 0, it doesn't prompt the "if" statement. However, when the first "Enter your age" prompt comes up and I pressed 0, the "if" statement worked. But for each iteration, the program won't let me execute the statement.
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks. What I wanted is when I press 0, it should exit the loop and output the average, like what the task said.
I don't know if you guys can get it.. Is the code right? Am I on the right track? Am I missing something???
Cheers
You could consider a do while loop approach. This would allow your code to naturally run once, and exit once the user enters 0:
int ageValue = 0, numOfAges = 0, sumOfAges = 0;
do {
System.out.println("Enter age");
ageValue = sc.nextInt();
if (ageValue < 0 || ageValue > 120)
System.out.println("Bad value... try again");
else if (ageValue != 0) {
sumOfAges += ageValue;
numOfAges++;
}
} while (ageValue != 0);
return ((double)sumOfAges / numOfAges);
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks.
You can have another condition in your for loop like this
boolean finished = false;
for (int i = 1; i <= 120 && finished == false; i++)
and replace
System.exit(0)
with
finished = true;
However, I would question why using "break" will score you zero marks. This is exactly the sort of scenario break was intended for.
you can try this approach.
i've corrected a bit the exit condition and the way averaging is done.
the "for" loop you show in your code is limiting the number of sample to 120, but the question don't say so, so i took the liberty to generalise you question to any number of sample to average.
first thing is you should look up "if-else" conditionnal structure, as that was the main point missing in your code.
https://en.wikipedia.org/wiki/Conditional_(computer_programming)
you can think the way the problem is expressed as :
calculate the average in a serie
the serie is keyboard inputted
when zero is inputted, exit the loop and return the current average
when any value out of bound [0,120] is inputted, give a message and continue the loop without changing anything to the serie
when any value inside the bound [1,119] is inputted add the value to the serie and recalculate the average
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Final Average age is: "+inputAge());
}
private static double inputAge()
{
int ageValue=0;
double avgAge=0;
boolean shouldExit=false;
Scanner sc=new Scanner(System.in);
List<Integer> samples=new ArrayList<Integer>();
// loop until flag is true
while(!shouldExit)
{
System.out.println("Enter age");
ageValue=sc.nextInt();
if(ageValue==0)
{
shouldExit=true;
}
else if(ageValue<0||ageValue>120)
{
System.out.println("Invalid input. Try again!");
}
else
{
// add current input in the samples and calculate average over all the samples
samples.add(ageValue);
avgAge=getAvg(samples);
System.out.println("Current Average age is: "+avgAge);
}
}
sc.close();
return avgAge;
}
private static double getAvg(List<Integer> samples)
{
double avgAge=0;
for(Integer tmp:samples)
{
avgAge+=tmp;
}
return avgAge/(double) samples.size();
}
}
I have just written my first java program for a class I am taking which is used to give a student graduation information based on the credits for each class remaining. I have gotten everything to work except the required entry to check for negative values. Please see below and let me know if you have any ideas. Thanks in advance.
package txp1;
import java.util.ArrayList;
import java.util.Scanner;
public class txp1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the University Graduation Calculator!");
System.out.println();
System.out.println("This calculator will help determine how many terms "
+ "you have remaining and your tuition total based upon credits"
+ " completed per semester.");
System.out.println();
double tuitionpersem = 2890;
System.out.println("We will begin by entering the number of credits for"
+ " each class remaining toward your degree.");
double sum = 0;
ArrayList<Double> credit = new ArrayList<>();
{
System.out.println("Please enter the number of credits for each individual class on a separate line and then press enter, Q to quit:");
Scanner in = new Scanner(System.in);
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
while (in.hasNextDouble()) {
credit.add(in.nextDouble());
}
for (int i = 0; i < credit.size(); i++) {
sum += credit.get(i);
}
System.out.println("Total credits remaining: " + sum);
}
int perterm = 0;
System.out.println("How many credits do you plan to take per term? ");
Scanner in = new Scanner(System.in);
perterm = Integer.parseInt(in.nextLine());
if (perterm <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
double totterms = sum / perterm;
totterms = Math.ceil(totterms);
System.out.print("Your remaining terms: ");
System.out.println(totterms);
double terms = (totterms);
System.out.print("The number of months to complete at this rate is: ");
System.out.println(6 * terms);
double cost = terms * 2890;
System.out.println("The cost to complete at this rate is: " + cost);
}
}
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
The ";" at the end of if statement is the end of it. You are not doing anything with the result of number <=0. I believe you meant it to be like:
if (number <= 0){
//operations….
}
Notice that you create number of type double, then assign an int (parsed from String) to it. You can use nextDouble method to get a double directly, and if you plan this number to be an Integer anyway then use type int instead of double and nextInt instead of parsing. For more information about parsing from input, check Scanner documentation.
Your if statements terminate if you put a semi colon at the end of them. Effectively ending your logic right there. The program basically checks the condition and then moves on. Which in turn executes your second statement regardless of what number <= 0 resolves to.
//Does not get expected results
if (number <= 0);
{
//Gets executed regardless of condition
System.out.println("The number of credits must be greater than zero!");
}
//Gets expected results
if (number <= 0)
{
//Gets executed only if the condition returns true
System.out.println("The number of credits must be greater than zero!");
}
Edit: Changed due to some helpful input.
2nd Edit: I would also consider putting a loop in your code that makes the user re-enter input to get the desired value. If you put in a negative value your code will just spit the error message and keep running which can make you scratch your head. Unless your teacher isn't grading on that then forget all of what I just said. =p