I have a for loop and the method to call it is printMe() and I want the user to be able to determine how many times it runs with their input. This is along the lines of what I think it should be:
System.out.println("Enter a number: ");
loop = input.nextInt();
This should work:
Scanner input = new Scanner(System.in);
int loop = input.nextInt();
for(int i = 0; i<loop;i++){
//do the thing
}
Read the user input thanks to a scanner
Scanner sc = new Scanner(System.in);
int loopNum = sc.nextInt();
for (int i=); i<loopNum; i++){
printMe();
}
Should be something like:
for (int i=0; i<loopNum; i++)
printMe();
Cheers
yes it is correct if your variable input from class Scanner. You can declare variable sc like this and call it many times if you want to read more input from users.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
loopNum = sc.nextInt();
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
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]);
}
i write one program that get input from user as "Enter number of students:" then add the student names into it and print it in console. I write one code that run fine but problem is the loop is already ramble one time the code is not properly working i also want to know that how to get inputs using command line argument without Scanner and store it in String Array
Current Output is like that
Here is my code please help and i am in learning phrase of Java
import java.util.Scanner;
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns
the input that was skipped.
Try placing a scanner.nextLine(); after each nextInt() if you intend
to ignore the rest of the line.
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
in.nextLine();// just to ignore the line
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println("Enter Student Names: "+i);
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
You can use array args[]
Need not pass number of students there.
So what ever name you pass on command prompt after java <className> shall be stored in this array and you can iterate over it.
Add in.nextLine(); after you assign this int totalstudents = in.nextInt();
use ArrayList instead of String Array
declare header file
import java.util.ArrayList;
change your code
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into arraylist
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < totalstudents;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
al.add(in.next());
}
for(int i=0; i< al.size(); i++)
{
System.out.println(al.get(i));
}
Try this code:
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.print("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.print("Enter Student " + i + " Name:");
studentname[i] = in.nextLine();
}
for(int i = 0; i < studentname.length;i++)
{
System.out.println(studentname[i]);
}
How would I read a single "line" of input from the user that seperates the values by space and assign them to a certain variable? Seems quite confusing for me.
For example,
Enter 3 digits = 3 4 5
Total = 12
The input that I put, once there is a space, only prints first value when I put "3 4"
I know I should not use nextInt scanner but I can't figure out a way
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 digits:");
a = scan.nextInt();
System.out.println(a);
By doing sum in for loop:
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 digits:");
int sum=0;
for(int i=0;i<3;i++){
sum = sum + scan.nextInt();
}
System.out.println(sum);
It would be best to have an array of variables, and read integers into the array one at a time like this:
int[] a = new int[3];
Scanner scan = new Scanner(System.in);
System.out.print("Enter 3 digits: ");
for(int i = 0 ; i < a.length ; i++) //loop 3 times
{
a[i] = scan.nextInt(); //get int from input
System.out.println(a[i]);
}
scan.nextLine(); //consume the \n
You just call nextInt() 2 more times.
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
If you are required to read all integers in one read you can use this code. If reading one by one is ok the refer to other answers. For this code you can make a loop and use arrays as well.
String a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 digits:");
a = scan.nextLine();
Scanner stscan = new Scanner(a);
System.out.println(a);
int number1 = stscan.nextInt();
int number2 = stscan.nextInt();
int number3 = stscan.nextInt();
System.out.println(number1+number2+number3);
I got the following code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
And the output for that code is the following:
How many names are you going to save:3
Type a name: Type a name: John Doe
Type a name: John Lennon
Notice how it skipped the first name entry?? It skipped it and went straight for the second name entry. I have tried looking what causes this but I don't seem to be able to nail it. I hope someone can help me. Thanks
The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
in.nextLine();
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
or just read the line and parse the value as an Integer.
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine().trim());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
use sc.nextLine(); two time so that we can read the last line of string
sc.nextLine()
sc.nextLine()
It's because the in.nextInt() doesn't change line. So you first "enter" (after you press 3 ) cause the endOfLine read by your in.nextLine() in your loop.
Here a small change that you can do:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
This because in.nextInt() only receive a int number, doesn't receive a new line. So you input 3 and press "Enter", the end of line is read by in.nextline().
Here is my code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
You could have simply replaced
names[i] = in.nextLine(); with names[i] = in.next();
Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.