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)
Related
When I insert the arguments the search always returns "not found" - even though the searched value was input into the array?
import java.util.Scanner;
public class assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] BookID = new String [3];
String [] Booktitle = new String [3];
//input the BookID
System.out.println("Enter the 12 BookID");
for (int a = 0 ; a < BookID.length; a++)
{
System.out.print("BookID :");
BookID[a] = sc.next();
}
//Input the book title
for (int b = 0 ; b < Booktitle.length ; b++)
{
System.out.print("Booktitle :");
Booktitle[b] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter BookID to find :");
for(int c = 0; c < BookID.length; c++)
{
searchValue = sc.next();
if(searchValue.equals(BookID))
System.out.print("BookID is found : ");
else
System.out.print("BookID is not found : ");
}
}
}
I'm expecting the result to return like so: if input BookID 112. The Linear search would return "The BookID is found :" instead of the else statement.
Try printing out the value of the bookId you wanna find to see if there anything with the string that could cause it to not be equals. Also, you could convert the string to an integer with:
Integer.parseInt("BookId");
The equals would have less chance of failing, you could also change de the array for an array of int instead of String.
This code has some basic things right, but it could be a bit better. Some of the changes I made are for keeping Java conventions (so the code is easier to read and understand) and some are functional. I added them as comments.
import java.util.Scanner;
public class Assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] bookIDs = new String [3]; //lowercase for the attribute name (convention)
String [] bookTitles = new String [3]; //plural for the array (convention)
//input the BookID
System.out.println("Enter the Book ID");
for (int i = 0 ; i < bookIDs.length; i++) { //you can re-use the i in all loops
System.out.print("Enter " + i + " Book ID: ");
bookIDs[i] = sc.next();
}
//Input the book title
for (int i = 0 ; i < bookTitles.length ; i++) {
System.out.print("Enter " + i + " Book title: ");
bookTitles[i] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter Book ID to find: ");
searchValue = sc.next(); //NOTE: this is your first mistake. read out of the loop
for(int i = 0; i < bookIDs.length; i++) {
if(searchValue.equals(bookIDs[i])) { //NOTE: this is your second mistake - you wanted the array value, not the array
System.out.println("BookID is found in position "+i);
break; //suggestion - stop the loop when found.
}
else {
System.out.println("BookID is not found in position "+i);
}
}
sc.close(); //NOTE: important to close scanners at the end.
}
}
Good luck with your studies.
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]);
}
I am trying to create a program which will be able to search a user inputed string for a specific word, and count the number of times that word is repeated.
For example I want the program to function like this:
Please enter a string of your choice:
kelowna is a nice city, kelowna is my home.
Enter a word for which you would like to search for:
kelowna
The word Kelowna was found 2 times.
How would I go about doing this? My initial approach was to use loops, but that hasn't got me too far.
This is what I have so far:
import java.util.Scanner;
public class FinalPracc {
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
System.out.println("please enter a string of you choice: ");
String a = s1.nextLine();
System.out.println("Please enter the word you would like to search for: ");
String b = s1.nextLine();
int aa = a.length();
int bb = b.length();
if (a.contains(b)) {
System.out.println("word found");
int c = a.indexOf(b);
int
if (
}
}
/* ADD YOUR CODE HERE */
}
One approach would be that if you find the word, modify the search string to remove everything before and including the word, then search again:
public static void main(String[] args) {
Scanner s1=new Scanner(System.in);
System.out.println("please enter a string of you choice: ");
String a=s1.nextLine();
System.out.println("Please enter the word you would like to search for: ");
String b=s1.nextLine();
int count = 0;
while(b.contains(a)) {
count++;
int pos = b.indexOf(a);
b = b.substring(pos + a.length());
}
if (count > 0){
System.out.println("word found " + count + " times");
} else {
System.out.println("word not found");
}
}
Edit: Alternatively, if you don't want to call substring in a loop, you could use the form of indexOf that takes a starting index for the search. In this case, your loop might look like:
int count = 0;
int searchIndex = 0;
while((searchIndex = b.indexOf(a, searchIndex)) > -1) {
count++;
searchIndex += a.length();
}
Maybe something like while(a.contains(b))
and set up a counter by one every time a word is found and cut everything until the last sign of the found word every loop round.
My program does not end. I am a beginner and am having trouble understanding why. It was working fine before I changed the name, so I copied it to another file, but it still does not end.
import java.util.Scanner;
public class Fan
{
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
//first input
System.out.println("Enter your first input: ");
String first = s.nextLine();
String[] firstsplit = first.split(", ");
//second input
System.out.println("Enter your second input: ");
String second = s.nextLine();
String[] secondsplit = second.split(", ");
//third input
System.out.println("Enter your third input: ");
String third = s.nextLine();
String[] thirdsplit = third.split(", ");
//fourth input
System.out.println("Enter your fourth input: ");
String fourth = s.nextLine();
String[] fourthsplit = fourth.split(", ");
//fifth input
System.out.println("Enter your fifth input: ");
String fifth = s.nextLine();
String[] fifthsplit = fifth.split(", ");
for (int a = 0; a<=firstsplit.length-1; a++)
{
//skipping over values that say how many pieces are on board
for (int i = 3; i <= 12; i++)
{
//compatible with piece numbers up to 12(max)
if (Integer.parseInt(firstsplit[0])==i) {
while (i >= 1 && i <= Integer.parseInt(firstsplit[i])) {
continue;
}
System.out.println(firstsplit[i]);
}
}
}
}
}
I would be grateful for any advice.
The problem is here:
while (i >= 1 && i <= Integer.parseInt(firstsplit[i])) {
continue;
}
This is an infinite loop since you never change the value of i inside it. Just comment it to make your application finish. Then, spend some time thinking about how to fix it or what are you trying to accomplish with this loop.
Working on a project for school and I'm getting a error when I try to enter the number of students for the array. The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Project1.enterStudents(Project1.java23)
at Project1.mainMenu(Project1.java59)
at Project1.enterStudents(Project1.java7)
The code I have written it below as always any help is appreciated.
import java.util.Scanner;
public class Project1{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Project1 project1 = new Project1();
project1.mainMenu();
}//main
int numOfStudents;
Student[] students = new Student[numOfStudents];
public void enterStudents(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students");
numOfStudents = input.nextInt();
int i;
for(i = 0; i <= numOfStudents - 1; i++){
i--;
System.out.println("Enter student's ID: ");
students[i].getId();
System.out.println("Enter student's first name: ");
students[i].getFirst();
System.out.println("Enter student's last name: ");
students[i].getLast();
System.out.println("Enter student's class: ");
students[i].getStuClass();
}
}
public void retrieveStuId(){
Scanner input = new Scanner(System.in);
System.out.println("Enter student id");
}
public void Exit(){
System.exit(0);
}
public void mainMenu(){
Scanner input = new Scanner(System.in);
System.out.println("1 - Enter student info");
System.out.println("2 - Retrieve student by ID");
System.out.println("3 - Retrieve student by last name");
System.out.println("4 - Update student");
System.out.println("5 - Exit");
int menuSelect = input.nextInt();
if (menuSelect != 1 && menuSelect != 2 && menuSelect != 3 && menuSelect != 4 && menuSelect != 5)
System.out.println("That is not a option");
else
switch (menuSelect){
case 1: enterStudents();
case 2: System.out.print("case 2");
case 3: System.out.print("case 3");
case 4: System.out.print("case 4");
case 5: Exit();
}
}
}//project1
class Student{
private int studentID;
private String firstName;
private String lastName;
private String stuClass;
public Student(){
}
public Student(int id, String first, String last, String c ){
studentID = id;
firstName = first;
lastName = last;
stuClass = c;
}
public void setID (int id){
studentID = id;
}
public void setStuClass (String c){
stuClass = c;
}
public void setFirst(String first){
firstName = first;
}
public void setLast(String last){
lastName = last;
}
public String getFirst(){
return firstName;
}
public String getLast(){
return lastName;
}
public int getId(){
return studentID;
}
public String getStuClass(){
return stuClass;
}
public String toString(){
return "Student ID: " + studentID + " ---- " + "Student Name: " + firstName + "" + lastName + " ---- " + "Class:" + stuClass;
}
}
Look at this bit of code:
for(i = 0; i <= numOfStudents - 1; i++){
i--;
System.out.println("Enter student's ID: ");
students[i].getId();
Now work out what the value of i is going to be on each line...
Why do you have the i--; line at all?
Note that this only addresses the first ArrayIndexOutOfBoundsException issue - once that's fixed, you'll end up with another ArrayIndexOutOfBoundsException because you're initializing the array before asking for numOfStudents.
Once that's addressed, you'll get a NullPointerException because you're trying to call methods via null references - you never actually create a new Student instance.
To be honest, this program is quite a long way from working - I'm not sure that Stack Overflow is going to provide the most effective teaching environment in this particular case. I would suggest you talk to your teacher and ask for some 1-on-1 tutoring.
The i--; at the top of your loop body is a likely culprit. In fact, if it wasn't causing this problem, I think it'd make your loop run forever. Why is that even there?
Also, I see another problem. When the array students is initialized, numOfStudents has not yet been assigned a value. Since it's an instance variable, it defaults to 0, which means students won't actually hold any Students.
for(i = 0; i <= numOfStudents - 1; i++){
// REMOVE THIS i--;
// i is = -1 here but Arrays start by 0
System.out.println("Enter student's ID: ");
students[i].getId();
System.out.println("Enter student's first name: ");
students[i].getFirst();
System.out.println("Enter student's last name: ");
students[i].getLast();
System.out.println("Enter student's class: ");
students[i].getStuClass();
}
Why this?
for(i = 0; i <= numOfStudents - 1; i++){
i--; //<--THIS
The problem is probably there. You are tryng to access to an array with a negative index number.
int numOfStudents is initialized to nothing.
so attempting to edit your students array will not work.
How to fix it:
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students");
int numOfStudents = input.nextInt(); //this initializes to something.
Student[] students = new Student[numOfStudents];
then continue with your loop gathering the data.
Of course, you will want to remove the i-- as pointed out by others.
It's the i-- in your loop in enterStudents. This causes the index to go from 0 to -1 which is invalid. What exactly is this i-- supposed to accomplish?
Looks like others here have already pointed out the answer, but here's how to fish...
The fact that it's an ArrayIndexOutOfBoundsException tells you that it's happening while you're accessing an array, and it's even kind enough to tell you the index you've used that's out of bounds (in this case, -1, which is always out of bounds -- array indexes must be >= 0).
enterStudents only uses one array, and its index always comes from one variable. So, mentally step through your code and follow the values of that variable i to see if/how it can ever be -1.
Btw, for(i = 0; i <= numOfStudents - 1; i++) will work, but for(i = 0; i < numOfStudents; i++) is a bit more idiomatic.