Hello need help with this program where I need it to ask the user for 2 integers (Y and Z which is where i get my error) where one will be a min and the other a max and i don't understand why it doesn't run properly.
import java.util.Scanner;
public class sampleMethods {
public static void main(String[] args) {
printYikes();
int x = 12;
x = getAnInt("Please enter an integer min and a max seperated by a space: ",y, z);
System.out.println("\nThat was a valid Number.");
System.out.println("You entered " + x + "!");
System.out.println( "x is " + x );
x = doubleMyNumber(x);
System.out.println( "x is " + x );
x = tripleMyNumber(x);
System.out.println( "x is " + x );
}
static void printYikes() {
System.out.println("Yikes");
}
static int doubleMyNumber(int a) {
int b = a * 2;
return b;
}
static int tripleMyNumber(int a) {
int c = a * 3;
boolean odd = isOddOrEven(c);
if (odd) {
System.out.println("Number is Odd!!");
} else {
System.out.println("Number is Even!!");
}
return c;
}
static boolean isOddOrEven (int d) {
boolean isOdd = false;
if (d % 2 == 0) {
isOdd = false;
} else {
isOdd = true;
}
return isOdd;
}
static int getAnInt(String prompt, int min, int max) {
Scanner keyboard = new Scanner(System.in);
boolean numberError = false;
int enteredNumber = 0;
String enteredString = "";
do {
try {
System.out.print(prompt);
enteredString = keyboard.nextLine(); //Read into a string
enteredNumber = Integer.parseInt(enteredString.trim()); //then cast as a integer
numberError = false; //if we haven't bailed out, then the number must be valid.
if (enteredNumber < min || enteredNumber > max) {
numberError = true;
System.out.println("Your entry: \"" + enteredNumber + "\" is out of range...Please try again");
}
} catch(Exception e) {
System.out.println("Your entry: \"" + enteredString + "\" is invalid...Please try again");
numberError = true; //Uh-Oh...We have a problem.
}
} while (numberError == true ); //Keep asking the user until the correct number is entered.
return enteredNumber;
}
}
You haven't declared y,z;
Write this after int x = 12 :
int y,z;
The function int getAnInt(String prompt, int min, int max) expects three parameters:
prompt - the string to ask the user.
min - the minimum value you'll accept.
max - the maximum value you'll accept.
It returns an int that is guaranteed to be between min and max. That's what the function does. Nothing more; nothing less. You can't use it to ask for two numbers separated by a space.
It sounds like you used to have an existing program that asked for a single value, with arbitrary min and max values (0 and 100? 1 and 10?).
Now you want to change this program to first ask for the minimum and maximum values, and then do the previous processing. You need to ask the user for two more numbers - and those numbers need a min and max specified too!
Replace int x = 12; with:
int min, max, x;
min = getAnInt("Please enter an integer minimum between 0 and 1000000: ", 0, 1000000);
max = getAnInt("Please enter an integer maximum larger than minimum and less than 1000001: ", min, 1000001);
x = getAnInt("Please enter an integer x between minimum and maximum: ",min, max);
Related
if a user 8,10,50 why this code only shows 50 why doesn't it show 8,10 as there is condition number > max. 8,10 are also > 0.
package com.Zeeshan;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
int max = 0;
int min = 0;
while (true ) {
System.out.println("Enter Number");
boolean isNext = scanner.hasNextInt();
if (isNext) {
int NewMax = scanner.nextInt();
if (NewMax > max) {
max = NewMax;
}
if (NewMax < min) {
min = NewMax;
}
}
else {
break;
}
scanner.nextLine();
}
System.out.println("max " + max + "min " + min);
scanner.close();
}
}
NewMax < min this condition will always false due to min = 0 at beginning.
You need to take care that your first number must set to min.
When you run your code, you should look at the first 2 numbers. You should set min to the lowest of the 2 and max to the highest. From then on, you can compare the next number with min and max.
UPDATE: try this
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
// We assume there are at least 2 input numbers.
int max = 0;
int min = 0;
int first = scanner.nextInt();
int second = scanner.nextInt();
if (first > second) {
max = first;
min = second;
}
else {
max = second;
min = first;
}
while (true ) {
System.out.println("Enter Number");
boolean isNext = scanner.hasNextInt();
if (isNext) {
int NewMax = scanner.nextInt();
if (NewMax > max) {
max = NewMax;
}
if (NewMax < min) {
min = NewMax;
}
}
else {
break;
}
scanner.nextLine();
}
System.out.println("max " + max + "min " + min);
scanner.close();
}
This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
I am working on a project for my college, so far code is working fine, except when a program tries to calculate the average all input, it always gives the wrong answer.
Ex:
Test input:
3
-4
5
12
-7
0 (to exit the loop)
Result ->
sum: 9
Counter: 5
Average = 1.0 ? It should be 1.8
If anyone could help, please give me some advice.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int counter = 0;
int intInput;
int intLargest;
int intSmallest;
int intEven = 0;
int intOdd = 0;
int intSum = 0;
String strMessage = "Enter a series of value (0 to quit)";
System.out.print(strMessage);
System.out.println();
System.out.print("Enter Integer value?" + "\n");
intInput = sc.nextInt();
intLargest = intInput;
if (intLargest == 0)
{
intLargest = 0;
}
else
{
intLargest = intInput;
}
/////////////////////////////////////////////////////////////
intSmallest = intInput;
if (intSmallest == 0)
{
intSmallest = 0;
}
else
{
intSmallest = intInput;
}
while(intInput != 0)
{
{
if (intInput > intLargest)
{
intLargest = intInput;
}//Get the largest value
else if (intInput < intSmallest)
{
intSmallest = intInput;
}//Get the smallest value
if ((intInput%2) == 0)
{
intEven++;
}//Get number of Even value
else if ((intInput%2) != 0)
{
intOdd++;
}//Get number of Odd value
}
intSum = intSum + intInput;
intInput = sc.nextInt();
counter++;
}
/********************************************/
double doubleAvg = 0;
if (counter > 0)
{
doubleAvg = intSum / counter;
}
/***************************************************/
System.out.println();
System.out.print("Smallest = " + intSmallest +"\n");
System.out.print("Largest = " + intLargest + "\n");
System.out.print("Total Entered = " + counter + "\n");
System.out.print("Even Number = " + intEven + "\n");
System.out.print("Odd Number = " + intOdd + "\n");
System.out.print("Average = " + doubleAvg + "\n");
System.out.print("SUM: " + intSum + "\n");
}
}
Both intSum and counter are declared as int. And in case of dividing int by int the result will also be int. So result of division is 1 and then it is converted to double and you get 1.0. To get correct result declare intSum as double.
import java.lang.Math;
import javax.swing.JOptionPane;
public class IntegerNumber
{
//declaring main variable used throughout the whole code
public static void main(String[] args)
{
//declare variable
int menuNumber;
String input = JOptionPane.showInputDialog("Select What You want to do: \n1: Calculate the total of the squares of the first inputted natural numbers. \n 2: Get the mean of the first N odd natural numbers. \n 3: Determine if the inputted number is a prime number. \n 4: Return a Fibonacci number. \n 5: Exit Program.");
menuNumber = Integer.parseInt(input);
if (menuNumber == 1)
{
TotalSquares();
}
else if (menuNumber == 2)
{
OddNumberMean();
}
else if (menuNumber == 3)
{
PrimeNumber();
}
else if (menuNumber == 4)
{
FibonacciNumber();
}
else if (menuNumber == 5)
{
System.exit(0);
}
}
public static double TotalSquares()
{
int N;
double total;
int k;
String input = JOptionPane.showInputDialog("Enter a number between 1 and 20 to find the total squared numbers of");
N = Integer.parseInt(input);
total = 0;
for(k=1; k<=N; k++);
total +=(k*k);
return total;
System.out.println("Your total is = " + total);
}
public static double OddNumberMean()
{
int N;
int i;
String input = JOptionPane.showInputDialog("Enter a number between 1 and 50 to find the mean of the odd numbers");
N = Integer.parseInt(input);
double total = 0;
for(i=0;i<=N; i++);
{ total+= 2*i +1;};
System.out.println("The mean is = " + (total/N));
}
public static double PrimeNumber()
{
int N;
int g;
String input = JOptionPane.showInputDialog("Enter a number between 2 and 200, determine whether or not the number is prime");
N = Integer.parseInt(input);
for (g = 2; g<N; g++)
{
if (N % g == 0)
{
System.out.println("The number is not prime");
}
}
System.out.println("The number is prime");
}
public static int FibonacciNumber(int N)
{
String input = JOptionPane.showInputDialog("Compute and return a Fibonacci number");
N = Integer.parseInt(input);
if (N==0)
return 0;
else if(N==1)
return 1;
else
return FibonacciNumber(N-1) + FibonacciNumber(N-2);
}
}
I keep getting this error:
IntegerNumber.java:33: error: method FibonacciNumber in class
IntegerNumber cannot be applied to given types;
FibonacciNumber();
^ required: int found: no arguments reason: actual and formal
argument lists differ in length
and I can not find a way to fix it. Any help appreciated as I can't seem to find the answer on other posts.
Replace
public static int FibonacciNumber(int N)
{
...
N = Integer.parseInt(input);
with
public static int FibonacciNumber()
{
...
int N = Integer.parseInt(input);
You called FibonacciNumber() without parameters, whereas the original method declaration wanted a parameter int N.
Furthermore for methods, fields and variables use an initial small letter: fibonacciNumber, n.
Firstly, i'm very new to java, so excuse the mess of the code below.
My current program takes input from StdIn and prints out the highest and lowest values entered.
Can this be extended to ask the useר again if they entered an integer that isn't positive? I'm almost certain that a while loop can do the trick, but not sure if one executed with my current code. Once again, i'm very new and come from a music background, so my logical sense isn't the best.
public class PositiveIntegers
{
public static void main(String[] args)
{
do {
StdOut.println("Enter your integers:");
} while (StdIn.isEmpty());
int max = StdIn.readInt();
int min = max;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
if (value > max) max = value;
if (value < min) min = value;
}
do {
StdOut.println("Maximum = " + max + ", Minimum = " + min);
return;
} while (StdIn.readInt() > 0);
}
}
Cheers
You can do it by just adding a single if statement to check if the number given is negative, then print the message to add it again.
Check the ENHANCED code below:
public class PositiveIntegers
{
public static void main(String[] args)
{
StdOut.println("Enter your integers:");
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
// Adding the if-statement here to check if number is negative.
if(value < 0){
StdOut.println("You entered negative number, try positive numbers.");
// just reset the max and min variables..
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
continue;
}
if (value > max) max = value;
if (value < min) min = value;
}
StdOut.println("Maximum = " + max + ", Minimum = " + min);
}
}
First of all you don't need this many loops in your program. Take the user input in while loop and then print that number outside of loop.
Remember to use try-catch for error handling for user input.
Try this way :
try{
do {
StdOut.println("Enter your integers:");
} while (StdIn.isEmpty() && StdIn.readInt() < 0);
}catch(Exception ex){
StdOut.println("Error while taking user input !");
}
A quick answer to this would be
public class PositiveIntegers {
public static void main(String[] args) {
do {
StdOut.println("Enter your integers:");
} while (StdIn.isEmpty());
int max = StdIn.readInt();
int min = max;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
if (value < 0) {
StdOut.println("Please enter a positive integer");
} else {
if (value > max) max = value;
if (value < min) min = value;
}
}
do {
StdOut.println("Maximum = " + max + ", Minimum = " + min);
return;
} while (StdIn.readInt() > 0);
}
}
I made sure to change as little as possible, but this should give you the result you are looking for.
In this problem, I need to ask the user to input the number of integers they will put in. Then, they will manually input each number. Finally, the program counts the sum and max of all even inputs.
I am having trouble with initiating the value. If I set them to zero, there would be an issue if all the numbers were negative even numbers.
import java.util.*;
public class Exercise07 {
public static void main(String[] args) {
Scanner thing = new Scanner(System.in);
evenSumMax(thing);
}
private static void evenSumMax(Scanner stuff) {
System.out.print("How many integers?");
int times = stuff.nextInt();
int evenSum = 0;
int evenMax = 0;
System.out.println("Number 1 : ");
int value = stuff.nextInt();
if (value % 2 == 0) {
evenSum += value;
evenMax = value;
}
for (int i = 2 ; i <= times; i++) {
System.out.print("Number " + i + " : ");
value = stuff.nextInt();
if (value % 2 == 0) { // if even
evenSum += value;
if (evenMax < value) {
evenMax = value;
}
}
}
System.out.println("Even sum = " + evenSum + ", even max = " + evenMax);
}
}
Set evenMax to the minimum possible number Integer.MIN_VALUE