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]);
}
Related
I am trying to have the user set the name for how many numbers they set. for example if they set 3 the program asks for name 3 times and then sets those names to a different varible inside an array.
public static void main(String[] args) {
Scanner Num = new Scanner(System.in);
Scanner Name = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = Num.nextInt();
int[] numbs = new int[number];
for (int i = 0; i < numbs.length; i++) {
System.out.println("What is your name");
String [] nameArray = Name.nextLine();
Just a small improvement over Titan's answer.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int numberOfTimes = sc.nextInt();
String[] names = new String[numberOfTimes];
sc.nextLine();
for (int i = 0; i < numberOfTimes; i++) {
System.out.println("What is your name");
names[i] = sc.nextLine();
}
System.out.println(Arrays.toString(names));
}
Starting point
Here are several things happening in your posted code:
You have two different Scanners, each reading from System.in
After prompting for user input (int number = Num.nextInt()), you're using that number to create an array of size "number"
When you call nextLine(), you are assigning the result to a string array (String []).
Working solution
Here's a variation which addresses those issues, with a few additions, too:
Use one Scanner, and give it a general name ("scanner", not "Num") since a scanner has nothing to do with one specific data type. Any scanner can read strings, integers, booleans, bytes, etc. Look in Javadoc for the full set of supported data types.
Check if user input is valid before trying to create an array – if user enters "-1" that's a valid integer value, but not valid for allocating an array – new int[-1]) would throw a java.lang.NegativeArraySizeException at runtime.
Use "next()" instead of "nextLine()" – with the rest of your example, using "nextLine()" results in skipping one line without direct interaction from the user (so the first "name" is always an empty string)
Assign the result of "next()" to a String (not String[]), matching the return type from the method
Use "System.out.print()" instead of "println()", a little tidier program output
Use lowercase names to follow Java naming conventions ("scanner", not "Scanner")
Scanner scanner = new Scanner(System.in);
System.out.print("How many names do you want to enter: ");
int times = scanner.nextInt();
if (times < 0) {
System.out.println("negative numbers not allowed");
} else {
String[] names = new String[times];
for (int i = 0; i < times; i++) {
System.out.print("What is your name: ");
names[i] = scanner.next();
}
System.out.println(Arrays.toString(names));
}
And here's a sample run:
How many names do you want to enter: 3
What is your name: one
What is your name: two
What is your name: three
[one, two, three]
Create a String array of number length outside the loop and initialize each index with name as input.
By the way you only need to create one Scanner object for input(Not needed to create various objects for different input).
Edit - There was no use of numbs array.
Scanner sc=new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = sc.nextInt();
String []nameArray=new String[number];
/*Since nextInt() does not read the newline character in your input
created by hitting "Enter"*/.
sc.nextLine();
for (int i = 0; i < number; i++) {
System.out.println("What is your name");
nameArray[i]=sc.nextLine();
}
sc.close(); //To prevent memory leak
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();
}
}
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
I have a bit of a unique problem to solve and I'm stuck.
I need to design a program that does the following:
Inputs two series of numbers (integers) from the user.
Creates two lists based on each series.
The length of each list must be determined by the value of the first digit of each series.
The rest of the digits of each series of numbers becomes the contents of the list.
Where I'm getting stuck is in trying to isolate the first number of the series to use it to determine the length of the list.
I tried something here so let me know if this is what you're looking for. It would be better for you to provide your attempt first.
I also want to point out that Lists are for the most part dynamic. You don't have to worry about the size of them like a normal array.
Scanner sc = new Scanner(System.in);
ArrayList<Integer[]> addIt = new ArrayList<>();
boolean choice = false;
while(choice == false){
String line = sc.nextLine();
if(line.equalsIgnoreCase("n")){
break;
}
else{
String[] splitArr = line.split("\\s+");
Integer[] convertedArr = new Integer[splitArr.length];
for(int i = 0; i < convertedArr.length; i++){
convertedArr[i] = Integer.parseInt(splitArr[i]);
}
addIt.add(convertedArr);
}
}
This is assuming that you are separating each integer with a whitespace. If you are separating the numbers with something else just modify the split statement.
The user enters "n" to exit. With this little snippet of code, you store each array of Integer objects in a master ArrayList. Then you can do whatever you need to with the data. You can access the first element of each Integer object array to get the length. As you were confused how to isolate this value, the above snippet does that for you.
I would also advise you to add your parse statement in a try-catch block to provide error handling for invalid input that cannot be parsed to an integer.
This is one way of doing it with default arrays.
import java.util.Scanner;
public class ScanList {
public static void main(String[] args){
System.out.println("Array:");
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] nums = line.split(",");
int[] result = new int[Integer.parseInt(nums[0])];
for(int i = 0; i<result.length;i++){
result[i]=Integer.parseInt(nums[i+1]);
}
for(int r:result){
System.out.println(r);
}
}
}
This is what I came up with:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Insert the first series of numbers: ");
String number1 = input.nextLine();
System.out.println("Insert the second series of numbers: ");
String number2 = input.nextLine();
String[] items = number1.split(" ");
String[] items2 = number2.split (" ");
List<String> itemList = new ArrayList<String>(Arrays.asList(items));
itemList.remove(0);
Collections.sort(itemList);
System.out.println(itemList);
} // End of main method
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Yes this is an assignment...
I've got 2 arrays; one for student names and one for their scores. I've asked the user to input the number of students to initialize the sizes of both, and then loop through the input process to fill the elements.
But the weirdest thing happens that hasn't happened before. It seems that the student array is cut short by one element when the code is run (after 4 entries the program jumps to the next input loop), but even weirder is that the truncation seems to be at the front of the array, because the scores loop starts with a blank where a name should be but allows for 5 inputs.
import java.util.Scanner;
public class Ex6_17SortStudents {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numOfStu;
String[] students;
double[] scores;
System.out.println("Enter the number of students being recorded: ");
numOfStu = input.nextInt();
students = new String[numOfStu];
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++)
students[i] = input.nextLine();
scores = new double[numOfStu];
for (int i = 0; i < students.length; i++) {
System.out.print("Enter score for " + students[i] + ": ");
scores[i] = input.nextDouble();
}
}
}
Any ideas why this happens?
There's eventually a sort but that's a mess i think i have a handle on.
Sorry if the format for the post is wrong -- first time posting; trying my best.
thanks
This debugging output should give you a clue to your problem:
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++) {
System.out.print("Name index " + i + ": ");
students[i] = input.nextLine();
}
And this answer to this question is exactly the answer you need.
Use students[i] = input.next();
Just checked it, and it works now.
nextLine() advances your scanner past the current line and returns the input that was skipped -- so you were pretty much skipping a line. The first time it enters the loop, you lose an i value, that is i is now 1, yet your scanner does not record user input. The second time around, when i is 1, it takes input, and so forth.
New code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numOfStu;
String[] students;
double[] scores;
System.out.println("Enter the number of students being recorded: ");
numOfStu = input.nextInt();
students = new String[numOfStu];
scores = new double[numOfStu];
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++) {
students[i] = input.next();
}
for (int i = 0; i < students.length; i++) {
System.out.print("Enter score for " + students[i] + ": ");
scores[i] = input.nextDouble();
}
}