Check if user enters negative numbers straight away? - java

I am trying to make a program where the user enters a number and the program computes the max and min and keeps asking untill it encounters negative.
DETAILED DESCRIPTION:-
However if the user enters a negative number at start up it should print "Max and min are undefined!" and end.
But if a positive number is entered the program prints max and min ,still keeps asking for more numbers untill a negative number is encountered ,seeing negative number it still prints max and min and then ends.
Is there a way to do this?
What i have tried is given below:-
import java.util.Scanner;
public class NegativeNum {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
double num = keys.nextInt();
double Max = num+0.5;
double Min = num-0.5;
if(num<0) {
System.out.println("Max and Min undefined");
}
while(num>0) {
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
num = keys.nextInt();
}
{
num = num*-1;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("Number is Negative! System Shutdown!");
System.exit(1);
}
}
}

Just calculate the maximum and minimum value during iteration
while(num>0) {
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
num = keys.nextInt();
if(Math.abs(num) > max) {
max = Math.abs(num);
}
if(Math.abs(num) < min) {
min = Math.abs(num);
}
}
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("Number is Negative! System Shutdown!");
System.exit(1);

import java.util.Scanner;
public class NegativeNum {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
double num = keys.nextInt();
double Max = num+0.5;
double Min = num-0.5;
if(num<0) {
System.out.println("Max and Min undefined");
System.exit(1);
}
while(true) {
double temp_num = num;
num = Math.abs(num);
Max = num+0.5;
Min = num-0.5;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
if ( temp_num < 0 )
break;
System.out.println("\nEnter another: ");
num = keys.nextInt();
}
System.out.println("Number is Negative! System Shutdown!");
}
}

import java.util.Scanner;
public class NegativeNum {
private static int entryCount = 0; // Count the Number of Entries
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
double num = keys.nextInt();
double Max = num+0.5;
double Min = num-0.5;
while(true) {
if( num < 0 && entryCount == 0) { // Make sure if it's first entry and it's negative too
System.out.println("Number is Negative! System Shutdown!");
System.exit(1);
}
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
num = keys.nextInt();
entryCount++;
}
}
}

This code successfully runs all the cases:-
import java.util.Scanner;
public class class2
{
public void positive(double num)
{
double Max = num+0.5;
double Min = num-0.5;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
}
public void negative(double num,String k)
{
double Max = num+0.5;
double Min = num-0.5;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
if(k=="terminate")
{
System.out.println("System is shutting down");
System.exit(1);
}
System.out.println("\nEnter another: ");
}
public static void main(String []args)
{
class2 obj=new class2();
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
boolean bol=true;
String k="";
double num = keys.nextInt();
int count=1;
if(num<0 && count ==1)
{
k="terminate";
count=count+1;
System.out.println("Max and Min undefined");
System.exit(1);
System.out.println("\nEnter another: ");
num = keys.nextInt();
}
while(bol==true)
{
while(num>0)
{
count=count+1;
obj.positive(num);
num = keys.nextInt();
}
while(num<0 && count!=2)
{
k="terminate";
obj.negative(num,k);
num = keys.nextInt();
}
count=count+1;
}
}
}

Related

How to add a roll dice function and a check guess function?

How to add a roll dice method and a check guess method?
My code:
package oui;
import java.util.Scanner;
public class dicecalc {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
int numGuess;
System.out.println("Enter the number the numer the dice will roll: ");
numGuess = kb.nextInt();
int dice1=(int)(Math.random()*6+1);
int dice2=(int)(Math.random()*6+1);
int sum = dice1 + dice2;
System.out.println("Roll: total = " + sum);
{
if (sum != numGuess) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
}
I need to have this assignment resubmitted because I forgot those things but I don't know how to add it. Please help. I already have tried for days.
Here's one possible basic layout. Replace the ??? with some code!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number the numer the dice will roll: ");
int numGuess = kb.nextInt();
int sum = sumOfTwoDiceRolls();
System.out.println("Roll: total = " + sum);
{
if (!checkGuess(numGuess, sum)) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
public static int sumOfTwoDiceRolls() {
return ??? ;
}
public static int singleDiceRoll() {
// Math.random() * (max - min + 1) + min
return (int)(Math.random() * (6 - 1 + 1) + 1);
}
public static boolean checkGuess(int guess, int numberToGuess) {
return ??? ;
}
}

What's wrong with this method...?

import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
boolean first = true;
int sum = 0;
int count = 0;
int avg = 0;
while(true){
int number = scanner.nextInt();
boolean isAnInt = scanner.hasNextInt();
if(isAnInt){
sum += number;
count++;
avg = Math.round((sum)/count);
}else{
System.out.println("SUM = " + sum + " AVG = " + avg);
break;
}
scanner.nextLine();
}
scanner.close();
}
}
When input is "1, 2, 3, 4, 5, a", I think it's not reading the input 5, resulting sum = 10 and avg = 2! Why it's happening?
By the way it's just a method not whole code!
When scanner.nextInt() provides you '5', the next line 'scanner.hasNextInt() is false. Just change line order
import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
boolean first = true;
int sum = 0;
int count = 0;
int avg = 0;
while(true){
boolean isAnInt = scanner.hasNextInt();
if(isAnInt){
int number = scanner.nextInt();
sum += number;
count++;
avg = Math.round((sum)/count);
}else{
System.out.println("SUM = " + sum + " AVG = " + avg);
break;
}
scanner.nextLine();
}
scanner.close();
}
}
you can also clean the code like
import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
int sum = 0;
int count = 0;
while( scanner.hasNextInt() ){
int number = scanner.nextInt();
sum += number;
count++;
}
scanner.close();
double avg = Math.round((sum)/count);
System.out.println("SUM = " + sum + " AVG = " + avg);
}
}

Please explain that how this Java code identify maximum number from user input?

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();
}

How can I get this program to print out the numbers the user entered?

Here's my code:
import java.util.*;
public class InputSum
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
while (i != -1)
{
j += i;
i = input.nextInt();
}
System.out.println("Entered Number: " + i);
System.out.println("The Sum: " + j);
}
}
As of now my output is:
Entered Number: -1
The Sum: (Sum of the numbers entered)
Print them inside the loop :
while (i != -1)
{
System.out.println("Entered Number: " + i);
j += i;
i = input.nextInt();
}
System.out.println("The Sum: " + j);
Or it you want to print them in a single line :
List numbers = new ArrayList<Integer>();
while (i != -1)
{
numbers.add(i);
j += i;
i = input.nextInt();
}
System.out.println("Entered Numbers: " + numbers);
System.out.println("\nThe Sum: " + j);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out
.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
while (i != -1) {
numbers.add(i);
j += i;
i = input.nextInt();
}
System.out.println("Entered Numbers: ");
for (int a = 0; a < numbers.size(); a++) {
System.out.print(" " + numbers.get(a));
}
System.out.println("The Sum: " + j);
}
This should work to print the numbers. You can use an arraylist to store the numbers and then if you need them for later calculations they are still stored in the arraylist.
package net.rajkannan.stackoverflow;
import java.util.*;
public class InputSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out
.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
String numbers = "";
while (i != -1) {
j += i;
numbers = numbers + i + " ";
i = input.nextInt();
}
System.out.println("Entered Numbers: " + numbers);
System.out.println("The Sum: " + j);
}
}

Java enhanced for loop picking the highest and lowest number

I'm working on this project, and I've been stuck for a while now.
I am what they say a "noob" in the wonderful world of Java programming..
I've managed to get the highest number working. It only prints 4 times now, but I can't get the lowest number to work.
public class MainClass {
public static void main(String[] args) {
StringConversion test = new StringConversion();
// Make our input / output object
int d1;
int d2;
int d3;
int d4;
int d5;
ConsoleIO io = new ConsoleIO();
io.writeOutput("Click below this message, type something and press ENTER");
// Tell it to read something from the
// console (the program waits for this to happen):
String input1 = io.readInput();
String input2 = io.readInput();
String input3 = io.readInput();
String input4 = io.readInput();
String input5 = io.readInput();
// etc. etc. Here you can see that the value was correctly
// stored in our local 'input' variable.
// string omzetten naar int
String i1 = input1;
String i2 = input2;
String i3 = input3;
String i4 = input4;
String i5 = input5;
d1 = Integer.parseInt(i1);
d2 = Integer.parseInt(i2);
d3 = Integer.parseInt(i3);
d4 = Integer.parseInt(i4);
d5 = Integer.parseInt(i5);
int antwoord = d1+d2+d3+d4+d5;
// totaal rekensom
System.out.println("total: ");
System.out.println(d1+d2+d3+d4+d5);
// gemiddelde som
int gemiddelde = antwoord / 5;
System.out.println("avarage: ");
System.out.println(gemiddelde);
// hoogste getal
int zeeslag[] = {d1, d2 , d3 , d4 , d5};
int max;
int min;
// het op dit moment maximum
max = zeeslag[0];
min = zeeslag[0];
//array doorlopen
for (int i: zeeslag) {
if (i > max){
max = i;
System.out.println("highest number: " + i);
}
else if(i<min){
min = i;
System.out.println("lowest number: " + i);
}
}
// laagste getal
input1 = io.readInput();
input2 = io.readInput();
input3 = io.readInput();
input4 = io.readInput();
input5 = io.readInput();
}
}
You need to print the max and min and not i. Also, they should be after the for loop because you need to compare with all the elements in the array before printing the maximum and minimum value.
for (int i : zeeslag) {
if (i > max) {
max = i;
} else if (i < min) {
min = i;
}
}
// print the max and min after the for
System.out.println("highest number: " + max); // print the max value and not i
System.out.println("lowest number: " + min); // print the min value and not i
You can make your code quite a bit shorter:
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
int[] zeeslag = new int[5];
int total = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
// Make our input / output object
Scanner sc = new Scanner(System.in);
for(int i = 0; i <5; ++i)
{
System.out.println("Enter number " + (i+1) + " of " + 5 + ":" );
zeeslag[i] = sc.nextInt();
total += zeeslag[i]; // total and average
if(zeeslag[i] < min)
min = zeeslag[i];
if(zeeslag[i] > max)
max = zeeslag[i];
}
System.out.println("total: " + total);
System.out.println("Average: " + (total/5));
System.out.println("Lowest: " + min);
System.out.println("Greatest: " + max);
}
}
Check the whole array inside the loop and then print the result.
max = zeeslag[0];
min = zeeslag[0];
for (int i: zeeslag) {
if (i > max){
max = i;
}
else if(i<min){
min = i;
}
}
System.out.println("highest number: " + max);
System.out.println("Lowest number: " + min);

Categories