I am in a low level java programming class, and I am having trouble figuring something my professor assigned to us. We originally made a program that added integers that were placed in an arraylist. She then asked us to make it as user friendly as possible, without having a specific amount of integers the user inputs. So I came up with this:
public class CalculatorREDONE
{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add. ");
Scanner input = new Scanner(System.in);
do
{
numbers.add((int) input.nextInt()); //inserting input into the arraylist
System.out.println("The sum is " + sum(numbers)); //test output
}while(input.hasNextInt()); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(ArrayList<Integer> list)
{
int total = 0;
for (int i = 0; i < list.size(); i++)
{
total += list.get(i);
}
return total;
}
}
Sorry for the clutter of comments, I'm trying to show any of you my mindset behind what I did. Thank you so much in advance for anyone that has any suggestions!
See if this helps where in you take an input from user to terminate the program.
public class CalculatorREDONE {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add or -1 to exit");
Scanner input = new Scanner(System.in);
// boolean nextAvailable = true;
while(true)
{
String nextVal = input.nextLine();
if(nextVal.isEmpty()) {
break;
}
numbers.add(Integer.parseInt(nextVal)); //inserting input into the arraylist
// System.out.println("The sum is " + sum(numbers)); //test output
} //while (!input.next().); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(List<Integer> list) {
int total = 0;
for (int i = 0; i < list.size(); i++) {
total += list.get(i);
}
return total;
}
}
Try this -- it takes the input as a string, checks the length. If the user just hits enter the length will not be greater than zero. This catches the number exception from the parseInt by confirming the user has ended their list.
Note that I didn't include your sum portion since it wasn't relevant to the question of breaking the loop. You'll need to re-add
import java.util.Scanner;
import java.util.ArrayList;
public class CalculatorREDONE
{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add. ");
Scanner input = new Scanner(System.in);
String userinput = "xx";
int nextnum = 0;
while (userinput.length() > 0) {
try {
userinput = input.nextLine();
nextnum = Integer.parseInt(userinput);
numbers.add(nextnum);
System.out.println("Taken");
} catch (NumberFormatException e) {
System.out.println("Inputs complete");
}
}
System.out.println(numbers);
input.close();
}
}
Related
I want the user to be able to input the amount of numbers they specified BEFORE the code keeps running. Currently, the user is only able to input one number before the code continues. How do i keep the code from running until a certain amount of numbers are inputted?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter the amount of numbers you want the array to store: ");
// reads # of # user wants to enter
n = sc.nextInt();
// creates an array in the memory of length 10
int[] array = new int[10];
System.out.println("Enter "+n+" numbers ");
for (int i = 0; i < n; i++) {
// reading array elements from the user
array[i] = sc.nextInt();
double sum = 0;
double mode = 0;
double variance = 0;
double deviation = 0;
for (i = 0; i < 2; i++)
sum = sum + array[i];
//MEAN
mode = sum / 5;
sum = 0;
for (i = 0; i < 2; i++) {
sum = sum + Math.pow((array[i] - mode), 2);
}
//VARIANCE
variance = sum / 5;
//DEVIATION
deviation = Math.sqrt(variance);
//Standard
System.out.println("Standard Deviation is: " + deviation);
//mode
System.out.println("Mode is:" + mode);
//Variance
System.out.println("Variance is: " + variance);
}
}
}
I tried to let the user decide how many numbers should be in the array, then input that many numbers.
However, when i run the code, it doesn't give them enough time to type in the numbers.
I need a way to stop this from happening.
The first thing I discovered is that at no time are you using the variable "n" to create a constant value array, so it will always be an array of 10 elements.
One recommendation that I give you is that you do not use the "Scanner" class because it can give you problems if you ask the user for different types of data. Instead it uses BufferedReader because it is more direct. Here is an example of your exercise but fixed:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
private static Number getNumber(BufferedReader reader) throws IOException {
// Get input content
String line = reader.readLine();
return Double.parseDouble(line);
}
public static void main(String[] args) throws IOException {
// Auto closeable elements
try (InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader buffered = new BufferedReader(reader)) {
// Print message
System.out.print("The amount of numbers you want: ");
// Program variables here
final int totalSize = getNumber(buffered).intValue();
int[] arrayStore = new int[totalSize];
// Iterate all elementos of the array
for (int i = 0; i < totalSize; ++i) {
// Another message
System.out.print("Insert one number: ");
// Ask for numbers
int nextNumber = getNumber(buffered).intValue();
arrayStore[i] = nextNumber;
}
// TODO: Your logic program here
System.out.println(Arrays.toString(arrayStore));
}
}
}
If you were able to notice, the method that asks for the numbers does not check if the content is really a number, for that change the behavior of the getNumber method to the following:
private static Number getNumber(BufferedReader reader) throws IOException {
Number result = null;
do {
try {
result = Double.parseDouble(reader.readLine());
} catch (NumberFormatException e) {
System.err.println("The inserted content is not a valid number");
}
} while (result == null);
return result;
}
I hope it helps you in some way
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
Basically I have to prompt a user to enter 10 string values, and then in another loop print them in ascending order, then in a final loop, print them in descending order. My array is bringing back null, obviously because I am not prompting users to enter actual information into the array object. I am really stuck on this. I know I need to somehow reference the "userStrings[]" array in my first while loop. I keep researching and keep getting integer loops questions and For loops. This has to be a while loop. I just can no figure out how to get the userStrings[] to actually fill up when the user enters the values. How do I get it linked in the loop?
public class HomeWork10
{
public static void main(String[] args)
{
String[] userStrings = new String[10];
int count = 0;
int count2 = 0;
while (count < 10)
{
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
count++;
}
while (count2 < 1)
{
System.out.println(Arrays.asList(userStrings));
count2++;
}
}
}
You are not putting the values in the String[]
Do it like this:
while (count < 10) {
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
userStrings[count] = userInput;
count++;
}
Also, declare Scanner input = new Scanner(System.in) outside your while() {...}
See below code snippet may solve your problem.
package com.suresh;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class HomeWork10 {
public static void main(String[] args) {
String[] userStrings = new String[10];
int count = 0;
System.out.println("\t Reading Array Elements ");
while (count < 10) {
System.out.print("\t Please enter a string value : ");
Scanner input = new Scanner(System.in);
userStrings[count] = input.next();
count++;
}
System.out.println("\t PRINTING ORIGINAL ARRAY OF ELEMENTS ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
Collections.sort(Arrays.asList(userStrings), new StringAscComparator());
System.out.println("\t ASCENDING ORDER ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
System.out.println("\t DESCENDING ORDER ");
Collections.sort(Arrays.asList(userStrings), new StringDescComparator());
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
}
static class StringAscComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
static class StringDescComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
}
You created the array with 'String[] userStrings = new String[10];' and inside your while loop to access it you need to do something like this 'userStrings[0] = input.next()' This says the first item in the array userStrings will be set to input.next(). I'm not great at java so I'm not sure what input.next() will do though.
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;
}
}