Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 days ago.
Improve this question
I'm new to programming, and one of my assignments is making a code for a number ranging from 0 to 100; if a number is negative, I have to convert the negative to positive. I tried many ways to solve this problem but couldn't. If anyone can explain how to solve this problem, that would be great.
System.out.print("Enter a number between 0 to 100: ");
Scanner input = new Scanner(System.in);
int range = input.nextInt();
// Display the user result
if (user1 > range)
System.out.println("A correct number was entered ");
else if (user1 > range)
System.out.println("An incorrect number was entered");
else
{
System.out.print("The number range " + range + " needs to be positive ");
System.out.print(range * -1); // If the number is negative convert to positive
}
}
I'd re-write that as:
int minInclusive = 0;
int maxInclusive = 100;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number between " + minInclusive + " and " + maxInclusive + " inclusive: ");
int number = Math.abs(input.nextInt()); // number is now POSITIVE
if (number >= minInclusive && number <= maxInclusive) { // COMPOUND BOOLEAN EXPRESSION!
System.out.println("A correct number was entered ");
}
else {
System.out.println("An incorrect number was entered");
}
Here is what your missing on:
your inaccurate naming of the "range" variable is most possibly confusing you
I think you meant user1 to be the user input rather than the "range" variable. Here, it teaches you a very important lesson that all programmers will learn at some time: Name your variables so that you can understand them
for a more descriptive variable name, I will rename user1 to user_input
int user_input = input.nextInt();
which modifies your code to
if (user_input > range) {
System.out.println("A correct number was entered ");
}
else if (user_input > range) {
System.out.println("An incorrect number was entered");
}
else
{
System.out.print("The number range " + user_input + " needs to be positive ");
System.out.print(user_input * -1); // If the number is negative convert to positive
}
I also added some brackets for readability and proper formatting
moving on from this, it seems that what you meant by range here is the 0 and 100 range that the problem sets which gives
if (user_input > 0) {
System.out.println("A correct number was entered ");
}
else if (user_input > 100) {
System.out.println("An incorrect number was entered");
}
else
{
System.out.print("The number range " + user_input + " needs to be positive ");
System.out.print(user_input * -1); // If the number is negative convert to positive
}
finally We have a working, nice looking code.
For the last touch I recommend using abs to change signs for better understanding. Which modifies to
if (user_input > 0) {
System.out.println("A correct number was entered ");
}
else if (user_input > 100) {
System.out.println("An incorrect number was entered");
}
else
{
System.out.print("The number range " + user_input + " needs to be positive ");
System.out.print(Math.abs(user_input)); // If the number is negative convert to positive
}
Now we are done :)
If it is negative then simply negate the value
if(range < 0) {
range = -range;
}
Related
I can't seem to understand how to use a while loop to determine whether a number is positive or not. While (I > 0), if I put any positive number, it will always result above 0 meaning there's an infinite loop.
int i = 0;
System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation
System.out.print(" Please enter a value: ");
Scanner scan = new Scanner(System.in);
i = scan.nextInt();
while (i > 0)
{
System.out.println("The value is: " +i);
}
System.out.println("Sorry. Only positive values.");
Also, when I input a negative number, it doesn't go back to the scanner to possibly input a positive number.
You can go to this kind of approach:
int i = 0;
System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation
Scanner scan = new Scanner(System.in);
while (i >= 0) {
System.out.print(" Please enter a value: ");
i = scan.nextInt();
if (i > 0) {
System.out.println("The value is: " + i);
} else {
break;
}
}
System.out.println("Sorry. Only positive values.");
I believe this is what you're trying to achieve.
int i = 0; // int is 0
while (i <= 0) {
// int is 0 or a negative number
System.out.println("#1\n Input Validation\n Positive values only");
System.out.print(" Please enter a value: ");
Scanner scan = new Scanner(System.in);
i = scan.nextInt();
if (i > 0) {
System.out.println("The value is: " + i);
} else {
System.out.println("Sorry. Only positive values.");
}
// if number is positive then continue to termination. If negative then repeat loop
}
Pay closer attention to where you place your while loop as your initial placement would certainly result in an infinite loop
while (i > 0)
{
System.out.println("The value is: " +i);
// number is positive - repeat loop containing only this line of code to infinity
}
// number is either 0 or negative so continue to termination
I am trying to make a program that randomly generates two single digit numbers, creates a multiplication question, asks the user for the answer, counts the amount of questions and correct answers, and after every question the user is able to stop the loop to see how many he got correct out of the number of questions that were given.
I believe that I should be using a while loop (probably the easiest way) but I don't know exactly how to go about doing that. Here is what I currently have:
int number = 0;
int number1 = (int)(Math.random() * 10); //Produce two single digit numbers
int number2 = (int)(Math.random() * 10);
Scanner input = new Scanner(System.in); //Create Scanner
System.out.print("What is " + number1 + " + " + number2 + "? ");
int answer = input.nextInt();
while (number <= 10) {
if (number1 + number2 != answer ) {
System.out.println(" Incorrect!\n Would you like to see your overall result? (yes or no)");
}
else {
System.out.println(" Correct, great job!\n Would you like to see your overall result? (yes or no)");
}
}
Since this seems like an assignment I'll just give you pseudocode
MainMethod
{
//Create a new Random to generate random numbers
//(Import java.util.random)
//You need variables for:
//Total number of questions asked
//Total number of correct answers
//Start the question loop
while(true){
//Generate your two random numbers
//Ask the question
//Index the total number of questions
//Get their answer
//Check their answer
if(answer is correct){
//Index correct answers
}
//Ask whether they want to continue
//Check whether they want to stop
if(they want to quit){
//Break out of the while loop (break;)
}
}
//Tell them how many they got correct out of the total
}
Maybe I gave a little too much, but I hope this helps.
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
I need help making a loop that looks at each value from 1 to number-1.
Also how to test each value to see if it is a
divisor of number, and if it is, adding it to the sum.
This is what I have so far:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Please enter a positive integer: ");
int n = input.nextInt();
while (n < 0) {
System.out.println(n + " is not positive.");
System.out.print("Please enter a positive integer: ");
n = input.nextInt();
}
}
You can use this as a starting block for your application:
package Testers;
import java.io.Console;
public class Application {
public static void main(String[] args)
{
Console console = System.console();
if (console == null)
{
System.err.println("No console.");
System.exit(1);
}
boolean keepRunning = true;
while (keepRunning)
{
String name = console.readLine("Type your positive integer");
try{
int integer = Integer.parseInt(name);
if(integer < 0){
System.out.println("You must specify a positive integer!");
}
for(int i = 1; i<integer; i++){
// our variable "i" is smaller than "integer". This will parse all the numbers between one and "integer" -1.
if(i % 2 == 0){
//"i" IS divisible by 2. Of course, you can change this value to what you want to change it to.
//Here you can add it to a sum
}else{
//"i" is not divisible by 2. Of course, you can change this value to what you want to change it to.
}
}
}catch(NumberFormatException e){
System.out.println("You must specify a positive integer!");
}
}
}
}
If you want to do something for a known number of times, it is mostly a good idea to use a for loop. If you want to do something for number 1 to n-1, the loop could look like
for(int i = 1; i < n; i++) { // do stuff }
Note that it starts counting from 1 and stops as soon as i is greater or equal than n.
In order to know whether a number, say n, is divisible by some number, say k, the modulo-operator % could be used. If n % k == 0 this means that n is divisible by k. With an if-statement this can be tested and when you have some sum variable you can add whatever you want to that variable to sum things up.
Hope that helps
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
I have this small snippet of coding that requires an input from the user when it is ran to determine a certain value. I don't want the user to be able to enter anything less than 0 and anything greater than 1 million, so, 0 =< YEARS_AHEAD =< 1000000.
I've looked through so many tutorials and searched for help on this and found nothing. This is my code.
Scanner reader = new Scanner(System.in);
int YEARS_AHEAD;
System.out.print("Enter the amount of years ahead: ");
while (true)
try {
YEARS_AHEAD = Integer.parseInt(reader.nextLine());
break;
}catch (NumberFormatException nfe) {
System.out.print("This value must be an integer, please enter the number of years ahead again: ");
}
Add a simple if:
if (YEARS_AHEAD < 0 || YEARS_AHEAD > 1000000) {
// say something to the user, retry entering the number
}
Another option is to use the while cycle for this:
int YEARS_AHEAD = -1; // invalid value
while (YEARS_AHEAD < 0 || YEARS_AHEAD > 1000000) {
try {
System.out.print("Enter the amount of years ahead: ");
YEARS_AHEAD = Integer.parseInt(reader.nextLine());
}catch (NumberFormatException nfe) {
System.out.print("This value must be an integer, please enter the number of years ahead again: ");
}
}
Once you have read the input
YEARS_AHEAD = Integer.parseInt(reader.nextLine());
check using if-else whether the input is permitted or not.
if(YEARS_AHEAD < 0 || YEARS_AHEAD >1000000){
System.out.println("Invalid Input");
}else{
// do your processing here.
}