Why is the println() method being executed twice instead of once? - java

public class HashMapTest2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter total player");
Integer p = s.nextInt();
System.out.println("Enter total Team");
Integer t = s.nextInt();
List<String> listp = new ArrayList<>();
for (int i = 1; i<p; i++){
System.out.println("Enter Player name "+i);
listp.add(s.nextLine());
}
List<String> listt = new ArrayList<>();
for (int i = 1; i<t; i++){
System.out.println("Enter Team name "+i);
listt.add(s.nextLine());
}
}
}
I am getting some strange outputs, like the ones below:
Enter total player
3
Enter total Team
2
Enter Player name 1
Enter Player name 2
pari
Enter Team name 1
Why is the program asking me to enter the player's name twice? For the first time it is asking for player's name twice and I don't know why. Any way to solve this?

When you are using nextInt() then the integer value is read but not the end-of-line character (Return/Enter) change your code to use nextLine() as below for correct handling.
public static void main(String... obj) {
Scanner s = new Scanner(System.in);
System.out.println("Enter number of Players");
Integer p = Integer.valueOf(s.nextLine());
System.out.println("Enter number of Teams");
Integer t = Integer.valueOf(s.nextLine());
List<String> listp = new ArrayList<>();
for (int i = 0; i < p; i++){
System.out.println("Enter Player name " + i);
listp.add(s.nextLine());
}
List<String> listt = new ArrayList<>();
for (int i = 1; i < t; i++){
System.out.println("Enter Team name " + i);
listt.add(s.nextLine());
}
}

Related

How do I access the String value inside a for loop?

Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}

How to Give keys and values of my created list to the map?

public class HashMapTest2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Map<String,String> player = new HashMap<>();
System.out.println("Enter number of Players");
Integer p = Integer.valueOf(s.nextLine());
System.out.println("Enter number of Teams");
Integer t = Integer.valueOf(s.nextLine());
List<String> listp = new ArrayList<>();
for (int i = 0; i<p; i++){
System.out.println("Enter Player name "+i);
listp.add(s.nextLine());
}
List<String> listt = new ArrayList<>();
for (int i = 0; i<t; i++){
System.out.println("Enter Team name "+i);
listt.add(s.nextLine());
}
for (String str1 : listp){
for (String str2 : listt){
player.put(str1,str2);
}
}
System.out.println("---------------");
System.out.println(player);
}
}
I want to assign the player name as keys and team name as values...
seems like i am not getting it properly.
I tried using for-each loop but it is giving me same value for every one...
Taking following assumptions -
number of players and teams are same
We can randomly asssign any player to any team (there are no identifiers for the same)
You can try following code , if above mentioned assumptions are correct -
public class HashMapTest2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Map<String,String> player = new HashMap<>();
System.out.println("Enter number of Players");
Integer p = Integer.valueOf(s.nextLine());
System.out.println("Enter number of Teams");
Integer t = Integer.valueOf(s.nextLine());
List<String> listp = new ArrayList<>();
for (int i = 0; i<p; i++){
System.out.println("Enter Player name "+i);
listp.add(s.nextLine());
}
List<String> listt = new ArrayList<>();
for (int i = 0; i<t; i++){
System.out.println("Enter Team name "+i);
listt.add(s.nextLine());
}
for(int i=0;i<listp.size();i++) {
player.put(listp.get(i), listt.get(i));
}
System.out.println("---------------");
System.out.println(player);
}
}

Name and age application with specific output using arrays and output

For my university lab work we have to finish 4 tasks. I'm currently on 6 of 9 and have for the most part completed it, but I'm having difficulty in completing the final parts of it. This is the description of what we must do:
Write a program that defines two arrays - one of strings and one of integers, both of size 10.
Your program should then ask the user to enter the a string representing a persons name,
and an integer representing their age. It should continue to do this until either the user
enters ‘done’ instead of a name, or until the array is full (that is, 10 pairs of names and ages
have been entered). It should then print out the names and ages as well as the names of the
youngest and oldest.
Hint: One tricky part is making sure that once you’ve typed ‘done’ to Finish entering names,
your program does not then ask you for the age of the person with name ‘done’ - be careful
about this.
I've highlighted the issues I'm having above in bolded text. Below is the code I currently have, but I'm not sure how to properly accomplish the bolded text.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class nameAge {
public static void main(String[] args){
String[] name = new String[10];
int[] age = new int[10];
Scanner in = new Scanner(System.in);
String NAME_REQUEST = ("Please enter name");
String AGE_REQUEST = ("Please enter age");
System.out.println("Please enter the name of a person and then their age. Do this for up to 10 people and once finished, type 'done'");
name[0] = in.nextLine();
System.out.println(AGE_REQUEST);
age[0] = in.nextInt();
System.out.println(NAME_REQUEST);
name[1] = in.next();
System.out.println(AGE_REQUEST);
age[1] = in.nextInt();
System.out.println(NAME_REQUEST);
name[2] = in.next();
System.out.println(AGE_REQUEST);
age[2] = in.nextInt();
System.out.println(NAME_REQUEST);
name[3] = in.next();
System.out.println(AGE_REQUEST);
age[3] = in.nextInt();
System.out.println(NAME_REQUEST);
name[4] = in.next();
System.out.println(AGE_REQUEST);
age[4] = in.nextInt();
System.out.println(NAME_REQUEST);
name[5] = in.next();
System.out.println(AGE_REQUEST);
age[5] = in.nextInt();
System.out.println(NAME_REQUEST);
name[6] = in.next();
System.out.println(AGE_REQUEST);
age[6] = in.nextInt();
System.out.println(NAME_REQUEST);
name[7] = in.next();
System.out.println(AGE_REQUEST);
age[7] = in.nextInt();
System.out.println(NAME_REQUEST);
name[8] = in.next();
System.out.println(AGE_REQUEST);
age[8] = in.nextInt();
System.out.println(NAME_REQUEST);
name[9]= in.next();
System.out.println(AGE_REQUEST);
age[9] = in.nextInt();
System.out.println(NAME_REQUEST);
int size = name.length;
int sizeN = age.length;
for (int i=0; i < size; i++) {
System.out.println("Name: " + name[i]);
System.out.println("Age: " + age[i]);
}
int smallest = age[0];
int largetst = age[0];
for(int i=1; i< age.length; i++)
{
if(age[i] > largetst)
largetst = age[i];
else if (age[i] < smallest)
smallest = age[i];
}
System.out.println("Largest Number is : " + largetst);
System.out.println("Smallest Number is : " + smallest);
}
}
You have to take a look on loop doc in java
this code may help you
public static void main(String[] args) {
int youngest =0,older=0;
String[] name = new String[10];
int[] age = new int[10];
String NAME_REQUEST = ("Please enter name");
String AGE_REQUEST = ("Please enter age");
for(int i=0 ; i< 10;i++){
Scanner in = new Scanner(System.in);
System.out.println(NAME_REQUEST);
String tmpName = in.nextLine();
if(tmpName.equalsIgnoreCase("done"))
break;
name[i] = tmpName;
System.out.println(AGE_REQUEST);
age[i] = in.nextInt();
if(age[i] > age[older])
older = i;
if(age[i] < age[youngest])
youngest = i;
}
System.out.println("OLDER is : " + name[older]);
System.out.println("Younger : " + name[youngest]);
}
Try this out, I have tested it and it's working fine. Hope that helps. Happy coding.
package com.pearson.nextgen.aggregatedsessionservice;
import java.util.Scanner;
public class NameAgeTest {
public static void main(String[] args) {
String[] name = new String[10];
int[] age = new int[10];
Scanner in = new Scanner(System.in);
String NAME_REQUEST = "Please enter name";
String AGE_REQUEST = "Please enter age";
int count = 0;
while (count < 10) {
System.out.println(NAME_REQUEST);
String nameInput = in.next();
if (nameInput.equalsIgnoreCase("done")) {
break;
}
name[count] = nameInput;
System.out.println(AGE_REQUEST);
age[count] = in.nextInt();
count++;
}
int[] minAndMaxIndex = findMinAndMaxIndex(age, count);
System.out.println("Youngest Person: " + name[minAndMaxIndex[0]]);
System.out.println("Oldest Person: " + name[minAndMaxIndex[1]]);
}
private static int[] findMinAndMaxIndex(int[] inputArray, int count) {
int min, max = 0;
int minIndex = 0, maxIndex = 0;
max = min = inputArray[0];
for (int i = 0; i < count; i++) {
if (inputArray[i] > max)
maxIndex = i;
else if (inputArray[i] < min)
minIndex = i;
}
return new int[] { minIndex, maxIndex };
}
}

How to get array of strings or integers from users inside looping statement?

When I tried to run this code noOfSub() methods executed properly;
but GC() method faces the following problem:
Enter the number of subjects:
2
Enter Your Subject 1 Grade:
s
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35)
Java Result: 1
Here is my code:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i=1;
Scanner gradeInput = new Scanner(System.in);
String[] grade = new String[noOfSubjects];
int[] credit = new int[noOfSubjects];
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC() {
while(i<=noOfSubjects)
{
System.out.println("Enter Your Subject "+i+" Grade:" );
grade[i] = gradeInput.nextLine();
System.out.println("Enter the Subject "+i+" Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
When you do:
public int noOfSubjects;
noOfSubjects is set to 0 which is its default value
So when you have the following code:
String[] grade = new String[noOfSubjects];
it essentially means,
String[] grade = new String[0]; //create a new String array with size 0
which creates an empty array for you.
So when you do,
grade[i] = gradeInput.nextLine(); //where i is 1
you get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35
because there is no index 1 in String[] grade.
Problem in your array initialization. You can initialize your array after take the input from user.
For example :
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
And change your while condition. Instead of this you use
while(i < noOfSubjects)
and set i = 0
If you want to get the size for the array from the user, create the array after getting it from stdin. Otherwise it will create a array with the size of 0 which is the default value for int in java.
Separate your declaration and initalization
String[] grade = null;
int[] credit = null;
...
noOfSubjects = scan.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
Why don't you use ArrayList because the size of array isn't know for you
public class GPA {
public int noOfSubjects;
public int i=0;
Scanner gradeInput = new Scanner(System.in);
List<String> grade = new ArrayList<>();
List<Integer> credit = new ArrayList<>();
public void noOfSub(){
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC(){
while(i<noOfSubjects)
{
System.out.println("Enter Your Subject "+(i+1)+" Grade:" );
grade.add(gradeInput.nextLine());
System.out.println("Enter the Subject "+(i+1)+" Credit:");
credit.add(gradeInput.nextInt());
gradeInput.nextLine();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
Note : i added gradeInput.nextLine() after i++ because the Scanner.nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine() so i fire a blank gradeInput.nextLine() call after gradeInput.nextInt() to consume rest of that line including newline
Since the noOfSubjects has run time value so the code should be:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i = 0;
Scanner gradeInput = new Scanner(System.in);
String[] grade;
int[] credit;
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
public void GC() {
while (i < noOfSubjects) {
System.out.println("Enter Your Subject " + (i + 1) + " Grade:");
grade[i] = gradeInput.next();
System.out.println("Enter the Subject " + (i + 1) + " Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
for (int j = 0; j < grade.length; j++) {
System.out.println(grade[j] + " " + credit[j]);
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}

i don't get the right answer, why?

I'm quite new to java, and I've just started the course for a few days. I wrote the following code to make a simple phone book. It gets names and phone numbers first, then it gets a name and passes the phone number. Except the first name, if I enter any name it will print the last line (the name is not in the list) then the related number!!! Why?
import java.util.Scanner;
class MyPhoneBook {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String[] name = new String[200];
String[] number = new String[200];
System.out.println("when finished all contacts, just type : finish");
for (int a = 0; a < 200; a++) {
System.out.print("\nenter name:");
name[a] = myScan.nextLine();
if (name[a].equals("finish")) {
break;
} else {
}
System.out.print("enter number:");
number[a] = myScan.nextLine();
}
for (int a = 1; a > 0; a++) {
System.out.println("\nenter name to find number:\n");
String name2 = myScan.nextLine();
for (int b = 0; b < 200; b++) {
if (name2.equals(name[b])) {
System.out.println("number is " + number[b]);
break;
}
}
System.out.println("----THE NAME IS NOT IN THE LIST----\n");
}
}
}
Add a flag for when you find a name that matches user's input and dont print out last line when you find match, for that you could change your code like this:
for (int a = 1; a > 0; a++) {
System.out.println("\nenter name to find number:\n");
String name2 = myScan.nextLine();
boolean isNameFound = false;
for (int b = 0; b < 200; b++) {
if (name2.equals(name[b])) {
System.out.println("number is " + number[b]);
isNameFound = true;
break;
}
}
if (!isNameFound)
System.out.println("----THE NAME IS NOT IN THE LIST----\n");
}
Using a map will simplify this
Map<> contactBook = new Hashmap<>()
//then load the map using the phone number and name
You can also use data structure which will not allow dup names

Categories