How to make the scanner understand the amount I write? - java

This is just some homework but I cannot find a way to achieve it like I want. Have a look at my code please.
Once the numbers are typed, I'd just like to play around with them.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//user says if he'd like to use 3 numbers for instance (2,4,5)
System.out.println("How many numbers would you like to use? : ");
int amountOfNumbers = sc.nextInt();
System.out.println("Great! Please type in your numbers: ");
int numbers =sc.nextInt(amountOfNumbers);
// should let him write the amount of numbers he entered
}
Once he has typed the amount of numbers he'd like to use, I would like the scanner to give him the possibility to type in all of those numbers.
Let's say he the amount of numbers he'd like to use is three.
I would like him to be able to type it in the console like this:
First number + enter key
Second number + enter key
Third number + enter key
Not able to write anymore
That is what I meant here by adding "amountOfNumbers" in the scanner itself... (which is not working)
int numbers =sc.nextInt(amountOfNumbers);
BR

Consider a for loop:
for(int i = 0; i < amountofNumbers; i++){
// add to a collection / array / list
}
And then access what you need from there.

import java.util.*;
class EnterNumber{
public void enter_list_function(){
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers would you like to use?");
//Enter the Numbers of amount
int input = sc.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Great! Please type in your numbers: ");
//Input - Numbers of amount
for(int j =1; j<=input; j++ ){
int addval = sc.nextInt();
//Add the enter amount in array
list.add(addval);
}
Iterator itr=list.iterator();
while(itr.hasNext()){
//get the enter amount from list
System.out.println(itr.next());
}
}
public static void main(String[] args){
EnterNumber EnterNumber = new EnterNumber();
EnterNumber.enter_list_function();
}
}

Related

Solved!: the for loop in my code won't repeatedly repeat, gather input, and put it into an array

I am suppose to ask the user for how many integers they want to enter, and then use a loop to create a prompt message for each integer, so that the numbers can be entered. Each integer that is entered is stored in an array.
However, every time I run the code, an error appears. The code doesn't repeat during the loop, and it looks like this:
Please enter the number of values you would like to enter:
1
Please enter for index value of 0:
-Error-
I can't figure out why the loop and array aren't working, thank you!
```public static void main(String[] args) {
//create and label variables
int intCount, n, x;
//create a scanner that will accept the user's input and figure out how many
numbers the user wants to enter
Scanner Inputnumber = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to
enter:");
n = Inputnumber.nextInt();
Inputnumber.close();
//create a integer array to store the numbers
int [] integers;
integers = new int [n];
//create a while loop to continuously ask the user for what numbers they
want to enter
for (intCount = 0; intCount < n; intCount++){
Scanner InputInt = new Scanner(System.in);
System.out.println("Please enter for index value of "+intCount+": ");
x = InputInt.nextInt();
integers [intCount] = x;
InputInt.close();
}```
Refer this
You don't need to use two separate Scanner Objects.
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
// create and label variables
int intCount, n, x;
// create a scanner that will accept the user's input and figure out how many
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to enter:");
n = input.nextInt();
// create a integer array to store the numbers
int[] integers;
integers = new int[n];
// create a while loop to continuously ask the user for what numbers they
for (intCount = 0; intCount < n; intCount++) {
System.out.println("Please enter for index value of " + intCount + ": ");
x = input.nextInt();
integers[intCount] = x;
}
input.close();
}
}

Loop amount of times given inside a For Loop

I have a For Loop and it's asking the user how many times the loop should be looped inside the loop. How do I loop it the number of times given without repeating the question "how many names would you like to input"?
The issue is that I don't want to repeat the question after the user answered it. When the user answers the question, I want it to ask for the names x amount of times and then move on.
The main problem is that I need to ask how many times to loop it after the name is asked. It's says it the assignment sheet.
Thanks so much!
for (int i = 0; i < num; i++) {
System.out.println("Enter name #" + (i+1));
names[i] = input.next();
System.out.println("How many names would you like to input?");
num = input.nextInt;
}
You must move your num getter code outside of loop like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many names would you like to input?");
int num = input.nextInt();
String names[] = new String[num];
for (int i = 0; i < num; i++) {
System.out.println("Enter name #" + (i+1));
names[i] = input.next();
}
}
Always move these kinds of questions out of the loop rather than inside.
System.out.println("How many names would you like to input?");
num = input.next();
for (int i = 0; i < num; i++) {
System.out.println("Enter name #" + (i+1));
names[i] = input.next();
}
num = input.next();
You are asking a numbers not a string should change the .next() to either nextInt or nextShort.
#DevilsHnd the first code won't work indeed, I never saw that String [] = new String [] use array before plus this will explain better why.
#J.A.P link with code may work
import java.util.Scanner;
public class Newpro{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("how many times you want to loop?")
int num = sc.nextInt();//input the no of times you want to loop
String names[i] = new String[num];//initialize a string array for reading names
for(i=0;i<num;i++){
System.out.println("enter name#"+(i+1));
names[i]=sc.next();
}
for(j=0;j<num;j++){
//printing the names entered by you
System.out.println("the entered names by you are"+" "+names[j]);
}
as others suggested, you have to move your 'num' getter part out of the loop and after that initialize a string array for reading your names by specifying how many names you want to enter(index of string array = number of names you want to enter and no of times you want to loop as well==>'num') and based on that number the looping will be done with above code.
finally iterate through the array and print the names entered by you.
Edit:1
check with the below code if you need to ask "how many names user wants to input AFTER it asks for a first name.
import java.util.Scanner;
public class Newpro2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//make sure you create a string array with index = no of names you want to
//enter
String[] names = new String[10];
System.out.println("enter name#1");
names[0]= sc.next();
System.out.println("how many inputs you want to give?");
num=sc.nextInt();//give the no of inputs you want to give here
//read the remaining names
for(int i=1;i<num;i++){
System.out.println("enter name#"+(i+1));
names[i] = sc.next();
}
//print all the names entered by you
for(int j=0;j<num;j++){
System.out.println("entered name#"+(j+1)+"by you is"+" "+names[j]);
}

How do I use while loop with arrays that are user input

I just started learning Java and I need help on how to modify the program so that the array size is taken as a user input while using a while loop to validate the input so that invalid integers are rejected.
Also, using a while loop, take keyboard inputs and assign values to each array position.
I would appreciate any help!
Here is the code:
double salaries[]=new double[3];
salaries[0] = 80000.0;
salaries[1] = 100000.0;
salaries[2] = 70000.0;
int i = 0;
while (i < 3) {
System.out.println("Salary at element " + i + " is $" + salaries[i]);
i = i + 1;
}
It is very simple to use the while loop and take input from user Please refer below code you will understand how to take input from user and how while loop works. put all code in your main() function and import the import java.util.Scanner; and execute it and do modification to understand code.
Scanner sc= new Scanner (System.in); // this will help to initialize the key board input
System.out.println("Enter the array element");
int N;
N= sc.nextInt(); // take the keyboard input from user
System.out.println("Enter the "+ N + " array element ");
int i =0;
double salaries[]=new double[N]; // take the array lenght as the user wanted to enter
while (i<N) { // this will get exit as soon as i is greater than number of elements from user
salaries[i]=sc.nextDouble();
i++; // increment value of i so that it will store in next array element
}
you can use Scanner class for taking input from user
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements");
int n=sc.nextInt();
double salaries[]=new double[n];
for(int i=0;i<n;i++)
{
salaries[i]=sc.nextDouble();
}
You can also achieve using for loop and use Scanner class which is used to take input from keybord.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please enter the length of array you want");
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
double salaries[]=new double[length];
System.out.println("Please enter "+ length+" values");
for(int i=0;i<length; i++){
scanner = new Scanner(System.in);
salaries[i] = scanner.nextDouble();
}
scanner.close();
}
}
On java if you specific he array size, you can not change it,so you need to know array size before adding any value, but you can you use on of the List implementation like ArrayList to be able to add values without caring about the array size.
Example :
List<Double> salarie = new ArrayList<Double>();
while (i<N) { // this will get exit as soon as i is greater than number of elements from user
salarie.add(sc.nextDouble());
i++; // increment value of i so that it will store in next array
}
please read these articles for more details : difference-between-array-vs-arraylist
distinction-between-the-capacity-of-an-array-list-and-the-size-of-an-array

How do I get the user to enter a number into this array?

I need to have three arrays. The first array will allow the user to enter the points scored by a basketball team of 10 players for game 1. The second array will allow the user to enter the points scored for game 2. The third array will add the first two arrays together.
I'm stuck on the first part. I don't understand how to get the user to enter a number. I tried an input, but I got an error. How do I make it so the user can enter a number?
import java.util.Scanner;
public class array2 {
public static void main(String[] args) {
int i;
int [] game1 = new int[10];
// Enter Points scored by players in game 1
// Enter points scored by players in game 2
// Add arrays together
Scanner scanLine = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
for (i=0;i<game1.length;i++)
{
System.out.println ("The score of game 1 is " + game1[i]);
}
}
}
You can get points scored by a basketball team of 10 players for game1 array in following way...
Scanner scanner = new Scanner(System.in);
int[] game1 = new int[10];
for (int i = 0; i < 10; i++) {
game1[i] = scanner.nextInt();
}
scanner.close();
After doing this, you can print the array so that you can verify that you have got correct input from the user while you are developing the feature...
for (int i = 0; i < 10; i++) {
System.out.println(game1[i]);
}
And after that, you can get points scored by a team of 10 players for game-2 and game-3 in game2 and game3 arrays respectively...
Firstly, you only need one Scanner - you can use it as many times as you like.
At the point in your code where you need to read something, set a variable equal to
scanLine.nextLine()
Or
scanLine.nextInt()
You'll probably want to do some input validation on what you've scanner to make sure it is what you're expecting
The Java API documents for Scanner should be quite helpful for understanding how to use a scanner.
If points scored is integer type, try use nextInt() to read one integer:
Scanner scanner = new Scanner(System.in)
int number = scanner.nextInt();
Then you can save your input in array:
game1[0] = number;
For fill array you can use for loop:
for(i=0; i < game1.length; i++){
game1[i] = scanner.nextInt();
}

How to read in a value into an array using Scanner

I don't have any code to show what I am trying to do, because I honestly have no idea how to approach this.
What I am trying to do is have the user input how many numbers will be into an array. So basically, this is what I would like to be the output:
How many students in the class? 3
Enter the marks:
76
68
83
The class average is 75.67 %
I can program everything else, except for the first line. I have no idea how to read in a number into an array, so that the array will be as big as that number.
Thank you.
To start you will need to set up your scanner to read console input:
Scanner scanner = new Scanner(System.in);
You can then use function such as scanner.next() or scanner.nextInt() to get the input from the console. Hopefully this gives you some idea of where to start. If you need to look up more Scanner functions check the Scanner Documentation
As far as arrays go you simply need to save the first int input to the console and use this for size:
int size = Integer.parseInt(scanner.next());
int[] array = new int[size];
Then you should be able to use a loop to save each individual score.
import java.util.Scanner;
public class TestArrayInputViaConsole {
public static void main(String args[]) {
double sum = 0;
double avg = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many students are in the class? ");
int ArraySize = sc.nextInt();
int[] marks = new int[ArraySize];
System.out.println("Enter the marks:");
for(int i = 0; i < ArraySize; i++) {
marks[i] = sc.nextInt();
sum = sum + marks[i];
}
avg = (sum / ArraySize);
System.out.println("Average of the class : " + avg);
}
}

Categories

Resources