Lost first element in array? [duplicate] - java

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();
}
}

Related

How to print the selected name in the array?

How do I print the selected name in the array? I want to print the names i entered in the array and print it alone but when I try to run the code it says:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
here is my code:
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
//Getting the names using for loop.
for(int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
for(int i = 0; i <numOfLoop; i++) {
if(name[i] == name[num]) {
System.out.println(name[i]);
}
}
Input:
6 //How many loop and size of array I want.
john
mark
kevin
tesia
arthur
cody
5 //what ever is in array[5] will be printed.
Expected output: cody
I also encountered this problem before, it seems that when you change from nextInt() the scanner instance did not read the \n character before it goes forward to nextLine().
Just adding in.nextLine(); before the For-loop should fix the problem.
Your error comes from the fact that the first entry in the array gets set as an empty string and the last name you put in gets read where you normally would put the second number, thus the nextInt() throws an error since it gets a String and not an int.
There are several typical flaws in the code snippet to be addressed:
InputMismatchException - because not all new lines are consumed properly after calling to nextInt
name[i] == name[num] -- invalid String comparison, should be name[i].equals(name[num])
Missing check num < numOfLoop -- without that, ArrayOutOfBoundsException is possible
The fixed code would look as follows:
Scanner in = new Scanner(System.in);
System.out.println("Input the number of names: ");
int numOfLoop = in.nextInt(); //number of loops I want.
in.nextLine(); // skip remaining line
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
System.out.println("Input the names, one per line: ");
//Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
System.out.println("Input the index of the name to print: ");
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
if (num >= 0 && num < numOfLoop) {
System.out.println("Looking for name: " + name[num]);
for (int i = 0; i <numOfLoop; i++) {
if(name[i].equals(name[num])) {
System.out.println(name[i] + " at index=" + i);
}
}
} else {
System.out.println("Invalid index, cannot be greater or equal to " + numOfLoop);
}
Sample output:
Input the number of names:
5
Input the names, one per line:
john
jeff
joan
john
jake
Input the index of the name to print:
0
Looking for name: john
john at index=0
john at index=3
You do not need the second loop.
All you need to do is to check if (num >= 0 && num < numOfLoop) and display the value of name[num] or an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numOfLoop = Integer.parseInt(in.nextLine()); // number of loops I want.
String[] name = new String[numOfLoop]; // size of the array is depend on how many loop I want.
// Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = Integer.parseInt(in.nextLine()); // The name I want to print depend on what number I enter here.
if (num >= 0 && num < numOfLoop) {
System.out.println(name[num]);
} else {
System.out.println("Invalid index.");
}
}
}
Also, use Integer.parseInt(in.nextLine()) instead of in.nextInt() for the reason mentioned at Scanner is skipping nextLine() after using next() or nextFoo()?
A sample run:
5
Johny
Arvind
Kumar
Avinash
Stackoverflow
3
Avinash
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
for (int i=0; i<name.length; i++){
String names = in.next();
name[i] = names;
}
System.out.println("The names array: " + Arrays.toString(name));
for(int index=0;index<name.length;index++) {
System.out.print("Enter an index you want to print: ");
index = in.nextInt();
System.out.println("index " + index + " is: " + name[index-1]);
}

Adding the code for ascending order of user input

import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
line = in.nextLine();
System.out.print("Input Number 1: " );
line = in.nextLine();
System.out.print("Input Number 2: ");
line = in.nextLine();
System.out.print("Input Number 3: " );
line = in.nextLine();
System.out.print("Input Number 4: ");
line = in.nextLine();
System.out.print("Input Number 5: " );
line = in.nextLine();
}
public static void sortAscending (double[]arr)
{
Arrays.sort(arr);
System.out.printf("Sorted arr[] = %s",
Arrays.toString(arr));
}}
I am stuck on what the code is for putting the what the user inputs in ascending order. I have looked up and tried multiple resources on ascending order but nothing seems to work. I tried:
System.out.print("Input number 1: "+(i+1+":");
to try and add the inputs instead of writing all of them out but i was an unknown variable.
You should use an array to store input and a loop to read input.
System.out.print("How many numbers you want to input?: ");
int num = in.nextInt();
double[] arr = new double[num];
for(int i = 0; i < num; i++){
arr[i] = in.nextDouble();
}
sortAscending(arr);
You have to create an array. Then put the stuff you are reading into the array and after that call your method.
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
sortAscending(values);
Note that the name sortAscending is not accurate, it is not just sorting (and then returning the result or in-place), but also printing. So maybe you should rename it to sortAndPrintAscending. Or just sort it and let your main method to the printing.
Or drop it completely, the method does not really serve any purpose as it is just calling Arrays.sort, might as well do that in main:
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
Arrays.sort(values);
System.out.println("Sorted: " + Arrays.toString(values));

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 to read the user inputs(including spaces) line by line with Scanner?

I need to read user inputs line by line (may be included spaces). I had already read Scanner doesn't see after space question. So I used with scanner.nextLine() but this method does not help my program. Below is my sample program ....
public class TestingScanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many friends do you have ?");
int size = sc.nextInt();
String[] names = new String[size];
for (int i = 0; i < size; i++) {
System.out.println("Enter your name of friend" + (i + 1));
names[i] = sc.nextLine();
}
System.out.println("*****************************");
System.out.println("Your friends are : ");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
System.out.println("*****************************");
}
}
While runnig my program , after inserted no: of friend , my program produces two lines as below. How can I solve it ? Thanks.
After int size = sc.nextInt(); use sc.nextLine() to consume the newline characters, otherwise, they will be consumed by nextLine() in your loop and that is not what you want.
Solution
int size = sc.nextInt();
sc.nextLine();

reading input with Scanner; output is printed twice [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I have following class
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = sc.nextInt();
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
I can't type song name nr 1 because it Always shows first two together.
Like this if I type 3:
How many songs do your CD contain?
3
Please enter song nr 1:
Please enter song nr 2:
Change
int songs = sc.nextInt();
to:
int songs = Integer.parseInt(sc.nextLine().trim());
and it will work fine.
You should not mix usages of nextInt with nextLine.
add sc.nextLine(); after int songs = sc.nextInt();
Once you enter a number and read it using a scanner ( as a number) using sc.nextInt();, the newline character will be present in the input stream which will be read when you do sc.nextLine(). So,to skip(over) it, you need call sc.nextLine() after sc.nextInt();
Add a sc.nextLine() after sc.nextInt() and your code works fine.
The reason is the end of line after you type the nomber of songs.
Either use nextInt or nextLine, I would opt for nextLine:
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = Integer.parseInt(sc.nextLine()); // instead of nextInt()
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
put a sc.nextLine(); after int songs = sc.nextInt();

Categories

Resources