This is the code:
import java.util.Scanner;
public class javapractice {
public static void main(String[] Args) {
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number :");
int number = input.nextInt();
boolean nextint = input.hasNextInt();
if (nextint) {
count++;
XX += number;
} else {
break;
}
input.nextLine();
}
int YY = XX/count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();
}
}
I want the output to print the sum of the numbers entered and when I enter let's say a word like "Hello", it breaks out of the loop and prints Sum 0 0 and AVG = 0.
The issue I'm having is that whenever I enter the number, it asks me for it two times and doesn't take the next number in the row after that and whenever I enter a string variable lets say "I", it outputs Inputmismatch. What would be the fix to this?
Don't mix nextLine() and all the other next methods; pick one. If you want to read a line's worth of text, just call next(), but if you want the input to flow as 'everytime a user hits enter, read another token', which you usually do, update the definition of 'what defines a token?': scanner.useDelimiter("\r?\n");.
Try this code:
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number: ");
if (input.hasNextInt()) {
count++;
XX += input.nextInt();
} else {
break;
}
}
int YY = XX / count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();
Related
I am new to java and have just learned how to use user input. I have a for loop that goes through 10 times with user input to ask for a number. If the number is invalid, it should print "Invalid number" and not count towards the increasing for loop. Instead, it just loops forever saying 'Invalid number'.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int sum = 0;
Scanner scanner = new Scanner(System.in);
for(int i = 1; i<=10; i++){
System.out.println("Enter number #" + i + " ");
boolean validInt = scanner.hasNextInt();
if(validInt){
int num = scanner.nextInt();
sum += num;
} else{
System.out.println("Invalid Number");
i--;
}
}
System.out.println("Sum was " + sum);
scanner.close();
}
}
The problem is you are updating the iterator i at 2 places.
The better way is to update it according to the condition.
I would also suggest you to make use of wrapper classes for safe integer conversions and handle the exceptions properly like done in the following code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int sum = 0;
Scanner scanner = new Scanner(System.in);
for(int i = 1; i<=10; ){
System.out.println("Enter number #" + i + " ");
String input = scanner.nextLine();
try{
int num = Integer.parseInt(input);
sum += num;
i++; // If input is a valid integer, then only update i
}catch(NumberFormatException e){
System.out.println("Invalid Number");
}
}
System.out.println("Sum was " + sum);
scanner.close();
}
}
I think you also can tweak the code using hasNextInt() directly in the while loop.
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
sum += num;
}
I needed to add a
scanner.nextLine();
After the if and else statement to clear the scanner in both situations.
I am new to java coding. I have written the code below to the problem: How can I write a statement that can be used in a Java program to read two integers and display the number of integers that lie between them, including the integers themselves?
I couldn't run it in Eclipse. When I try to run it through Eclipse, it tells me "The selection cannot be launched, and there are no recent launches. Anyway, can someone please tell me if this code correct? Are there any errors in it?
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:10");
int first = s.nextInt();
System.out.print("Enter the second integer:20");
int second = s.nextInt();
System.out.println("How many integers are between "+first+" and "+second+"???");
}
}
Please put some more effort on your query, for sure you can come up with your answers by yourself and you will learn faster. For now You can refer to below answer.
package com.barnwal.jeetendra.learn;
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:");
int first = s.nextInt();
System.out.print("Enter the second integer:");
int second = s.nextInt();
System.out.println("How many integers are between " + first + " and "
+ second + "???");
// To print number of integer between entered number
if (second > first) {
System.out.println("Answer : " + (second - first - 1));
// To print the numbers
for (int i = first + 1; i < second; i++)
System.out.print(i + " ");
} else {
// To print number of integer between entered number
System.out.println("Answer : " + (first - second - 1));
// To print the numbers
for (int i = second + 1; i < first; i++)
System.out.print(i + " ");
}
}
}
To avoid the unnecessary if-else statement to look which value is bigger, you can also use the functionality of the class java.lang.Math like this
Scanner s = new Scanner(System.in);
System.out.print("Enter the first integer:");
int first = s.nextInt();
System.out.print("Enter the second integer:");
int second = s.nextInt();
int small = Math.min(first, second) ;
int big = Math.max(first, second);
System.out.println("How many integers are between " + small + " and " + big + "???");
System.out.println("Answer : " + (big - small + 1));
// To print the numbers
for (int i = small; i <= big; i++)
System.out.print(i + " ");
You can use looping like this:
if (first > second){
big = first;
small = second;
}
else if (second > first){
big = second;
small = first;
}
for (int i = small; i <= big; i++)
System.out.print(i + " ");
first of all, when you use resources (System.in) you should close them. You can do it with try-finally or you can use try-with-resources.
Here is your code:
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
try (Scanner s = new Scanner(System.in)){
System.out.print("Enter the first integer:10");
int first = s.nextInt();
System.out.print("Enter the second integer:20");
int second = s.nextInt();
System.out.println("How many integers are between "+first+" and "+second+"???");
if (first != second)
System.out.println("Answer: " + Math.abs(first-second - 1));
else
System.out.println("Answer: 0");
}
}
}
How about this:
int diff = second - first - 1;
let secont = 25 and first = 23 so the output will be:
25-23-1 = 1;
which is 24
I have a program here in java that asks the user to input ten integer numbers and would print out how many are ODD and how many are EVEN.
import java.io.*;
public class Count {
public static void main(String[] args) {
int i, , even_ctr=0, odd_ctr = 0;
String input = " ";
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
n = Integer.parseInt(input);
if(n % 2 == 0)
even_ctr++; //counter for even
if(n % 2 == 0)
odd_ctr++; //counter for odd
}System.out.println("EVEN: " + even_ctr + "\nODD: "+ odd_ctr);
}
}
I am trying to change the program by using only one counter instead of two counter. Anyone knows how?
import java.io.*;
public class NewClass {
public static void main(String[] args) {
int i,n, even_ctr=0;
String input = " ";
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
n = Integer.parseInt(input);
if(n % 2 == 0)
even_ctr++;
}System.out.println("EVEN: " + even_ctr + "\nODD: "+ (10-even_ctr));
}
}
Just keep the first counter incrementing for ODD number detection (OR EVEN but either of them). At the end of the computation, if ODD counter = 4, and total number of numbers entered are 10, then 10 - ODDcounter = 10 - 4 = 6 are the number of even numbers.
For this it looks like it would be equally useful to use the Scanner so that you can avoid the step of having to parse the string.This also would require you to import java.util.Scanner but you can use the scanner to take in strings or integers.
Scanner in = new Scanner(System.in);
int input;
int evenCount = 0;
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.nextInt();
}catch(IOException e){
System.out.println("Error!");
}
if(input % 2 == 0)
evenCount++;
}
System.out.println("EVEN: " + evenCounter + "\nODD: "+ (10 - evenCounter);
Include in.close(); at the end of the method to close the scanner or the reader which ever you use.
package evenoddten;
import java.util.Scanner;
public class EvenOddTen {
public static void main(String[] args) {
int num1 = 0, num2, even = 0, count = 0;
Scanner scr = new Scanner(System.in);
System.out.print("Total Nos:");
num2 = scr.nextInt();
while(count<num2) {
System.out.println("Enter no:");
num1 = scr.nextInt();
if (num1%2 == 0) {
even = even + 1;
}
count = count+1;
}
System.out.println("Even nos are:"+even);
System.out.println("Odd nos are:"+(count - even));
}
}
I am new to stackoverflow. First I would like the program to loop with a price, then a question(enter another price?), price, then a question and so on. Below is the output.
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Please enter a price:
99
Please enter a price:
22
However it will keep looping at the end with "Please enter a price:". I want it to do:
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Enter another price?
y
Please enter a price:
22
Can anyone help me with this? Also, sometimes the average does not update fully. Thanks :)
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice;
System.out.println("Please enter a price: ");
integer = input.nextInt();
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
}
while (addPrice.equalsIgnoreCase("Y"));
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
You need to replace your while with an if
if (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
In fact, addPrice is not modified within your second while loop, and so you have an infinite loop.
In order to do the averaged price, you're in the right way but not in the right place :P
count = count +1 and sum = sum + integer should be done after each integer = input.nextInt(). In your current code, you don't increment the counter and don't add the integer for the last input.
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
}
}
while (addPrice.equalsIgnoreCase("Y"));
Finally here is a improved version which avoid the use of if.
int sum = 0;
int integer = 0;
String addPrice = "Y";
while( "Y".equalsIgnoreCase(addPrice) ) {
System.out.println("Please enter a price: ");
integer = input.next();
sum += integer ;
count++;
System.out.println("Enter another price? ");
addPrice = input.next();
}
int avg = sum / count ;
What you should do is change your logic a bit. You need to repeat two actions, entering a price and asking if the user wants to enter another price. Only one loop is required for this.
do {
System.out.println("Please enter a price: ");
integer = input.nextInt();
count = count + 1;
sum = sum + integer;
System.out.println("Enter another price? ");
addPrice = input.next();
} while (addPrice.equalsIgnoreCase("Y"));
i think you want something like this:
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice = "Y";
while (addPrice.equalsIgnoreCase("Y")){
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++;
sum += integer;
System.out.println("Enter another price? ");
addPrice = input.next();
}
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
Try this:
EDIT Added min and max.
public class ReadInPrice {
public static void main(String[] args) {
//better to use 2 scanners when dealing with both string and int
//one for string ; one for ints
Scanner strScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
boolean enter = true;
int sum = 0;
int count = 0;
int min=Integer.MAX_VALUE;
int max=0;
while (enter) { //while user wants to keep adding numbers
System.out.println("Please enter a price: ");
int price = intScanner.nextInt();
if(price < min)
min=price;
if(price > max)
max=price;
sum += price;
count++;
System.out.println("Enter another price? ");
String answer = strScanner.nextLine();
if (!answer.equalsIgnoreCase("Y"))
enter = false; //user doesn't want to keep adding numbers - exit while loop
}
double average = (double)sum / count;
System.out.println("Average = " + average);
System.out.println("Min = " + min);
System.out.println("Max = " + max);
strScanner.close();
intScanner.close();
System.exit(0);
}
}
The problem I am having is I have to input 50 integers, and when I hit space it won't recognize the number and when I hit enter then my output box is very very long for just 1 digit #'s
static final int MAX = 50;
public static void main(String[] args)
{
int index;
int check;
int infants = 0, children = 0, teens = 0, adults = 0;
System.out.println("This program will count the number of people "
+ "and how many of that age group cameto the college fair.");
System.out.println("**********************************************************");
System.out.println("Please enter the integer value data:");
int [] peopleTypes = new int[MAX];
Scanner keyboard = new Scanner(System.in);
for(index=0; index<MAX; index++)
{
peopleTypes[index] = keyboard.nextInt();
if(peopleTypes[index] == 1)
infants = infants + 1;
if(peopleTypes[index] == 2)
children = children + 1;
if(peopleTypes[index] == 3)
teens = teens + 1;
if(peopleTypes[index] == 4)
adults = adults + 1;
else
index = index-1;
System.out.print("");
}
System.out.println("The number of infants that were at the college fair was: " + infants);
System.out.println("The number of children that were at the college fair was: " + children);
System.out.println("The number of teenagers that were at the college fair was: " + teens);
System.out.println("The number of adults that were at the college fair was: " + adults);
Try to use this:
public class ScannerDelimiter {
public static void main(String[] args) {
Scanner scanner = new Scanner("12, 42, 78, 99, 42");
scanner.useDelimiter("\\s*,\\s*");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
}
} /* Output:
12
42
78
99
42
In this case the delimiter is
<any number of spaces or tabs>,<any number of spaces or tabs>
You could read your input as a String and try to parse it:
String s = "";
int i = 0;
for (index = 0; index < MAX; index++) {
s = keyboard.next();
try {
i = Integer.valueOf(s.trim());
} catch (NumberFormatException nfe) {
// log exception if needed
System.out.println(s + " is not a valid integer.");
continue;
}
// do the rest
peopleTypes[index] = i;
//...
}
Console input in Java is line buffered. You won't get anything until the user hits enter. Hitting space, just adds a space to the line you will get. Note: hitting backspace deletes a character which you won't see either.