If I enter 3 objects
aakash
12323
aakshit
24r352
rahul
12323
If i give this as a input and enter search string as 'aa' then it gives only first string that matches the search ouput will be
aakash
12323
why not aakshit also
import java.util.Scanner;
import java.io.*;
public class DA_2_searching {
String name,phone_number;
Scanner s = new Scanner(System.in);
DA_2_searching()
{
System.out.print("Enter the Details");
name=s.nextLine();
phone_number= s.nextLine();
}
void search()
{
String search;
search=s.nextLine();
if(name.startsWith(search))
{
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[])
{
int n;
Scanner s = new Scanner(System.in);
n= s.nextInt();
DA_2_searching obj[]= new DA_2_searching[n];
for(int i=0;i<n;i++)
{
obj[i]= new DA_2_searching();
}
for(int i=0;i<n;i++)
{
obj[i].search();
}
}
}
The reason for your problem is, that you only search for one object at a time. Your for loop that calls the search() function only compares one object to a search input at a time.
In the for loop, you are only calling the search function for one DA_2_searching object (the one with index i - obj[i]). But you want to search in every DA_2_searching object you created, that means you have to rework the search() function so that it gets all DA_2_searching objects and compares them to the search-String.
Here's my solution:
import java.util.Scanner;
public class DA_2_searching {
private String name, phone_number;
private static DA_2_searching[] allPersons;
private static Scanner s = new Scanner(System.in);
public DA_2_searching() {
System.out.println("Enter the Details: ");
System.out.print("Name: ");
this.name = s.next();
System.out.print("Phone-Number: ");
this.phone_number = s.next();
System.out.println("\nNext: ");
}
public static void search() {
System.out.println("Type a word to search for: ");
String toSearch = s.next();
for(DA_2_searching person : allPersons) {
if(person.name.contains(toSearch)) { //contains is better for searching.
System.out.println("Result: " + person.name + " | " + person.phone_number);
}
}
System.out.println("\n");
if(!toSearch.equals("exit")) {
search();
}
}
public static void main(String args[]) {
System.out.print("Amount of Entries: ");
int n = s.nextInt();
System.out.println("");
allPersons = new DA_2_searching[n];
//Creating Persons
for(int i = 0; i < n; i++) {
allPersons[i] = new DA_2_searching();
}
//initializing search
search();
}
}
In your current code you search for a String in every iteration. You read in a String and check if this String equals Array[0] then you print it. Then you read in a String again and check if it is equal to Array[1]... and so on. What you want is a search in the whole Array.
A simple solution would be to read in the String before the 2nd loop and pass the
string into search();
void search(String search) {
if (name.startsWith(search)) {
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[]) {
int n;
Scanner s = new Scanner(System.in);
n = s.nextInt();
DA_2_searching obj[] = new DA_2_searching[n];
for (int i = 0; i < n; i++) {
obj[i] = new DA_2_searching();
}
String search = new String();
search = s.nextLine();
for (int i = 0; i < n; i++) {
obj[i].search(search);
}
}
Related
I have to:
Prompt the user for a string,
if the string entered is in the array "names", print out its index,
if not in names, print out "NOT FOUND"
this is what I have:
This is for my programming final and i can't figure out how to do this because I missed 1 class...
import java.util.Scanner;
public class Final1 {
public static void main (String[] args) {
int y;
int x=0;
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
y=s.nextInt();
for (String a: names){
if (a.equals(y))
System.out.println(y);
}
}
}
Use Array.asList(yourArray).contains(yourValue):
import java.util.*;
public class Final1
{
public static void main (String[] args)
{
int y = 0;
int x = 0;
String name = "";
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
name = s.nextLine();
if(Arrays.asList(names).contains(name)) // Check this line
{
System.out.print(name);
}
}
}
If you are trying to print the index of it instead of the actual name again you will have to modify it a bit.
import java.util.*;
public class Final1
{
public static void main (String[] args)
{
int y = 0;
int x = 0;
String name = "";
boolean found = false;
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
name = s.nextLine(); // get a string instead of an int
// likely the way your professor would like you to do this
// there are many ways, but this is the quickest while using a simple array
// you could cast it to a list
for(int i=0; i<names.length; ++i){
if(names[i].equals(name)){
System.out.print(i);
found = true;
}
}
if(!found)
System.out.println("NOT FOUND");
}
}
Edit: You could also use the Arrays static class.
int result = Arrays.binarySearch(names, name);
if(result > 0)
System.out.println(result);
else
System.out.println("NOT FOUND");
The problem is that you get user input as int.
User input values are String in order to check names since names are contained in a String array.
You can try this:
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
String y;
int x=0;
int found = 0; //to identify the index
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
y=s.nextLine();
for (String a: names){
if (a.equals(y))
{
System.out.println("index of "+a+" is :"+x);
found++; // increment if found
}
x++;//iterate each time to get the index
}
if(found == 0)// check if it is not found
System.out.println("NOT FOUND");
}
}
Output:
Enter String Name:charley
index of charley is :2
You are comparing int y with scanned Integer. y should be a string and you should scan for a String.
Try this:
import java.util.Scanner;
public class Final1 {
public static void main (String[] args) {
int x=0;
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
String y=s.nextLine();
for (String a: names){
if (a.equals(y))
System.out.println(y);
}
}
}
Your y should be a String and you should input it with an s.nextLine(). Currently you are matching integers and strings. You could use the indexOf
int index = Arrays.asList(names).indexOf(s.nextLine());
return index > -1 ? "Not found" : Integer.toString(index);
public static public static void main(String[] args) {
System.out.print("Enter the number of student names to input: ");
int studentNum = new Scanner(System.in).nextInt();
String students[ ] = new String[studentNum];
for(int i = 0; i<studentNum; i++){
students[ i ] = inputStudent(i+1);
}
}
public static String[] inputStudent(int i) {
String studentNum[] = new String[i];
for(int a=0; a<i; a++) {
System.out.print("Enter student name"+(a+1)+": ");
studentNum[a]=new Scanner(System.in).nextLine();
}
return studentNum;
}
ERROR:
students[ i ] = inputStudent(i+1);
IT SAYS:
incompatible types: String[] cannot be converted to String
PS:
The main function should not be modified.
You are trying to assign String array to String
i.e
inputStudent(int i)
returns Array, but you are trying to assign Array to students[ i ] = inputStudent(i+1);
As
String[i] is the element String array which will accept String only
Change your method to this. You cannot assign a String array to a String. Also, why do you loop in your method? If I understand correctly you want to add n students to a student array? You loop in your main and method runs for each student.
public static String inputStudent(int i) {
System.out.print("Enter student name");
String studentName = new Scanner(System.in).nextLine();
return studentName;
}
Modify your input student method in such a way that it returns a single student only.
public static String inputStudent(int i) {
String studentNam = null;
System.out.print("Enter student name"+i+": ");
studentNum=new Scanner(System.in).nextLine();
return studentNum;
}
Since you stipulate that the main function can not be modified you are going to have to change the return type of your inputStudent function from String[] to String. This will mean you have to change how you are storing the data inside that function.
So, change the String studentNum[] to String studentNum and instead of asking for a new user input for every index of the array, ask for all inputs at once comma separated and store them in studentNum.
This is one possible approach according to your criteria.
I understand what you want to implement, the code below will solve your problem, every line of code has the explanation.
public static void main(String[] args) throws Exception {
System.out.print("Enter the number of student names to input: ");
Scanner scanner = new Scanner(System.in); // get the scanner
int numOfStudents = scanner.nextInt(); // get the number of students from user
String [] students = new String [numOfStudents]; // create an array of string
int studentAdded = 0; // counter
scanner = new Scanner(System.in); // recreate the scanner, if not it will skip the first student.
do {
System.out.println("Enter student name "+(studentAdded+1)+": ");
String studentName = scanner.nextLine(); // ask for student name
students[studentAdded] = studentName; // add student name to array
studentAdded++; // add 1 to the counter
} while (studentAdded < numOfStudents); // loop until the counter become the same size as students number
System.out.println("students = " + Arrays.toString(students)); // and show the result
}
What you can do to do is change:
students[ i ] = inputStudent(i+1);
to
students[ i ] = Arrays.toString(inputStudent(i + 1));
As students is a String you are unable to assign an array directly to a String. By using Array.toString() it will return a representation of the contents of the array as a String value.
Looking at your question again you are unable to modify the main. In this case we can set inputStudent to return a String type.
public static String inputStudent( int i )
{
String studentNum[] = new String[i];
for( int a = 0; a < i; a++ )
{
System.out.print( "Enter student name" + (a + 1) + ": " );
studentNum[a] = new Scanner( System.in ).nextLine();
}
return Arrays.toString(studentNum);
}
Or short and sweet.
public static String inputStudent( final int id )
{
System.out.print("Enter student name at ID: "+id+": ");
return new Scanner( System.in ).next();
}
You have an error in your code. For loop is not needed in main
public static public static void main(String[] args) {
System.out.print("Enter the number of student names to input: ");
int studentNum = new Scanner(System.in).nextInt();
String students[ ] = inputStudent(studentNum);
}
public static String[] inputStudent(int i) {
String studentNum[] = new String[i];
for(int a=0; a<i; a++) {
System.out.print("Enter student name"+(a+1)+": ");
studentNum[a]=new Scanner(System.in).nextLine();
}
return studentNum;
}
So I'm new to Java and I figured I'd do something simple like a for loop to print out an array of strings or something,
My code ended up like this:
package package.four;
import java.util.Scanner;
public class arrayrecurse {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Please enter 5 words");
String a = in.next();
String b = in.next();
String c = in.next();
String d = in.next();
String e = in.next();
String[] s = {a, b, c, d, e};
for(int i = 0; i< s.length;){
System.out.println(s[i]);
i++;
}
in.close();
}
}
It works fine but my question is if it's possible to make a for loop cycle through variables.
For examples if I wanted something like:
for(words = 5; words > 0;){
String a = in.next();
a++}
Where would it change the variables each time I enter a new word.
Would it be possible to do something like that or do I need to type out the String variable = in.next(); every time I want to enter a new word input from the console?
You can call next() inside the loop, but you need to declare the variable outside the loop if you want to use it afterwards, also, there is no ++ operator for String or array in Java:
String[] inputs = new String[5];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
Use an ArrayList to store the input variables.
That is:
import java.util.*;
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (String s: inputVars)
{
System.out.println(s);
}
}
Or alternatively, if you want to change the contents of the ArrayList:
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (int i = 0; i < inputVars.size(); i++)
{
System.out.println(inputVars.get(i));
//Change the variable
inputVars.set(i, "Hello, " + inputVars.get(i));
}
}
I have to write a program having 3 parallel arrays one that holds 4 digit student ID the second the student Name and the last one that holds the GPA and the size of the arrays have to be 10
also the program be able to do a Student ID search and if it doesnt exist to show an error message
the first part works fine but when it comes to the searching it doesnt work
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.util.Scanner;
public class StudentIDArray
{
public static void main(String[] args)
{
int option;
String inputString;
inputString = JOptionPane.showInputDialog("Welcome"
+" Choose the option you will like"
+ " \n1. Enter Student Information "
+ "\n2. Search for Student");
option = Integer.parseInt(inputString);
if(option ==1)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the Student");
String[] studentname = new String[10];
for(int i =0; i<studentname.length; i++)
{
studentname[i] = in.nextLine();
}
System.out.println("Enter the 4 digit Student ID");
int[] studentID = new int[10];
for(int x=0; x<studentID.length; x++)
{
studentID[x] = in.nextInt();
}
System.out.println("Enter the Student's Grade Point Average");
int[] gpa = new int[10];
for(int y=0; y<studentID.length; y++)
{
gpa[y] = in.nextInt();
}
}
else
{
searching();
}
}
public static void searching()
{
int idnumber,
results;
int[]studentID = null;
String inputString;
inputString = JOptionPane.showInputDialog("Please Enter the ID number");
idnumber = Integer.parseInt(inputString);
results = sequentialSearch(studentID, idnumber);
if (results == -1)
{
System.out.println("no information");
}
else
{
System.out.println("yeii congrats");
}
}
public static int sequentialSearch(int[] studentID, int value)
{
int index;
int element;
boolean found;
index =0;
element = -1;
found = false;
while(!found && index < studentID.length)
{
if (studentID[index] == value)
{
found = true;
element = index;
}
index++;
}
return element;
}
}
The primary issue is that you are declaring the studentID array locally to your methods.
Make it a class member instead (an instance member would be preferred, but all your methods are static), so that your methods are working on the same array, not on different ones:
public class StudentIDArray
{
private static int[] studentID = new int[10];
...
Note that this limits the number of entries to the size of the array and you will get exceptions if you exceed these limits. Consider using a Vector or an ArrayList instead.
searching(studentID);
Pass the studentID array to the searching method instead of declaring it again.
public static void searching(int[] studentID)
{
int idnumber,
results;
//int[]studentID = null;
String inputString;
inputString = JOptionPane.showInputDialog("Please Enter the ID number");
idnumber = Integer.parseInt(inputString);
results = sequentialSearch(studentID, idnumber);
if (results == -1)
{
System.out.println("no information");
}
else
{
System.out.println("yeii congrats");
}
}
public static int sequentialSearch(int[] studentID, int value)
{
int index;
int element;
boolean found;
index =0;
element = -1;
found = false;
while(!found && index < studentID.length)
{
if (studentID[index] == value)
{
found = true;
element = index;
}
index++;
}
return element;
}
A better approach would be to keep it as a static/class variable as #Andreas pointed out.
These are the Running Steps of Program....
First Step => Enter Size of Array.
Second Step => Enter Member of Array.
Third Step => Enter Searching Integer of Array.
import java.util.Scanner;
public class Searching
{
public static void main(String[] args)
{
int temp =-1;
Scanner user_input=new Scanner(System.in);
System.out.println("Enter Size Of Array ");
int Size=user_input.nextInt();
int[] a=new int[Size];
//Scan input Array.
System.out.println("Enter element Of an Array...");
for(int j=0;j<Size;j++)
{
a[j]=user_input.nextInt();
}
System.out.println("The contents of the Array are :");
//Print input Arrray
for(int i=0;i<a.length;i++)
{
System.out.println("array[" + i + "] = " + a[i]);
}
System.out.println("Enter Integer For Searching..");
int Search=user_input.nextInt();
//Searching in an Array.
for(int index=0;index<a.length; index++)
{
if(a[index]==Search)
{
temp=index;
break;
}
}
if(temp!=-1)
{
System.out.println(" The search element is : " + Search);
System.out.println(" It is found in the array at position : " + temp);
}
else
System.out.println("\n Element not Found..");
}
}
My code works fine. However the output seems incorrect when I enter -1 from name or age input. How do I remove null values and "-1" and display the existed array?
import java.util.Scanner;
public class quizLoop {
private static Scanner key = new Scanner(System.in);
private static Scanner keyNum = new Scanner(System.in);
public final static int arrayLoop = 5;
public static String[] nameList = new String[arrayLoop];
public static int[] age = new int[arrayLoop];
public static void main(String[] args) {
System.out.println("NAME & AGE SYSTEM\n-----------------\n");
for(int i=0; i<arrayLoop; i++) {
System.out.print("Name: ");
nameList[i] = key.nextLine();
if(nameList[i].equals("-1"))
break;
System.out.print("Age: ");
age[i] = keyNum.nextInt();
if(age[i] < 0)
break;
}
System.out.println("----------");
for(int i=0; i<nameList.length; i++) {
System.out.println(nameList[i] + " " + age[i]);
}
}
}
Currently, when you input -1, the loop exits. That is, as soon as you input -1, the loop is not run again. This is because you use the break statement.
If you'd like to let -1 allow the user to start the current entry again, you'll need to do two things:
if (nameList[i].equals("-1")) {
// Take the loop variable down one.
i--;
// Instead of break, continue to the next iteration.
continue;
}
If you want to keep the loop how it is, but only print non-null values, modify your printing code:
for(int i=0; i<nameList.length; i++) {
if (nameList[i] == null || nameList[i].equals("-1") || age[i] < 0) {
// Invalid; go to the next one.
continue;
} else { // (not strictly necessary)
System.out.println(nameList[i] + " " + age[i]);
}
}
Try to use a List instead a Array, something like this:
import java.util.Scanner;
public class quizLoop {
private static Scanner key = new Scanner(System.in);
private static Scanner keyNum = new Scanner(System.in);
public final static int arrayLoop = 5;
public static List<String> nameList = new ArrayList<String>();
public static List<Integer> ages = new ArrayList<Integer>();
public static void main(String[] args) {
System.out.println("NAME & AGE SYSTEM\n-----------------\n");
while (true){
System.out.print("Name: ");
String name = key.nextLine();
if(name.equals("-1"))
break;
System.out.print("Age: ");
Integer age = keyNum.nextInt();
if(age < 0)
break;
nameList.add(name);
ages.add(age);
}
System.out.println("----------");
for(int i=0; i<nameList.length; i++) {
System.out.println(nameList[i] + " " + age[i]);
}
}
}