Confused on this exercise, its asking me to create a loop which remembers multiple integers that the user inputted, and prints them out the exact same way. I'm confused on how to print the input without making it a list and not using any methods. I tried making input equal to i, but that doesn't output anything.
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int i = 0;
int i2 = 0;
ArrayList <Integer> name_input = new ArrayList<>();
while(true) {
System.out.print("print number:");
int input = Integer.valueOf(scanner.nextLine());
name_input.add(input);
if (input == -1) {
break;
}
i++;
}
while(i2 < i){
System.out.println(i);
i2++;
}
}
Original question: The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1.
Expand the functionality of the program so that after reading the numbers, it prints all the numbers received from the user. The number used to indicate stopping should not be printed.
Related
I cannot get out of while loop.
I do not why sc.hasNextInt() does not return false after last read number.
Should I use another method or is there a mistake in my code?
public static void main(String[] args) {
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int[] numbers = new int[sc.nextInt()];
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
**while ( sc.hasNextInt()) {**
numbers[index++] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
}
Do the following:
Use the input length as the end of the loop.
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int len = sc.nextInt();
int[] numbers = new int[len]; // use len here
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
for (index = 0; index < len; index++) { // and use len here
numbers[index] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
And don't close the scanner.
When you are receiving your input from the console, the Scanner hasNextInt() method placed inside a while loop condition will continue to read (meaning the loop will continue), until one of the following happens:
You submit a non-numeric symbol (e.g. a letter).
You submit a so-called "end of file" character, which is a special symbol telling the Scanner to stop reading.
Thus, in your case you cannot have the hasNextInt() inside your while loop condition - I am showing a solution below with a counter variable that you can use.
However, the hasNextInt() method inside a while loop has its practical usage for when reading from a different source than the console - e.g. from a String or a file. Inspired from the examples here, suppose we have:
String s = "Hello World! 3 + 3.0 = 6 ";
We can then pass the string s as an input source to the Scanner (notice that we are not passing System.in to the constructor):
Scanner scanner = new Scanner(s);
Then loop until hasNext(), which checks if there is another token of any type in the input. Inside the loop, perform a check if this token is an int using hasNextInt() and print it, otherwise pass the token to the next one using next():
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
System.out.println("Found int value: " + scanner.next());
} else {
scanner.next();
}
}
Result:
Found int value: 3
Found int value: 6
In the example above, we cannot use hasNextInt() in the while loop condition itself, because the method returns false on the first non-int character that it finds (so the loop closes immediately, as our String begins with a letter).
However, we could use while (hasNextInt()) to read the list of numbers from a file.
Now, the solution to your problem would be to place the index variable inside the while loop condition:
while (index < numbers.length) {
numbers[index++] = sc.nextInt();
}
Or for clarity`s sake, make a specific counter variable:
int index = 0;
int counter = 0;
while (counter < numbers.length) {
numbers[index++] = sc.nextInt();
counter++;
}
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
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();
}
I'm trying to make a "for" loop in which it asks the user to input 10 numbers and then only print the positives.
Having trouble controlling the amount of inputs. I keep getting infinite inputs until I add a negative number.
import java.util.Scanner;
public class ej1 {
public static void main(String args[]) {
int x;
for (x = 1; x >= 0; ) {
Scanner input = new Scanner(System.in);
System.out.print("Type a number: ");
x = input.nextInt();
}
}
}
From a syntax point of view, you've got several problems with this code.
The statement for (x = 1; x >= 0; ) will always loop, since x will always be larger than 0, specifically because you're not introducing any kind of condition in which you decrement x.
You're redeclaring the scanner over and over again. You should only declare it once, outside of the loop. You can reuse it as many times as you need.
You're going to want to use nextLine() after nextInt() to avoid some weird issues with the scanner.
Alternatively, you could use nextLine() and parse the line with Integer.parseInt.
That said, there are several ways to control this. Using a for loop is one approach, but things get finicky if you want to be sure that you only ever print out ten positive numbers, regardless of how many negative numbers are entered. With that, I propose using a while loop instead:
int i = 0;
Scanner scanner = new Scanner(System.in);
while(i < 10) {
System.out.print("Enter a value: ");
int value = scanner.nextInt();
scanner.nextLine();
if (value > 0) {
System.out.println("\nPositive value: " + value);
i++;
}
}
If you need to only enter in ten values, then move the increment statement outside of the if statement.
i++;
if (value > 0) {
System.out.println("\nPositive value: " + value);
}
As a hint: if you wanted to store the positive values for later reference, then you would have to use some sort of data structure to hold them in - like an array.
int[] positiveValues = new int[10];
You'd only ever add values to this particular array if the value read in was positive, and you could print them at the end all at once:
// at the top, import java.util.Arrays
System.out.println(Arrays.toString(positiveValues));
...or with a loop:
for(int i = 0; i < positiveValues.length; i++) {
System.out.println(positiveValues[i]);
}
Scanner scan = new Scanner(System.in);
int input=-1;
for(int i=0;i<10;i++)
{
input = sc.nextInt();
if(input>0)
System.out.println(input);
}
I am self-learning Java and am stuck on a simple project. I'd like to receive 6 unique 'lottery' numbers from a user.
User will be asked to input an integer.
Each user input will be placed into an array.
If the user inputs a previously input number, I want to prompt to reenter the number again.
Recheck the new input. If unique, continue the for loop. If non-unique, run step 3 again.
So far, all I have is:
public static int[] userLottoInput()
{
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < userNums.length; i++ ) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
for (int k=i; k<userNums.length; k++) {
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}
}
}
Any help is appreciated!!
Try and keep you logic simple.
While the user hasn't enter 6 numbers, loop
Ask the user for a value
Check to see if it's a duplicate
If it is, ask the user to re-enter the value
If it's not (a duplicate) increment the counter to the next element...
For example...
public static int[] userLottoInput() {
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
int i = 0;
// Keep looping until we fill the array, but
// allow the control to fall somewhere else
while (i < userNums.length) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
// Check for duplicates
boolean duplicate = false;
// We only need to check up to i - 1, as all the
// other values are defaulted to 0
// We also don't need to check for the last number entered ;)
for (int k = 0; k < i; k++) {
// Check for duplicated
if (userNums[k] == userNums[i]) {
System.out.println("No duplicates allowed, please try again");
duplicate = true;
// Break out of the loop as we don't need to check any more..
break;
}
}
// If no duplicates where found, update i to the next position
if (!duplicate) {
i++;
}
}
return userNums;
}
With this, there is only one point at which you prompt the user. Everything else is used to control the element position (i) to meet your requirements.
Now, I'm sure that there are other ways to do this and this is just a simple example ;)
Move the asking of number outside loop, when received the number loop over the numbers array to find a match. If match found re-ask for number (outside the for loop used for finding the match), else if match not found, then add the number to array.
Don't you think your for loop is little complicated. Anyways, you can try this :
for (int k=0; k<i-1; k++) { //Start k=0 means from the first stored value
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}