Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

totalCans = scan.nextInt(); if(totalCans < 0) { System.out.println(\"Number of c

ID: 3629420 • Letter: T

Question

totalCans = scan.nextInt();
if(totalCans < 0)

{
System.out.println("Number of cans needed has to be greater than 0.");
System.out.println("Quitting Program.");
System.exit(0);

}
else
{
totalCans = scan.nextInt();
}
if (scan.hasNextDouble())
{
System.out.println("Error");
System.exit(0);
}
else
{
totalCans = scan.nextInt();
}

This is what I have ^ , what I am trying to do is when they enter something less than 0 it prints the error, and also if they print a double, like 3.3, it returns an error as well. I can get one or the other to work, but not both. What do I need to do?

Explanation / Answer

please rate - thanks

try this instead of has double, doesn't have an integer,

import java.util.*;
public class main
{public static void main(String [] args)
{Scanner scan = new Scanner(System.in);
int totalCans;
System.out.print("Enter number of cans: ");
if (!scan.hasNextInt())
{
System.out.println("Error");
System.exit(0);
}
else
{
totalCans = scan.nextInt();
if(totalCans < 0)

{
System.out.println("Number of cans needed has to be greater than 0.");
System.out.println("Quitting Program.");
System.exit(0);

}

}}

}