I am trying to build a new code, and now the problem is after user entered negative value, this will print something and prompt again to enter value. What should I add after 69th line?
Here is my code:
import java.util.Scanner;
public class bchimedochir_Math
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
double userInput;
double value;
double pow;
double sqrt;
double log;
double floor;
double ceil;
double abs;
double sqrtE;
System.out.print("How many numbers would you like to process:");
userInput = input.nextDouble();
sqrtE = Math.sqrt(Math.E);
if (userInput > 0)
{
while (true)
{
System.out.println();
System.out.print("Please enter a number: ");
value = input.nextDouble();
sqrt = Math.sqrt(value);
log = Math.log(value);
ceil = Math.ceil(value);
floor = Math.floor(value);
pow = Math.pow(value, value);
abs = Math.abs(value);
System.out.println ("Using truncated integer value for exponent of power method.");
System.out.printf("Math.pow(%.4f,%.4f)=%.4f\n", ceil, ceil, pow);
if (value < 0 )
{
System.out.println ("Cannot use negative number for square root, using absolute value instead.");
System.out.printf("Math.sqrt(%4f)=%.4f\n", abs, sqrt);
}
else
{
System.out.printf("Math.sqrt(%4f)=%.4f\n", value, sqrt);
}
if (value < 0 )
{
System.out.println ("Cannot use negative number for log method, using absolute value instead.");
System.out.printf("Math.log(%.4f)=%.4f\n", abs, log);
}
else
{
System.out.printf("Math.log(%.4f)=%.4f\n", value, log);
}
System.out.printf("Math.floor(%.4f)=%.4f\n", value, floor);
System.out.printf("Math.ceil(%.4f)=%.4f\n", value, ceil);
System.out.printf("Math.abs(%.4f)=%.4f\n", value, abs);
userInput = userInput - 1;
}
System.out.printf("\n\nThe square root of e is: \nMath.e = %.4f \n", sqrtE);
}
if (userInput < 0)
{
System.out.print("You must enter a number greater than or equal to 0.\n");
}
if (userInput == 0)
{
System.out.print("No numbers to process.\n");
System.out.printf("\n\nThe square root of e is: \nMath.e = %.4f \n", sqrtE);
}
}
}
use while loop with the condition given in the if().
Also the answer for "How many numbers would you like to process:" will be a integer value, cannot be in double.
Just create a method to read positive values.
public int readPositiveInt() {
int userInput = input.nextInt();
if(userInput<0) {
System.out.println("You must enter a number greater than or equal to 0.");
return readPositiveInt();
}
return userInput;
}
I think you are trying to achieve this:
while(userInput <0){
System.out.print("You must enter a number greater than or equal to 0.\n");
userInput = input.nextInt();
}
If you want to restrict the attempts:
int MAX_ATTEMPTS = 10;
int attempts = 0;
while(userInput <0 && attempts < MAX_ATTEMPTS ){
System.out.println("You must enter a number greater than or equal to 0.\n");
userInput = input.nextInt();
attempts++;
}
if(userInput <0 ){
System.out.println("You didn't enter correct value in "+
MAX_ATTEMPTS +" attempts");
}
Related
I'm fairly new to Java and the problem I am having is that this code compiles, but does not run after the hexadecimal conversion; it instead just ends after the method hexCharToDecimal. I can't reuse method main and I'm not sure how to call the method intreverse and actually have it run. Is there a way to get back into main or do I have to call intreverse somewhere?
import java.util.Scanner;
public class Homework4 {
public static void main(String[]args) {
// Sum and average of a set of intergers entered by the user
// First we will declare some variables
int userInput = 1;
int positives = 0;
int negatives = 0;
int sum = 0;
int numCount = 0;
Scanner input = new Scanner(System.in);
// Will start a while loop that will stop when user enters 20 integers
while ((numCount <= 20)) {
System.out.println("Please enter a nonzero integer or enter 0 to finish ");
userInput = input.nextInt();
if (userInput == 0) {
break;
} else if (userInput > 0) {
positives += 1;
numCount += 1;
sum = sum + userInput;
} else if (userInput < 0) {
negatives += 1;
numCount += 1;
sum = sum + userInput;
} else
System.out.println("Error, please enter an integer");
continue;
}
double average = (sum / numCount);
System.out.println("The sum of the entered integers is " + sum);
System.out.println("The average of the enetered integers is " + average);
System.out.println("There are " + positives + " positive integers and " + negatives + " negative integers");
// Convert Hexadecimal number to decimal
// Ask the user to input a string of 5 digits or less in hex
System.out.println("Please enter a hexadecimal number of up to 5 characters");
String hex = input.next();
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
}
// Now we will create the method to convert to decimal
public static int hexToDecimal(String hex) {
int decimal = 0;
for (int i = 0; i < hex.length(); i++) {
char hexcharacter = hex.charAt(i);
decimal = decimal * 16 + hexCharToDecimal(hexcharacter);
}
return decimal;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') // check to see if there is any letters in the string
return 10 + ch - 'A';
else
return ch - '0';
}
// Print entered integer in reverse
public static void intreverse(String[]args) {
// Ask user for an integer to be reversed
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer to be reversed");
int number = input.nextInt();
reverse(number); // Method to be called
}
// Will now state our method
public static void reverse(int number) {
// use a while loop to get each digit
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
}
}
}
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
Will always run once because it is not enclosed in any sort of loop. If you want it to run again when the second case is called then enclose it in a while(true) loop and have a break statement in the first case where you want it to stop execution.
This is what I am supposed to do:
Write a Java program that will compute the factorial of some numbers n (input from the user, accept only range 1 - 10). For each valid number in input, the output should be the value of n!. Your program should use a loop, to allow the user to input more than one number (count-controlled or sentinel-controlled, your choice)
This is what I have at the moment:
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int num, result = 1;
String str;
System.out.print("Do you want to start? (y/n) ");
str = console.next();
System.out.println();
while(str.charAt(0) == 'y')
{
System.out.print("Enter an integer (1 - 10): ");
num = console.nextInt();
if(num < 1 || num > 10)
{
System.out.print("NUMBER OUT OF RANGE!");
num = console.nextInt();
}
else
{
int i = 2;
while(i <= num)
{
result = result * i;
i++;
}
System.out.println(num + "! = " + result);
System.out.println();
System.out.print("Do you want to continue? ");
str = console.next();
}
System.out.println();
}
}
But this is my result:
Do you want to start? (y/n) y
Enter an integer (1 - 10): 1
1! = 1
Do you want to continue? y
Enter an integer (1 - 10): 2
2! = 2
Do you want to continue? y
Enter an integer (1 - 10): 3
3! = 12
Do you want to continue? y
Enter an integer (1 - 10): 4
4! = 288
I can't get the output to display the right results, that is the only problem I am having with my program. Also, it shows the correct result the first time you are asked to enter an integer, but after that, everything goes wrong
Try this code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String str;
System.out.print("Do you want to start? (y/n) ");
str = console.next();
System.out.println();
int num, result;
while (str.charAt(0) == 'y') {
System.out.print("Enter an integer (1 - 10): ");
num = console.nextInt();
while (num < 1 || num > 10) {
System.out.println("NUMBER OUT OF RANGE!");
System.out.print("Enter an integer (1 - 10): ");
num = console.nextInt();
}
int i = 2;
result = 1;
while (i <= num) {
result = result * i;
i++;
}
System.out.println(num + "! = " + result);
System.out.println();
System.out.print("Do you want to continue? ");
str = console.next();
System.out.println();
}
}
}
You need to set result = 1 inside your outer while loop, not before it. What's happening here is that the numbers you're multiplying are getting multiplied by the result from the previous iteration of the outer while loop.
You are not resetting the result when you iterate for a new value.
Just reset the result to 1 before you start calculating factorial
e.g. -
while(str.charAt(0) == 'y')
{
result =1;
I think you're having a logical error with your if statement. Having a range of 1-10, your if statement should look something like this:
if(userInput>0 && userInput<=10);
Also, as what David Wallace has stated, you need to re-initialize your variable i back to 1 after your inner "factorial while loop" finishes. In this way, your variable i would always have the starting value of 1 whenever it enters your inner factorial while loop.
I would begin by creating a lookup table for the valid range of factorials. That might be done iteratively, create a fact array and fill it. Something like,
int[] fact = new int[10];
int i;
fact[0] = i = 1;
while (i < fact.length) {
fact[i] = (i + 1) * fact[i - 1];
i++;
}
Then you can use an infinite loop with your Scanner (breaking on non-integer input) and the fact lookup table like,
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter a number 1-10 for the factorial (or a "
+ "non-number to quit): ");
if (!scan.hasNextInt()) {
break;
}
i = scan.nextInt();
if (i < 1 || i > 10) {
System.out.println("NUMBER OUT OF RANGE!");
continue;
}
System.out.printf("%d! = %d%n", i, fact[i - 1]);
}
I am doing a simple fraction test class. I want my program to do this.
IF a user input 0 > the loop repeats until the user enter a number that not 0
In my class, it not doing that. I tried to mixed it with do while conditions with if statements plus initializing if the statement true or false. Im stuck so please I need help.
Here my fraction Class:
import java.util.*;
public class FractionTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
boolean valid = true;
int num, den;
den = 0;
do {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den == 0 && valid) {
System.out.println("denominator cannot be zero");
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
}
} while (den != 0 && !valid);
System.out.println("Decimal is " + result(num, den));
}
public static double result(int x, int y) {
return (x / y);
}
}
Here the program once I run the Test
The question is not completely clear but I think that you are asking that whenever denominator becomes zero continue loop else calculate answer and return value. I made some changes to your code according to that
public class FractionTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
boolean valid = true;
int num, den;
den = 0;
while(den == 0) {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den == 0 && valid) {
System.out.println("denominator cannot be zero");
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
}
}
System.out.println("Decimal is " + result(num, den));
return;
}
public static double result(int x, int y) {
return ((1.0)*x / y);
}
}
change the code in the main-method to this:
Scanner input = new Scanner(System.in);
int num, den;
do {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den!=0)
System.out.println("Decimal is " + result(num, den));
else
System.out.println("Denominator shouldnt be 0");
} while (den == 0);
input.close();
There was no need to initialized 'den' as the value is anyways replaced.
There was no need of having 'boolean variable' as its value never change
if den==0, no need to re-ask for inputs within the loop as the loop should
anyways re-run
I would just separate your input validations:
System.out.println("Please enter the numerator: ");
num = input.nextInt();
do{
System.out.println("Please enter the denominator: ");
System.out.println("denominator cannot be zero");
den = input.nextInt();
} while (den == 0);
System.out.println("Decimal is " + result(num, den));
If you need an input validation for your numerator just do a do while around that. Also your boolean value for valid is always true. Never modified to be false. Logic (x ^ True) will always be if x is true.
The idea is to create an average for money made in a week by day and my average must be calculated in a method that is called in the main method. That is the easy part, but the part I'm stuck on is if a number less than zero is entered it should give me an error message and re-prompt the user for a better value. I'm not looking for a handout here just for someone to tell me what I've been doing wrong if it is simple and easy or a pointer in the right direction.
import java.util.*;
public class weeklyAveragesClient2
{
public static void main(String [] args)//output averages in format
{
averageCash();
}
public static double averageCash()//use array and loop to calculate weekly average
{
double [] cashMoney;
cashMoney = new double[7];
Scanner scan = new Scanner(System.in);
int j = 0;
String s = "ERROR";
while (j < 7)
{
double num = cashMoney[j];
if (num == 0)
{
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
}
else if(num > 0)
{
System.out.print("Please enter an amount for day " + (j+1) +": ");
cashMoney[j] = scan.nextDouble();
j++;
}
else
{
System.out.println("Error: negative number please enter a number > 0");
}
}
System.out.println("Calculating...");
double sum = 0;
for (int i = 0; i < cashMoney.length; i++)
{
sum = sum + cashMoney[i];
}
double average = sum / (double)cashMoney.length;
System.out.println("Average: " + average);
return average;
}//end averageCash
}//end class
I've added some comments that will hopefully provide food for thought.
// This will *always* be zero at first because you haven't called scan.nextDouble() yet
// and zero is the default value. So when you run the program, it will output "Error
// please enter a number > 0" before doing anything else
if (num == 0) {
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
} else if (num > 0) {
System.out.print("Please enter an amount for day " + (j + 1) + ": ");
cashMoney[j] = scan.nextDouble();
j++;
} else {
// If we get into this state, the user will never be invited to enter
// another number, since the last entered number was negative, so
// num == 0 is false, and
// num > 0 is false, so
// we'll end up back here. In fact, you'll enter an infinite loop and
// this message will be printed over and over again.
System.out.println("Error: negative number please enter a number > 0");
// cashMoney[j] = scan.nextDouble(); // <-- try prompting the user again
}
Please also consider indenting your code correctly. It will greatly increase readability. If you're using an IDE like Eclipse, you can select Source > Format.
I have to make a program that allows the user to enter integer numbers until he press '0'. The program has to print:
1)The total number of the entered numbers
2) The number of the positive ones
3) The average of the positive ones
4) The number of the negative ones
5) The sum of the negatives
So far, all I could do is make the "enter untill '0' is pressed" and find the number of the entered numbers, which is a lot for me and my programing skills. I am having troubles trying to find out if the number is positive or negative. Probably I am not comparing them right, so I would love if I get a little help from someone advanced.
Here's my code so far:
import java.io.*;
class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
EnteredNumbers++;
str = br.readLine();
} while(!str.equals("0"));
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Firstly as pointed out Integer.parseInt is used in java to convert from String to int.
Secondly you need to have a extra variable to store and accumulate the total of positive numbers too. I have added a try-catch exception block to handle errors.
Here is a code for reference.
import java.io.*;
public class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
int PositiveSum = 0; // Added extra variable
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
try{
do {
EnteredNumbers++;
str = br.readLine();
int num = Integer.parseInt(str);
if (num>0)
{
Positive++;
PositiveSum+=num;
}
else if (num<0)
{
Negative++;
NegativeSum+=num;
}
} while(!str.equals("0"));
AveragePositive = (double)PositiveSum/(double)Positive;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
catch (java.lang.NumberFormatException e)
{
System.out.println("Wrong format");
}
}
}
Output if there are no errors
Enter '0' to quit.
Enter Numbers:
1
5
5
-5
-5
0
You have have entered 5 numbers!
You have have entered 3 Positive numbers!
The Average of the Positive Numebers is 3.6666666666666665!
You have have entered 2 Negative numbers!
The Sum of the Negative numbers is -10!
check by parsing String to int
Integer.parseInt(str)>0 //positive number
Integer.parseInt(str)<0 //negative
do {
EnteredNumbers++;
str = br.readLine();
int number= Integer.parseInt(str);
if(number>0){ //do positive stuffs}
else if(number<0){//do negative stuffs}
} while(!str.equals("0"));
Hope the below code achieves what you want to do
import java.io.*;
class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
double AveragePositive = 0;
double PositiveSum = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
EnteredNumbers++;
str = br.readLine();
if(Integer.parseInt(str) > 0){
Positive++;
PositiveSum = PositiveSum + Integer.parseInt(str);
AveragePositive = PositiveSum/Positive;
}
if(Integer.parseInt(str) < 0){
Negative++;
NegativeSum = NegativeSum + Integer.parseInt(str);
}
} while(!str.equals("0"));
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Create a list and keep adding the numbers into List. You should do something like:
List<Integer> numberList = new ArrayList<Integer>();
do {
str = br.readLine();
int number = Integer.parseInt(str);
} while(number != 0);
And then use for loop to do count like:
int negativeNumberSum = 0;
int positiveNumberSum = 0;
int positiveNumberCounts = 0;
for (int i =0; i<numberList.size(); i++) {
if (numberList.get(i) >= 0) {
positiveNumberSum += numberList.get(i);
positiveNumberCounts ++;
} else {
negativeNumberSum += numberList.get(i);
}
}
//print average of positive as positiveNumberSum /(double) positiveNumberCounts if positiveNumberCounts != 0
//print average of positive as negativeNumberSum / (double)(numberList.size() - positiveNumberCounts) same if (numberList.size() - positiveNumberCounts) != 0
//print positive count as positiveNumberSum and same for negative.
//
Try using Integer.parseInt() to get an int from your string str, and checking to see if the integer is < 0 (negative) or > 0 (positive)
I have added an extra variable called PositiveSum to assist with the AveragePositive calculation.
In order to perform this calculation, you need to ensure the value is an Integer so I have added the parse statement.
class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
int PositiveSum = 0;
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
EnteredNumbers++;
str = br.readLine();
int number = Integer.parseInt(str);
if(number<0) {
Negative++;
NegativeSum += number;
} else if(number>0) {
Positive++;
PositiveSum += number;
}
} while(!str.equals("0"));
AveragePositive = PositiveSum / EnteredNumbers;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Change your do-while loop: it is using Strings, not integers:
do {
EnteredNumbers++;
num = sc.nextInt();
} while(num != 0);
Also, you need to import the scanner utility:
import java.util.Scanner;
Don't use a BufferedReader, but use:
static Scanner sc = new Scanner(System.in);
Also, you would want to use a checker for your positive and negative numbers inside your do-while loop:
if(Integer.parseInt(num)<0) { Negative++; }
else { Positive++; }
I've also added a try-catch statement to handle an error if someone doesn't enter an int:
try {
num = sc.nextInt();
}
catch(Exception e) {System.out.println("Invalid integer"); System.exit(0); }
I added a little bit of code that takes the 0 off when it prints the numbers, as I realise it will include 0 when you type it in to exit.
Change your class statement to public, it's just programming:
public class Nums {
Also, I add a negative-number counter in the main code, and an averager.
Here is the complete code, to avoid confusion:
import java.io.*;
import java.util.Scanner;
public class prime {
static Scanner sc = new Scanner(System.in);
public static void main(String args[])
{
int EnteredNumbers = 0;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
double AveragePositive = 0;
int num = 0;
int PosTotal = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
try {
num = sc.nextInt();
}
catch(Exception e) {System.out.println("Invalid integer!"); System.exit(0); }
if(num<0) { Negative++; NegativeSum += num; }
if(num>0){ Positive++; PosTotal += num; }
EnteredNumbers++;
} while(num != 0);
AveragePositive = PosTotal / Positive;
EnteredNumbers -= 1;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numbers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Hope it helps!
Note I have trial-tested it, and it works brilliantly. If you have any errors with this please tell me :)