Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am making a simple for loop to go through an ArrayList and add objects to them but when I enter my first object nothing happens. It looks like the program isn't continuing the loop. Here is what I have:
for (int i = 0; i < (numPlayers.nextInt()-1); i++){
System.out.println("what is player " + (i + 1) + " name?");
Scanner namePlayer = new Scanner(System.in);
String playerName = namePlayer.nextLine();
playerList.add(new Player(playerName));
}
The player object constructor is very simple as well
public Player(String name) {
this.name = name
}
public static void main(String[] args)
{
Scanner numPlayers = new Scanner(System.in);
ArrayList<Player> playerList = new ArrayList<>();
int input = numPlayers.nextInt();
for (int i = 0; i < input; i++){
System.out.println("what is player " + (i + 1) + " name?");
String playerName = numPlayers.next();
playerList.add(new Player(playerName));
}
}
You should have declared scanner object outside the for the loop. The problem with your code was each time after taking a string input your code was needed to provide an integer for (int i = 0; i < (numPlayers.nextInt()-1); i++) and that's why if you provide anything but an integer it gives InputMismatchException. So you have to initialize the input constant outside the for loop otherwise execution will vary dynamically.
You need to define the limits of your loop only once, if possible:
int numberOfPlayers = numPlayers.nextInt()-1;
for (int i = 0; i < numberOfPlayers; i++){
System.out.println("what is player " + (i + 1) + " name?");
Scanner namePlayer = new Scanner(System.in);
String playerName = namePlayer.nextLine();
playerList.add(new Player(playerName));
}
You will need to make sure that you are iterating the loop as many times as you want.
Related
At the start of the code the user determines a number of keywords and the keyword strings themselves, they place this into an array. Lets say the user says 3 keywords and they are "music", "sports" and "memes". After all this, say the user inputs in the program "I like sports". I simply want the program to respond with "Let's talk about sports" after recognising that the user said sports which is in the array that the user has essentially created.
I want to reference a string the user has predetermined then print it along with a message
I can see the potential of this working using for loops and going through every article until you find a match, I haven't done much work with booleans yet so I just need some assistance punching out the code then learning from it
this all has to happen inside a while loop so when that's done they can use a different keyword and get the same boring response
thanks
note: I don't actually have any of this code I want in my program yet, this code is just to show you kind of how it fits into the greater scheme of things.
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
String kwArray[];
String UserMessage;
String Target = "";
int numKw = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many keywords do you want?");
numKw = input.nextInt();
kwArray = new String[numKw];
System.out.print(System.lineSeparator());
input.nextLine();
for (int i = 0; i < numKw; i++) {
System.out.println("Enter keyword " + (i + 1) + ": ");
kwArray[i] = input.nextLine();// Read another string
}
for (int i = 0; i < numKw; i++) {
kwArray[i] = kwArray[i].toLowerCase();
}
int x = 0;
while (x == 0) {
System.out.println("Hey I'm a chatbot! Why don't you say something to me!");
System.out.println("These are the keywords you gave me");
for (String i : kwArray) {
System.out.print(i);
System.out.print(", ");
}
System.out.print(System.lineSeparator());
System.out.println("Or you can terminate the program by typing goodbye");
UserMessage = input.nextLine();
// Gives the user opportunity to type in their desired message
UserMessage = UserMessage.toLowerCase();
if (UserMessage.contains("?")) {
System.out.println("I will be asking the questions!");
}
if (UserMessage.contains("goodbye")) {
x = 1;
}
}
input.close();
}
}
If I am getting the question right, you want to check whether an element exists in the submitted keywords and want to reference it back if you further processing.
For this, instead of an array you could use a HashSet which can check the existence any element in O(1).
Updated the code, but I still feel your query is the same what I understood, putting the exact example of your use case below:
Scanner input = new Scanner(System.in);
Set<String> set = new HashSet<String>();
int keywords = input.nextInt();
for (int i=0; i<keywords; i++) {
//add to set set like:
set.add(input.readLine());
}
String userComment = input.readLine();
String[] userCommentWords = userComment.split(" ");
//you can iterate over the words in comment and check it in the set
for (int i=0; i<userCommentWords.length; i++) {
String word = userCommentWords[i];
if (set.contains(word)) {
System.out.println("Let's talk about "+word);
}
}
I'm having problems realizing why my counter keeps printing out a different value even when I enter all the right answers. I've tried everything I could think of plus researching and still no luck. Please help, this is hour 14 of me working on this "simple" program.
import java.util.Scanner; //import scanner
public class DriverTestBlah {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
char[] correctAnswers = {'A','D','C','A','A','D','B',
'A','C','A','D','C','B','A','B'};
char singleAnswer = ' ';
int number_Correct = 0;
for(int i = 0; i < 15; i++) //print question numbers/takes user input
{
System.out.println("Question " + (i + 1) + ":");
singleAnswer = input.nextLine().charAt(0);
}//end of for loop
System.out.println("number correct: " +
total_correct_answers(correctAnswers, singleAnswer));
}//end of main
public static int total_correct_answers(char []correctAnswers,char singleAnswer){
int number_correct = 0;
for (int i = 0; i < 15; i++){
if(correctAnswers[i] == singleAnswer){
number_correct++;}
}//end of for loop
return number_correct;
}//end of correct method
}//end of class
The reason your program was showing wrong value is singleAnswer variable stores only the last value/answer given by user.
I have created an array userAnswer to store all answers given.
Try this:
public class DriverTestBlah {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
char[] correctAnswers = {'A','D','C','A','A','D','B',
'A','C','A','D','C','B','A','B'};
char[] userAnswer = new char[correctAnswers.length];
for(int i = 0; i < 15; i++) //print question numbers/takes user input
{
System.out.println("Question " + (i + 1) + ":");
userAnswer [i] = input.nextLine().charAt(0);
}//end of for loop
System.out.println("number correct: " + total_correct_answers(correctAnswers, userAnswer));
input.close();
}//end of main
public static int total_correct_answers(char []correctAnswers,char [] userAnswer) {
int number_correct = 0;
for (int i = 0; i < 15; i++){
if(correctAnswers[i] == userAnswer[i]){
number_correct++;
}
}//end of for loop
return number_correct;
}//end of correct method
}//end of class
For every question you have the correct answers in the array correctAnswers and user-answer where? In this mode in singleAnswer you save only the last answer of user and check it for every answer.
To solve this problem you can create an array of char of singleAnswer like that:
char[] singleAnswer=new char[15];
And the result add in the array:
singleAnswer[i]=input.nextLine().chatAt(0);
After you can see if the result is correct with this instruction in the for loop:
if(singleAnswer[i]==correctAnswers[i]) number_correct++;
I am new to programming and I decided to learn Java. I had just finished reading about one dimensional array and I am having trouble with searching.
The summary of this program I had made is to ask the user how many students will be enrolled in the class. The user then inputs the name of the students based on the length of the array. Then I want the to be able to have the user search for the students name. How can i accomplish this? What I want to accomplish is when the user inputs the first name it will return the list of full names that has the matching first name. I really struggling with this. Please don't give any advanced methods. I would like to stay in pace pace with my book.
I am using introduction to java programming comprehensive version 10th edition.
import java.util.Scanner;
public class classSystem {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
}
public static String[] getStudentAttendance(int studentAmount)
{
Scanner input = new Scanner(System.in);
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++)
{
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String StudentSearch)
{
for (int count = 0; count < enrolledStudents.length; count++)
{
if(StudentSearch.equals(enrolledStudents[count]))
{
return getStudent;
}
}
}
}
I have updated your code. Please see the comments inline. Hope this helps.
import java.util.Scanner;
class classSystem {
static Scanner input; //created a static reference for Scanner
//as you will be using in both the methods
public static void main(String[] args) {
input = new Scanner(System.in); //creating the Scanner object.
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
input.nextLine(); //added this to consume new-line leftover
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
input.close(); //close the scanner
}
public static String[] getStudentAttendance(int studentAmount) {
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String studentSearch) {
boolean flag = false; //added flag, this will be true if name is found
//otherwise false
for (int count = 0; count < enrolledStudents.length; count++) {
if (studentSearch.equals(enrolledStudents[count])) {
flag = true;
break; //if name is found breaking the loop.
} else {
flag = false;
}
}
if (flag == true) //checking the flag here
return studentSearch + " is present in the class";
else
return studentSearch + " is not present in the class: ";
}
}
I am getting below result after running my code.
Looks like you already got the idea how to search using .equals() method. Assuming you'll fix getStudent() method by handling "not found" situation, you should be done.
Next, do you want to improve your search, is that your real question? That depends on what type of search do you want to implement. Partial name match, name starts with, ignoring upper/lower case, wildcard search are different options. If that is what you want, please add it to the question.
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();
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hi there I am trying to create an array of records in java in which you have to enter 3 details, the name of a town, the population and the county in which is resides. Before then outputting all the data on a county which you have asked for. I was wondering if anyone could show me why a null.point.exception occurs if I enter the population of a town when does not occur when i enter another one.
import java.util.*;
public class CathedralTowns
{
public static String name;
String population;
String county;
public static int count = 0;
public static int continuation = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
while (loop1 <= 0) {
System.out.println("Please enter the name of the town. ('no' to end)");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides. ('no' to end)");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town. ('no' to end)");
String populationEntered = input.nextLine();
if (nameEntered.equals("no") || populationEntered.equals("no") || countyEntered.equals("no") ) {
loop1 = 5;
System.out.println("Thank you for entering your county.");
continuation = 1;
}
WorkingDemCathedrals(nameEntered, populationEntered, countyEntered);
}
}
public static void WorkingDemCathedrals(String nameEntered, String populationEntered, String countyEntered) {
Scanner input = new Scanner(System.in);
CathedralTowns[] allTowns = new CathedralTowns[50];
allTowns[count] = new CathedralTowns();
int loop2 = 0;
int loop3 = 0;
while (loop2 == 0){
allTowns[count].name = nameEntered;
allTowns[count].population = populationEntered; //the error relates back to here according to bluej
allTowns[count].county = countyEntered;
if (continuation == 1) {
loop2 = 1;
System.out.println("please enter the name of a county for which you wish to know the details.");
String countyOfChoice = input.nextLine();
while (loop3 > 0){
if ((allTowns[loop3].county).equals(countyOfChoice)){
System.out.println(allTowns[loop3].name);
System.out.println(allTowns[loop3].population);
loop3 = -2;
}
loop3 = loop3 +1;
}
}
count = count + 1;
}
}
}
Elements in an Object array are null by default. Initialialise the elements prior to attempting to access them
for (int i=0; i < allTowns.length; i++) {
allTowns[i] = new CathedralTowns();
}
This lines is very suspicious
allTowns[count] = new CathedralTowns();
You allocate only one object in the array while you have a line before allocated an array of the length 50.
CathedralTowns[] allTowns = new CathedralTowns[50];
Not to mention that it is prone to ArrayIndexOutOfBoundsException if count is equal or more that 50
Then you start to loop and increment count and that's where it happens!
your should loop over the entire array and allocate an object in each slot.
The NullPointerException occurs at "population" and not at "name" is because the "name" field is static, whereas the "population" is non-static.
Also the allocation of the array of CathedralTowns has to be done as per the first answer.
The while (loop2 == 0) could end up in a infinite loop. There is no end condition for this while loop, if the user wants to enter details of more than one county.