How to print the selected name in the array? - java

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

Related

save several names in a string array [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}

Specific index of Array

So I'll give you some brief background, I'm in AP computer science and I'm confused on this program.
We are suppose to enter in the size of the array, then the program runs through a for loop, get the full name in one string, ( use scanner.nextLine();), then the test Score, which isn't that important. The user then will enter the first name of ANYONE and there should be a for loop running through each array seeing if firstName is in the first name array.
The problem is firstName when is printed out is blank.. fixed the first error.
import java.util.Scanner;
public class totalScores {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int sizeOfArray = input.nextInt();
String kline[] = new String[sizeOfArray];
for ( int index= 0; index< kline.length; index++)
{
System.out.println("Enter the name: ");
String name = input.next();
kline[index]= name;
input.nextLine();
}
double[] testScore= new double[sizeOfArray];
for (int i = 0; i< testScore.length; i++)
{
System.out.println("enter the test score");
double testz = input.nextDouble();
testScore[i]= testz;
input.nextLine();
}
System.out.println("Enter first name : ");
String want = input.next();
for( int index = 0; index < kline.length; index++)
{
String firstName="";
String namez;
namez = kline[index];
int space = namez.indexOf("");
firstName = namez.substring(0,space);
if (want.equalsIgnoreCase(firstName))
{
System.out.println("The test score is: "+ testScore[index]);
}
else
{
System.exit(0);
}
}
}
}
Your example is not too clear but I can see the for loop is running with kline.length as the limit, but you are getting nameofarray[index] which could be an array with different size than kline.
Possibly the problem is here:
int space = namez.indexOf(" ");
In case the namez don't contain spaces in it, the value for space will be -1. So it will form this statement:
namez.substring(0, -1)
Of-course you will encounter exception.
Try doing this:
String firstName = kline[index].split(" ")[0];
System.out.println(firstName);
This will return the first word of kline[index] even if it doesn't contain a space.
The error is occurring most likely because your kline[index] does not contain a space (therefore, indexOf(" ") returns -1. And you cant substring with (0,-1)

How to put IF statement in given scenario?

I'm a beginner programmer Java:
I want to get 10 values from user and put if statement, if some one enters grade value above 100, it may get "Enter right value < 100"
But i don't want to use any array etc.
When i use the following code, it shows the error message but for 1 wrong value, it calculates other 09 values and don't repeat the wrong value, given if statement skips the wrong
int i, number, total=0;
Scanner sc = new Scanner(System.in);
for (i=1; i<=10; i++)
{ System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100);;
{total = total + number;}
}
int number, total=0;
int i = 1;
Scanner sc = new Scanner(System.in);
while (i<=10)
{
System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100){
total = total + number;
i++;
}else{
System.out.println("invalid value");
}
}
This will work, using a while loop
You just had few typo errors in your code also , to make the for loop more simple you don't need to define i at top just define the i when you need to use the for loop . And its avoid overwrite outside of the for loop .
To make using for loop more professional also considering that maybe sometimes you need to use it for arrays its better to always start the loop with i=0 thats the better practice.
After if(condition) don't need to put any ;
int number, total=0;
Scanner sc = new Scanner(System.in);
for (int i=1; i<=10; i++)
{ System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100){
total = total + number;
}
}

Splitting string of integers and then put the numbers onto a int array Java

Ok so i take as an input a list of numbers as a string and i want to take these numbers and create an int array with them.
import java.util.Scanner;
public class StringSplit
{
public static void main(String[] args)
{
int a;
int i = 0;
String s;
Scanner input = new Scanner(System.in);
System.out.println("This programs simulates a queue of customers at registers.");
System.out.println("Enter the number of registers you want to simulate:");
a = input.nextInt();
while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");
a = input.nextInt();
}
System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3.
Enter: ");
s = input.next();
String[] parts = s.split(" ");
System.out.println(parts[1]);
for(int n = 0; n < parts.length; n++) {
System.out.println(parts[n]);
}
input.close();
}
}
Everything would be great if i could get the whole array created printed but for some reason i get this:
Input:
0 0 1 1 2 2
Output:
0
Thats it. Only the 1st element of the array is printed.Should i try to manually print and element such as parts[1](as i do and i get this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at QueueSimulation.main(QueueSimulation.java:32)
Why is this happening? And more importanly how do i fix it?
If you want to read a line, use:
s = input.nextLine();
next() returns the value till the first space.
Read more here

Simple for loop issue with arrays

This is the code I have right now
for (int i = 0; i <= listOfPeople.length; i++){
String name = scnr.nextLine();
System.out.println("Person " + (i + 1) + ": ");
listOfPeople[i] = name;
}
List of people is a properly declared list of Strings with the length of a value the user sends in. The error that is happening is that when I run the program, I get this:
Person 1:
Jordan
Person 2:
Jordan
Person 3:
Jordan
Person 4:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at RGG.main(RGG.java:20)
I am not quite sure what is wrong, but I have tried removing the = in the for loop declaration, then I get this output:
Person 1:
Jordan
Person 2:
Jordan
Person 3:
After the third prompt, the code moves on and I cant type in anything there.
Does anyone know what might be happening? Thanks in advance!
Remove the = in this expression i <= listOfPeople.length;. Its causing you to access an element of the array that does not exist.
for (int i = 0; i < listOfPeople.length; i++){
String name = scnr.nextLine();
System.out.println("Person " + (i) + ": ");
listOfPeople[i] = name;
}
Full Example:
public class PersonArrayTest {
public static void main(String[] args) {
String[] listOfPeople = new String[5];
assign(listOfPeople);
System.out.println(Arrays.toString(listOfPeople));
}
public static void assign(String[] listOfPeople) {
Scanner scnr = new Scanner(System.in);
for (int i = 0; i < listOfPeople.length; i++) {
String name = scnr.nextLine();
System.out.println("Person " + (i) + ": ");
listOfPeople[i] = name;
}
}
}
With this line
for (int i = 0; i <= listOfPeople.length; i++){
You are advancing one beyond the end of the array, length 3, which has valid indices 0-2. 3 is an invalid index.
When you remove the =, you get the corrected version:
for (int i = 0; i < listOfPeople.length; i++){
which stops after the 2 iteration, which is the end of the array, before you run off the end of the array.
change this the <= sign in forloop
for (int i = 0; i < listOfPeople.length; i++)
I am make an educated guess that you are using Scanner#nextInt to get the input for the length of the array. Something along the lines of this:
String[] listOfPeople = new String[scnr.nextInt()];
I've garnered this because your loop code looks like this:
take input for i == 0
print prompt #1
take input for i == 1
print prompt #2
take input for i == 2
print prompt #3
But your output shows this:
print prompt #1
take input for i == 1
print prompt #2
take input for i == 2
print prompt #3
So what actually must be happening is this:
silently advance past whatever scnr is still retaining for i == 0
print prompt #1
take input for i == 1
print prompt #2
take input for i == 2
print prompt #3
nextInt orphans a new line character. (So will any calls to next_ besides nextLine.) That's why your first input is skipped. Calling scnr.nextLine in the first iteration of the loop just advances the Scanner past the last line.
Change the loop to this:
// skip the last new line
scnr.nextLine();
// < not <=
for (int i = 0; i < listOfPeople.length; i++) {
// prompt before input
System.out.println("Person " + (i + 1) + ": ");
// you don't need that extra String
listOfPeople[i] = scnr.nextLine();
}

Categories

Resources