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.
Related
Im trying to make this program work but im getting the error that it cant find the variable min and max in the system.out.print statement in main method. I guess it is because main doesnt know what those variables are since the MinMax destroys those variables once its ran. But how can I transfer the results over from my MinMax method so that results will be printed in system.out.print in main method statement?
class MethodMinMaxWithUnlimitedValues {
public static void main(String[]args) {
Scanner console = new Scanner (System.in);
int value;
char choice;
do{
System.out.print ( " enter value " );
value = console.nextInt();
isMinMax(value);
System.out.print ("enter more numbers? (y/n) ");
choice = console.next().charAt(0);
}
while (choice == 'y' || choice == 'Y');
System.out.print("min value is = " + min + " max value is = " + max);
}
public static void isMinMax (int n) {
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
if (n > max) {
max = n;
} else if (n < min) {
min = n;
}
}
}
Make them static and global
import java.util.Scanner;
class MethodMinMaxWithUnlimitedValues {
static int min = Integer.MIN_VALUE;
static int max = Integer.MAX_VALUE;
public static void main(String[]args) {
Scanner console = new Scanner (System.in);
int value;
char choice;
do{
System.out.print ( " enter value " );
value = console.nextInt();
isMinMax(value);
System.out.print ("enter more numbers? (y/n) ");
choice = console.next().charAt(0);
}
while (choice == 'y' || choice == 'Y');
System.out.print("min value is = " + min + " max value is = " + max);
}
public static void isMinMax (int n) {
if (n > max) {
max = n;
} else if (n < min) {
min = n;
}
}
}
NOTE: that can have side effects
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();
}
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);
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
In Java, I am having trouble running multiple loops using a single sequence of user-inputted integers. Individually, they run fine individually but together it prints out incorrect numbers.
I'm at a loss as to what is causing this problem.
Here is my code.
import java.util.Scanner;
public class SequenceTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers. " +
"Enter a non-integer to terminate");
int sequence = in.nextInt();
//Print One
int min = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input < smallest)
{
smallest = input;
}
}
System.out.println(smallest);
//Print Two
int max = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input > max)
{
max = input;
}
}
System.out.println(max);
//Print Three
int even = 0;
int odd = 0;
while(in.hasNextInt())
{
int input = in.nextInt();
if((input %2) == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println( even);
System.out.println(odd);
//Print Four
double total = 0;
int count = 0;
while (in.hasNextInt())
{
Int input = in.nextInt();
total = total + input;
count++;
}
double average = 0;
if (count > 0)
{
average = total / count;
}
System.out.println(average);
}
}
Your code is very fragmented, but it looks like you can achieve what you want with one loop since the loop condition is the same in all of them. This, of course, is only based on the vague description you gave us.
while(in.hasNextInt()) {
int input = in.nextInt();
if(condition1) {
//do stuff
} else if (condition2) {
//do other stuff
} else if (conditionN) {
//do other other stuff
} else {
//last of the stuff to do
}
}