I am fairly new to Java and I am trying to write a small program that asks a user to enter 3 integers between 1-10, stores them in an array and then adds up the integers and tells the user the answer. I have written this so far and it works:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 3 numbers in the range 1 to 10: ");
for (int i = 0; i < numArr.length; i++) {
numArr[i] = keyboard.nextInt();
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My problem is I am also meant to validate the input as in if they enter a double, a string or a number outside the 1-10 range. I have tried a while loop but I just cannot get the program to work, below is what I have so far. If I take out the first while loop the second one works i.e. it checks if it is an integer:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < numArr.length; i++) {
//check if between 1 and 10
while (i > 10 || i < 1) {
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt()) {
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
numArr[i] = keyboard.nextInt();
}
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My question is how do I get it to check if it is an integer and if it is the range 1-10?
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
int[] numArr = new int[3];
int sum=0,x;
Scanner keyboard = new Scanner(System.in);
for(int i=0; i<numArr.length; i++)
{
//check if between 1 and 10
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt())
{
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
x = keyboard.nextInt();
if(x>0 && x<=10)
numArr[i]=x;
else{
System.out.println("Retry Enter a number in the range 1 to 10:");
i--;
}
}
for (int counter=0; counter<numArr.length; counter++)
{
sum+=numArr[counter];
}
System.out.println("The sum of these numbers is "+sum);
}
}
To check simple use Integer.parseInt() and catch the NumberFormatException (together with Scanner.next()).
Once format is correct you can do an int comparison (i>0 && i<11).
I suggest you to use NumberUtils under org.apache.commons.lang.math
It has isDigits method to check whether given string contains only digits or not:
if (NumberUtils.isDigits(str) && NumberUtils.toInt(str) < 10) {
// your requirement
}
Note that toInt returns zero for big numbers!
Maybe for just this reason adding a whole library seems unnecessary but for bigger projects you will need such libraries like Apache Commons and Guava
You can wrap the System in into a BufferedReader to read whatever the user has to input, then check if its an 'int' and repeat input from user.
I have modified your code a little bit to make it work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Feb11a {
public static void main(String[] args) throws NumberFormatException, IOException
// You may want to handle the Exceptions when calling the getInt function
{
Feb11a tester = new Feb11a();
tester.perform();
}
public void perform() throws NumberFormatException, IOException
{
int[] numArr = new int[3];
int sum = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < numArr.length; i++)
{
int anInteger = -1;
do
{
// First get input from user.
System.out.println("Enter a number in the range 1 to 10: ");
anInteger = getInt(in);
} while (anInteger > 10 || anInteger < 1); // then check for repeat condition. Not between 1 and 10.
numArr[i] = anInteger; // set the number into the array.
}
for (int counter = 0; counter < numArr.length; counter++)
{
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
public int getInt(BufferedReader br) throws NumberFormatException, IOException
{
String str = br.readLine();
int toReturn = Integer.parseInt(str);
return toReturn;
}
}
Related
Question:
I need to create an array that holds 1000 integers ranging from 1-100. I then need to ask the user for an input and find out if the number the user has input is present in the array. If its not, then I have to output the message that it is not in the array.
I populated the array with random numbers, just need to find out how to search for the number in the array. I tried using a while loop to condition the for loop, but cant because the random generator and searcher would be in the same loop. Is there a way to linearly search for the number?
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int[] numbers = new int[1000];
System.out.println("Please enter a number: ");
int n = Integer.parseInt(reader.nextLine());
for(int i = 0; i < 1000; i = i + 1)
{
numbers[i] = (int)(Math.random()*100);
}
}
}
Try this
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] numbers = new int[1000];
boolean found = false;
System.out.println("Please enter a number: ");
int n = Integer.parseInt(reader.nextLine());
for(int i = 0; i < 1000; i = i + 1)
{
numbers[i] = (int)(Math.random()*100);
}
for(int i =0; i < 1000; i++){
if(numbers[i] == n){
found = true;
System.out.println(numbers[i] + " Appears first at index " + i);
break;
}
}
if(!found){System.out.println("Number " + n + " is not in the list");}
}
This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0" which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[i]);
++j;
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[i] + " ");
}
}
}
You need to work more about on for loops and study how to iterate values in for loop, the problem in your i,j variables.
Here I fix your code.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
//for 5 inputs you need loop
for(;i<NUM_VALS;i++){
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
}
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[j]);
//++j; //no need to increment as you already did in for loop
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[j] + " ");// userNum[0] = your last value which you reverse
}
}
}
Here is a solution using the collections framework:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final List<Integer> numbers = new ArrayList<>();
System.out.println("Enter any number of integers. (whitespace delimited. enter a non-integer to quit.): ");
while (scnr.hasNextBigInteger()) {
final int n = scnr.nextInt();
System.out.println("Parsed: " + n);
numbers.add(n);
}
System.out.println("Done reading user input.");
System.out.println("Your input: " + numbers);
Collections.reverse(numbers);
System.out.println("Your input reversed: " + numbers);
}
}
I have provided you with a solution. This is a clean way of doing it.
nextInt() reads the next integer that the user inputs. Notice that this will throw a InputMismatchExceptionif the user does not input a integer as value.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> input = new ArrayList<Integer>();
//Simple loop that will read 5 user inputs
//and add them to the input list
for(int i = 0; i < 5; i++){
input.add(scanner.nextInt());
}
//print the 5 values
for(Integer val : input){
System.out.println(val);
}
//reverse the 5 values
Collections.reverse(input);
//print the 5 values again, but they are now reversed
for(Integer val : input){
System.out.println(val);
}
}
I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps
Hi I am fairly new to java and trying to familiarize myself to it by doing some exercises online.
How do i properly code the while loop so that everytime the user input is wrong it asks the same question again and does not proceed to the next line of code
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
boolean checker = true;
while (checker){
for (int i = 0; i < entries; i++){
int input;
int addToList;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
grade.add(input);
if (input >= 0 && input<= 100) {
}else {
System.out.println("invalid input try again..");
checker = false;
}
}
}
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade){
sum+= grades;
}
mean =(double)sum/count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
Your logic is backwards. You want the loop to continue if the input is incorrect. There are two ways to fix this:
Change while(checker) to while(!checker)
Change checker=false to checker=true after printing the error message. And set checker=false in the if branch.
It might help if you change the name of your checker variable to something that reads more directly. For example isInputCorrect reads very nicely when you write while(!isInputCorrect) and it also makes it more clear what the values of true and false represent.
try this :
boolean checker = true
for(int i=0;i< entries;i++){
int input;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
while(checker){
if(input >= 0 && input<= 100){
grade.add(input);
checker = false;
}else{
System.out.println("invalid input try again..");
}
}
checker = true;
}
You could try this
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
for (int i = 0; i < entries; i++) {
int input;
do{
input = dataIn.nextInt();
if (input >= 0 && input <= 100) {
grade.add(input);
}else{
System.out.println("invalid input try again..");
}
}while(!(input >= 0 && input <=100));
}
dataIn.close();
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade) {
sum += grades;
}
mean = (double) sum / count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
instead of doing while(checker)
make a loop for while(running)
then send it to the keyboard.nextInt()
if its the wrongAnswer than it will loop, if its correct than set running to false
and have code that follows the while loop
The program is meant to count how many even numbers that have been inputted by the user. However, when the user inputs even numbers along with odd numbers the program crashes. But when the user enters all odd or even the program works fine. I can't seem to find the error either as the error message returns:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AllEven.getEven(AllEven.java:52)
at AllEven.read(AllEven.java:41)
at AllEven.main(AllEven.java:10)
Java Result: 1
The code for the program is below and any help would be greatly appreciated
import java.util.Scanner;
public class AllEven
{
private static int evenCount;
private static int[] evenArray;
private static int count;
public static void main (String args [])
{
read();//LINE 10
}
public static int [] read ()
{
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the size of the array");
int arrayIn = scanner.nextInt();
if (arrayIn == 0)
{
System.out.println("No Array");
}
else
{
System.out.println("------------------");
}
int userArray [] = new int [arrayIn];
for (int i = 0; i < userArray.length; i++)
{
System.out.println("Please enter a value for position: " + i);
arrayIn = scanner.nextInt();
userArray[i] = arrayIn;
if (arrayIn % 2 == 0)
{
evenCount++;
}
}
getEven(userArray);//LINE 41
return userArray;
}
public static int [] getEven(int[] userArray)
{
if (evenCount > 0)
{
evenArray = new int [evenCount];
for (int i = 0; i < userArray.length; i++)
{
evenArray[count] = userArray[i]; //LINE 52
count++;
}
print (evenArray);
}
else
{
System.out.println("No even numbers found");
}
return evenArray;
}
public static void print (int [] evenArray)
{
System.out.println();
System.out.println("Even numbers in the array are: ");
for (int i = 0; i < evenArray.length; i++)
{
System.out.println(evenArray[i]);
}
}
}//endprogram
userArray.length is not always equal to evenCount
problematic code
evenArray = new int [evenCount];
for (int i = 0; i < userArray.length; i++)
{
evenArray[count] = userArray[i];
Your even count is less than the size of the user array, yet you are indexing into the even array count times. You are incrementing count each time you get an item from the input array, and the input array will always be larger than the even array if you enter both even and odd numbers.