public class FileAddClient {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanfile = new Scanner(System.in);
System.out.println("What is the exact name of your file?");
String doc = scanfile.next();
Scanner scanint = new Scanner(new File(doc));
int number1 = scanint.nextInt(), number2 = scanint.nextInt(),
number3 = scanint.nextInt(), number4 = scanint.nextInt(),
number5 = scanint.nextInt(), number6 = scanint.nextInt();
int sum = number1 + number2 + number3 + number4 + number5 + number6;
System.out.println("The sum of the numbers that typed is " + sum);
}
}
How can I ensure that the user enters at least 2 numbers into the file and that the only data types in the file are numbers? I am not sure how to navigate through this problem. I tried making a while loop, but, unfortunately, that is not working. Any help would be appreciated.
The method .nextInt() will throw an exception (specifically an InputMismatchException) in case the input is not an int or there is none.
You can handle that exception with a try-catch block, like this:
try {
// ... use nextInt ...
}
catch(InputMismatchException e) {
// print error message
}
My solution to this uses a while loop. The hasNextInt() function just checks if the input is of type int.
public class FileAddClient {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanfile = new Scanner(System.in);
System.out.println("What is the exact name of your file?");
String doc = scanfile.next();
Scanner scanint = new Scanner(new File(doc));
int count = 0;
int sum = 0; //total sum of numbers
while ( scanint . hasNextInt() ) { //makes sure that the input is of type int
count ++; //counts the number of correct inputs
sum += scanint.nextInt();
}
if ( count < 2 ) // file has one number or zero numbers
System.out.println ( "File has less numbers than expected. Please fix it." );
else if ( count > 6 ) //file has more than 6 numbers
System.out.println ( "File has more than 6 numbers." );
else // file has two numbers or more
System.out.println("The sum of the numbers that typed is " + sum);
}
}
Related
Here is my while loop. The program sums up integers until a negative number is input. At that point the loop should break and it should print "Goodbye". However it is adding the negative number each time before it says goodbye. Im not sure what is going wrong here. Please help?!
import java.util.Scanner;
public class While {
public static void main(String[] args)
{
int input = 5;
int sum = 0;
while(input >= 0)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
sum = sum + input;
System.out.println("Running total: " + sum );
}
System.out.println("Goodbye!" );
}
Test:
Please enter a positive integer:
5
Running total: 5
Please enter a positive integer:
10
Running total: 15
Please enter a positive integer:
-1
Running total: 14
Goodbye!
I do not want to get the return value of 14, it should simply say Goodbye!
You need to use the break keyword. Your loop will always finish so the check on the while only happens after you've added the negative number. You could change to this:
while(true)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
if(input <0){
break;
}
sum = sum + input;
System.out.println("Running total: " + sum );
}
Or this:
while(input >= 0)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
if(input <0){
break;
sum = sum + input;
System.out.println("Running total: " + sum );
}
}
Or to avoid if statements entirely if needed (though that isn't the point of loops):
while(input >= 0)
{
sum = sum + input;
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
System.out.println("Running total: " + sum );
}
Here was my solution:
while(input >= 0)
{
sum = sum + input;
System.out.println("Running total: " + sum );
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
}
System.out.println("Goodbye!" );
}
by calculating the sum at initialization and before the first integer is entered. It appears to work the way I want now. Thanks for your help.
I am supposed to ask the reader to input a number and then check if it's between 500 and 1000, so i can add up the digits. But i don't know how to check if the number is between the interval.
import java.util.Scanner;
public class AddNumbers {
public static void main(String[]args){
Scanner input = new Scanner (System.in);
//Prompt user to enter number
System.out.println("Enter a number between 500 and 1000:");
String number;
number=input.nextLine();
//Get digits from number
char numberDigit1 = number.charAt(0);
char numberDigit2 = number.charAt(1);
char numberDigit3 = number.charAt(2);
//initialize variable
String constant=500;
String constant2=1000;
while (number.CompareTo(constant)){
System.out.println("The sum of the digits is: " + ((number.charAt(0) + (number.charAt(1) + (number.charAt(2))))));
}
while (number.CompareTo(constant)){
if (number<=0)
System.out.println("****ERROR: THE NUMBER MUST BE BETWEEN 500 AND 1000****");
}
while (number.CompareTo(constant2)){
if (number>=0)
System.out.println("****ERROR: THE NUMBER MUST BE BETWEEN 500 AND 1000****");
}
input.close();
}
}
This will not compile
String constant=500;
String constant2=1000;
But why are you even using Strings?
int constant=500;
int constant2=1000;
number=input.nextLine();
int realInt = Integer.parseInt (number);
if (realInt >= constant && realInt <= constant2) {
// you still have `number` so
int result = 0;
for (char ch : number.toCharArray ())
{
result += Integer.valueOf ("" + ch);
}
System.out.println (result);
}
Instead of reading input as a string and converting it into an int, we can directly validate integer input e.g:
Scanner scanner = new Scanner (System.in);
int input;
if(!scanner.hasNextInt()){
System.out.println("Input must be a number.");
}else{
input = scanner.nextInt();
if(input < 500 || input > 1000){
System.out.println("****ERROR: THE NUMBER MUST BE BETWEEN 500 AND 1000****");
}
}
I have to write a program that asks the user to enter an integer value. After each value, the user has to respond with a "y" or a "n" if he/she wants to continue with the program, and each number the user enters is stated as either odd or even.
I have done this so far with a do-while loop, but I am confused on how to get the averages of the values the user enters. How would you get the average for all the numbers entered?
Here is my code so far:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
do {
int num, count = 0;
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.equals("y"));
}
}
From the Question looks like following things need to handled,
haven't add mechanism for addition into single variable.
put all variable to out from do...while loop body...
created additional variable according to requirement.
see all this things covered by me with following code snippet.
do something likewise,
String answer = "";
double sum = 0; // use for storing addition to all entered values..
int num, count = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter any number : ");
num = scan.nextInt(); // getting input from user through console
sum = sum + num; // add every input number into sum-variable
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next(); // ask for still want to repeat..
count++;
} while (answer.equals("y"));
System.out.println("Average is : " + sum + "/" + count + " = "+ (sum /count));
In order to calculate Average, you need 2 things: Sum of all numbers and Count of all numbers involved in the Average calculation.
Your sum and count which involved in the Average calculation needs to be out of the do..while scope in order for them to be known at the calculation stage.
I also took the liberty of fixing your code a little bit
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
int count = 0;
int sum = 0;
String answer = "";
do {
System.out.print("Enter any number : ");
int num = scan.nextInt();
boolean isEven = (num % 2 == 0);
System.out.println(num + " is an " + (isEven ? "even" : "odd") + " number.");
sum += num;
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.toLowerCase().equals("y"));
System.out.println("Average: " + (sum/count));
}
}
Change your code like this:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
int avr =0;
int num, count = 0;
do {
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
avr += num;
answer = scan.next();
count++;
} while (answer.equals("y"));
avr = avr /count;
System.out.println("The avreage of value is:" + avr );
}
}
avr is average. that means when you input an integer. we add num and avr . and when finish looping. we divideto count. like this:
1-5-9-11
avr = 1+5+9+11;
count = 4;
avr = avr/4;
I'm trying to write a program that gets a series of five double String values from a user and then attempt to convert those Strings to a double using the Double.parseDouble() method. The trouble I'm having is that I have to enter two values before the next "Please enter a number" pops up. Here is the output I've been getting:
Please enter a number 1: 4
3
Please enter a number 2: 5
4
Please enter a number 3: 3
4
Please enter a number 4: 5
6
Please enter a number 5: 4
2
The average is: 3.8
Here is my code:
import java.io.*;
import java.util.Scanner;
public class theman {
public static void main(String[] args) throws IOException{
// Variables
int counter;
int userEntries = 5;
double sum = 0;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
// Creating a new Scanner
Scanner scanner = new Scanner(System.in);
// Loop for the five entries
for (counter = 1; counter <= userEntries; counter++) {
String input = "";
System.out.print("Please enter a number " + counter + ": ");
input = br.readLine();
double number = Double.parseDouble(input);
sum += scanner.nextDouble();
}
// Print statements
System.out.println("The average is: " + sum / userEntries);
} // End of method header
} // End of class header
What is the best way to correct this problem? I'm assuming it's because of the sum += scanner.nextDouble(); but I need it to increment so I really can't delete it.
You already have the double, so there's no need to use Scanner.nextDouble(). The nextDouble() method scans the next token of the input as a double. What you should be doing is sum += number.
final int userEntries = 2;
Scanner in = new Scanner(System.in);
double sum = 0.0;
for (int counter = 1; counter <= userEntries; ++counter) {
System.out.printf("Please enter a number %d: ", counter);
sum += in.nextDouble();
}
System.out.printf("The average is: %.2f%n", sum / userEntries);
Here's an updated code -
import java.io.*;
import java.util.Scanner;
public class theman {
public static void main(String[] args) throws IOException{
// Variables
int counter;
int userEntries = 5;
double sum = 0;
// Creating a new Scanner
Scanner scanner = new Scanner(System.in);
// Loop for the five entries
for (counter = 1; counter <= userEntries; counter++) {
System.out.print("Please enter a number " + counter + ": ");
sum += scanner.nextDouble();
}
// Print statements
System.out.println("The average is: " + sum / userEntries);
} // End of method header
} // End of class header
This question already has an answer here:
java.lang.IllegalStateException: Scanner closed
(1 answer)
Closed 4 years ago.
I'm trying to write a program where it will tell you:
The number of integers in a list entered by the user at the command prompt
The sum of those integers.
But I'm having some trouble figuring out how to access those individual numbers. I've tried writing the while loop already, as well as the "if" statements.
Another issue I'm having is that when I try to run my program, I get this error message: Exception in thread "main" java.lang.IllegalStateException: Scanner closed.
NOTE: I'm very new to Java so a simpler solution that mainly uses scanners, next methods, and hasNext methods would be better!
import java.util.Scanner;
public class InputParser
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("How many values do you want to parse?: ");
int numValues = scanner.nextInt();
System.out.println("Please enter " + numValues + " values: ");
while(scanner.hasNextLine())
{
if(scanner.hasNext())
{
if(scanner.hasNextInt())
{
int sum;
System.out.println("The sum of your values is: " + sum + ".");
}
}
scanner.close();
}
}
}
Your code should be like:
Scanner scanner = new Scanner(System.in);
System.out.print("How many values do you want to parse?: ");
int numValues = scanner.nextInt();
int[] values = new int(numValues);
int sum = 0,i=0;
while(i<numValues)
{ i++;
System.out.print("Enter "+ i+" number : ");
values[i-1] = scanner.nextInt();
sum+= values[i-1];
}
System.out.println("Sum is : "+sum);
scanner.close();
Haven't really consider error handling.
I don't understand why you would ask the user how many numbers they want to sum ahead of time. Basically, your code can be simplified and handle an arbitrary number of numbers. It's also a really bad idea to call close() on a Scanner wrapping System.in (Because you can't re-open it, and if you extract it into a method you will create a hard to debug and find issue). Anyway, you could do something like,
Scanner scanner = new Scanner(System.in);
// System.out.print("How many values do you want to parse?: ");
// int numValues = scanner.nextInt();
System.out.println("Please enter values to sum (type quit to stop)");
int sum = 0; // <-- start at 0.
int count = 0;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
count++;
sum += scanner.nextInt();
} else {
String str = scanner.next();
if (str.equalsIgnoreCase("quit")) {
break; // <-- end the loop.
}
System.out.printf("The value '%s' is not an int (quit to stop).%n", str);
}
}
System.out.printf("The sum of your %d values is %d.%n", count, sum);
// scanner.close(); // <-- Really Bad Idea
Edit Based on your comment,
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter values to sum (type quit to stop)");
while (scanner.hasNextLine()) {
String str = scanner.nextLine();
str = (str != null) ? str.trim() : "";
if (str.equalsIgnoreCase("quit")) {
break; // <-- end the loop.
} else if (str.length() == 0) {
continue;
}
int sum = 0; // <-- start at 0.
int count = 0;
Scanner scan2 = new Scanner(str);
while (scan2.hasNextInt()) {
count++;
sum += scan2.nextInt();
}
System.out.printf("The sum of your %d values is %d.%n", count, sum);
}