How do I read different inputs from scanner in Java? - java

I need to get various integral inputs and then when -1 is entered, the program should show the largest, smallest, sum of all entered, number of values of all entered, and the mean of all values entered. I have started a loop to take various inputs but cannot find a suitable way to read them and then play with them. I have searched everywhere on the internet.
import java.util.Scanner;
public class Exercise16 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter a Positive integer or -1 to quit.");
while (!s.nextLine().equals("-1")) {
System.out.println("Please enter a Positive integer or -1 to quit.");
}
}
}

s.nextLine() reads your input
You should save it to a variable.
Also using a do-while to prevent the copied print statement
Scanner s = new Scanner(System.in);
String in; // where to save next input value
do {
System.out.println("Please enter a Positive integer or -1 to quit.");
in = s.nextLine();
// TODO: parseInt, check for positive number
} while (!in.equals("-1"));
If you want to track mins and maxes, you need two additional integer values.
If you want to track averages, you need a list.
Best of luck

You first need to read integer from command line. For that you have to use
s.nextInt();
Once you get this you have to get largest and smallest number, you can get these using 2 variables.
For average you can store sum and number of times user asked for input, 2 more variable. No need to store elements in list or some other storage.
If you want to see numbers entered than you have to store else you don't have to.
For storing use :
List<Integer> numbers = new ArrayList<Integer>();
For adding number you can use add method of List.
public static void main2() {
Integer laregst = Integer.MIN_VALUE;
Integer smallest = Integer.MAX_VALUE;
Integer sum = 0;
Integer count =0 ;
Scanner s = new Scanner(System.in);
int temp = s.nextInt();
while (temp != -1) {
if(temp > laregst){
laregst = temp;
}
if(temp < smallest){
smallest = temp;
}
sum += temp;
count += 1;
System.out.println("Please enter a Positive integer or -1 to quit.");
temp = s.nextInt();
}
System.out.println("Largest : "+(count == 0?"NA":laregst)+" Smallest : "+(count == 0?"NA":smallest)+" Mean : "+(count == 0 ? "NA" : ((sum *1.0/count))));
}

if you wont to read Multible Integers Value in Same Line you Can use s.nextInt() to read one Integer Value in each time

Related

Issues with loops? Program runs as it should but test keep failing. Java using TMCbeans

I am doing an open university course in Java, it's been smooth sailing up until now. We are covering loops in this section and the problem I am stuck on asks for the following.
Write a program that reads values from the user until they input a 0.
After this, the program prints the total number of inputted values
that are negative. The zero that's used to exit the loop should not be
included in the total number count.
This is my the program I have written and I have run the program and it works as it should, however I keep getting failed test back with the following statement.
When input was: 5 4 -3 1 0 "Give a number:" text should appear a total of 5 times. Now the count was 0 expected:<5> but was:<0>
Here is my code, as I said when I run the program locally it seems to work just as asked for.
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0){
break;
}
if (number >= 1){
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
You have two problems with the code :
In the number test line,you check if a number is greater than or equal to one (number >= 1), but you should check that it is less than 0 because it is need to be negative numbers. (In the question : the total number of inputted values that are negative)
You are using with scanner.nextLine() But you don't get a line, you get a number (Int if it's integers, double if it's decimal numbers) on you to change it to : scanner.nextInt() :
Here the code :
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());// Scanner number !!
if (number == 0){
break;
}
if (number < 0){ // Less then zero !!!
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
Your problem statement says that the count of negative numbers should be the output. But what you are returning is the count of positive numbers. Change the condition from if (number >= 1) to if (number < 0).
Hope this helps.
You need the total number of inputted values that are negative. So the condition in the while loop has to change from number >= 1 to number < 0.
Check this
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());
if (number == 0) {
break;
}
if (number < 0) {
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
Also, prefer to use nextInt() because you know your input is of integer type.
I could not get the exact problem. But some observations.
If you really input all numbers at the first ask and then hitting ENTER, obviously it would throw NumberFormatException as "5 4 -3.." is not a valid number and the loop wont proceed. Try input each number and hit ENTER.
Scanner must be closed. If you are using JDK 8, use "try (Scanner scanner = new Scanner(System.in)) {...}. This would automatically close the scanner.

How can I make an input read out multiple integers on a single line?

How can I make it so that I can prompt the user to input multiple integers on one line that are seperated by spaces. And if the first integer is 0 or less than 0 it will print out "Bad Input" when all the integers are inputted and the user presses enter. Also how can I make it so that when the user enters a negative number at the end of the line, it will stop entering numbers and make multiply all of them together.
This is what I have so far but i'm not sure I am doing this right.
import java.util.Scanner;
public class tempprime {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int count = 1;
String inputnumbers;
System.out.print("Enter integers: ");
inputnumbers = input.nextLine();
for (int i = 0; i < inputnumbers.length(); i++){
if (inputnumbers.charAt(i) == ' ')
count++;
}
int[] numbers = new int[count];
}
}
You already have it so the user can enter in values until they hit enter. Now you can do is use a split operation to break the string up into an array of values.
String[] values = inputnumbers.split('\s');
Then you could replace charAt with access to the array.
Alternatively, Scanner already allows the user to enter in as many integers as they need on the same line. nextLine() finds the first occurance of a new line, but you can use input.nextInt(), grabs the next int stopping at a space, multiple times and read them in one at a time. You can also check if there are any more values remaining using the scanners hasNext methods.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You can see an example of reading multiple ints below. The user can enter them in one at a time, or 3 at a time and should still work the same.
Scanner in = new Scanner(System.in);
System.out.print("Enter 3 ints:");
int a,b,c;
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
System.out.printf("A: %d B: %d C: %d", a, b ,c);

Why can't I have a user prompted varaible be the array size?

public class Sort {
public static void main(String[] args) {
int i = 1;
Scanner input = new Scanner(System.in);
// prompts the user to get how many numbers need to be sorted
System.out.print("Please enter the number of data points: ");
int data = input.nextInt();
// this creates the new array and data sets how large it is
int [] userArray = new int[data];
// this clarifies that the value is above 0 or else it will not run
if (data < 0) {
System.out.println("The number should be positive. Exiting.");
}
// once a value over 0 is in, the loop will start to get in all user data
else {
System.out.println("Enter the data:");
}
while (i <= data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
// this calls the sortArray method to sort the values entered
sortArray(userArray);
// this will print the sorted array
System.out.println(Arrays.toString(userArray));
}
}
I have set the array size equal to what the user inputs for how many variables they will be entering to be sorted. For some reason, Java only wants a set number instead of the number that is entered by the user. Is there a way to make this work?
First of all, there are a few mistakes in your code. You are checking if(data < 0) after you create your array with int[] userArray = new int[data];. You should check it before.
Furthermore, you will get ArrayIndexOutOfBoundsException because userArray[data] does not exist. Array indices start at 0, so the last index is data-1. You need to change your while-loop to while(i < data) instead of while(i <= data).
The problem is not that you have data instead of 10 as the length of the array. The problem is as I stated above: your while-loop.
Your issue is the while loop. Because arrays are 0 based and you need to only check if i < data. By setting it to <=, you are exceeding the array length and generating and ArrayIndexOutOfBoundsException
while (i < data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
You are over-indexing the array. A more standard way for inputting the data would be
for ( int i=0; i < data; i++ ) {
userArray[i] = input.nextInt();
}

Dynamic array in Java - so we can decide the size of an array according to user's input

I just wrote this basic program. It takes 5 values from the user and stores all of them in an array and tells the highest number.
import java.util.Scanner;
public class HighestNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int [] numbers = new int [5];
int max = numbers[0];
System.out.println("Enter " + numbers.length + " numbers:");
for (int i=0; i<numbers.length; i++) {
numbers[i] = input.nextInt();
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("The highest number is:" +max);
}
}
I'd like to take off the restriction of 5 numbers and allow the user to add as many numbers as he wants. How can I do that?
Appreciate the assistance. :)
Thanks
If the user knows the number of numbers in advance (before they enter the actual numbers):
Ask the user how many numbers they want to enter:
System.out.println("How many numbers?");
int numberOfNumbers = input.nextInt();
Use that as the array size:
int[] numbers = new int[numberOfNumbers];
If the user shouldn't need to know the number of numbers in advance (e.g. if they should be able to type "stop" after the last number) then you should consider using a List instead.
Alternatively, you could use an ArrayList and keep on adding elements until the user enters a blank line. Here is a tutorial on using ArrayList.
Some pseudocode could be:
numbers = new list
while true
line = readLine
if line == ""
then
break
else
numbers.add(convertToInteger(line))
...
The benefit of this approach is that the user does not need to even count how many numbers he/she wants to enter.

Terminating loops with strings. (Java)

Write a program that uses a while loop. In each iteration of the loop, prompt the user to enter a number – positive, negative, or zero. Keep a running total of the numbers the user enters and also keep a count of the number of entries the user makes. The program should stop whenever the user enters “q” to quit. When the user has finished, print the grand total and the number of entries the user typed.
I can get this program to work when I enter a number like 0, to terminate the loop. But I have no idea how to get it so that a string stops it.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
int num;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
while (num != 0) {
if (num > 0){
sum += num;
}
if (num < 0){
sum += num;
}
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Your strategy would be to get the input as a string, check to see if it is a "q", and if not convert to number and loop.
(Since this is your project, I am only offering strategy rather than code)
This is the rough strategy:
String line;
line = [use your input method to get a line]
while (!line.trim().equalsIgnoreCase("q")) {
int value = Integer.parseInt(line);
[do your work]
line = [use your input method to get a line]
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
String num;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
while (!num.equals("q")) {
sum += Integer.parseInt(num);
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Cuts down on your code abit and is simple to understand and gives you exactly what you want.
could also add an if statement to check if they entered another random values(so program doesn't crash if the user didn't listen). Something like:
if(isLetter(num.charAt(0))
System.out.println("Not an int, try again");
Would put it right after the while loop, therefore it would already of checked if it was q.
java expects an integer but we should give the same exception. One way to solve this problem is entering a String, so that if the user first pressing is the Q, never enters the cycle, if not the Q. We assume that the user is an expert and will only enter numbers and the Q when you are finished. Within the while we convert the String to number with num.parseInt (String)
Integer num;
String input;
while(!input.equal(q)){
num=num.parseInt(input)
if(num<0)
sum+=1;
else
sumA+=1;
}

Categories