no matter what I use indexof() or contains or .equals() changing everything to uppercase or to lowercase It always return false and not found can someone please tell me what is going on?
class Students{
private ArrayList<String> snames;
private String tname;
//this one combines both question 2 and 4.
public Students(String tname){
snames=new ArrayList<>();
this.tname=tname;
}
public String gettname(){return tname;}
public ArrayList<String> getsnames(){return snames;}
public void addStudent(String name){
snames.add(name);
}
public boolean studentExists(String name){
boolean e=false;
for(String i:snames){
if(i.contains(name)){
e=true;
}
}
return e;
}
}
public class Main
{
public static void main(String[] args) throws IOException{
Scanner k=new Scanner(System.in);
out.println("what is your name?");
String name=k.nextLine();
out.println(name.toUpperCase());
Students s=new Students(name);
out.println("enter student name");
String snames=k.nextLine();
while(snames!="."){
out.println("enter student name");
snames=k.nextLine();
s.addStudent(snames);
if (snames.equals("."))
break;
}
out.println("who u want to find");
String target=k.nextLine();
boolean exist=s.studentExists(target);
if(exist==true){
out.println("Found student");
}
else out.println("Student not found.");
out.println(exist);
}
}
no matter what I use indexof() or contains or .equals() changing everything to uppercase or to lowercase It always return false and not found can someone please tell me what is going on?
You have a logic issue...
out.println("enter student name");
String snames = k.nextLine();
while (snames != ".") {
out.println("enter student name");
snames = k.nextLine();
s.addStudent(snames);
if (snames.equals(".")) {
break;
}
}
You...
Prompt for the name
Read the next line of input
Check to see if it's the exit condition (by the way, snames != "." is wrong, it should be !".".equals(snames)
You prompt them to enter the name
You read the input
You write the input to Students
You check for the exit condition ... again
So, between 3 and 4, you never write what was first entered by the user, so, if you only enter
enter student name
jack
enter student name
.
Only . will be added to the list
Instead, you should be doing something more like...
Scanner scanner = new Scanner(System.in);
Students students = new Students("Test");
String name = ".";
do {
System.out.print("enter student name (or \".\" to exit) ");
name = scanner.nextLine();
if (!name.equals(".")) {
students.addStudent(name);
}
} while (!name.equals("."));
do {
System.out.print("who u want to find (or \".\" to exit) ");
name = scanner.nextLine();
if (!name.equals(".")) {
if (students.studentExists(name)) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} while (!name.equals("."));
The important point here is to make sure when you ask for input, you are actually writing it the list, unless it's the exit value (ie .)
The code is bad-structured, and the first snames is never added to the ArrayList.
See the codes below in class Main:
public static void main(String[] args) throws IOException {
// ignore the teacher name part
Students s = new Students(name);
// when the first snames is received,
System.out.println("enter student name");
String snames = k.nextLine();
while (snames != ".") {
// the name is not saved, but another snames is received.
System.out.println("enter student name");
snames = k.nextLine();
System.out.println(snames);
s.addStudent(snames);
// the "." is also saved as well.
if (snames.equals("."))
break;
}
}
}
I would suggest modifying the while loop into something like this:
Students student = new Students(tname);
// no need to get scanner output before loop
String sname;
do {
System.out.println("enter student name");
sname = scanner.nextLine();
System.out.println(sname);
student.addStudent(sname);
} while (!sname.equals("."));
Hope this answer helps you well.
Related
This is the Question: Create an array of Strings and assign 5 names to it. Ask the user what their name is, if their name is the same as one that is already in the list do something. Get creative!, use a for-each loop to print every name in the array with a space in-between each indices.
This is what I have so far. One of the issues I am having is that the scanner is only comparing the input to the first name on the array and not the rest.
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
}
else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
break;
}
}
}
Feel free to comment on any other issues you see. I am new at this and I'd appreciate an feedback. Thx
Maybe this will be helpful. I think the "break" is called prematurely. There are lots of ways you can solve this, but I used a boolean to determine if the name was found. Then I used the boolean after the loop to determine what to print.
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
boolean isFound = false;
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
isFound = true;
break;
}
}
if (isFound) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
} else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
}
Same method but slightly different :)
`import java.util.Scanner;
import java.util.ArrayList;
public class New {
public static void main (String[]args) {
String [] cities = {"Poznan", "Warsaw", "Gdansk", "Wroclaw", "Krakow", "Lodz", "Katowice"};
Scanner scan = new Scanner(System.in);
System.out.println("What is the name of your city in Poland? ");
String name = scan.nextLine();
for (String n:cities) {
if (n.equalsIgnoreCase(name)) {
System.out.println("You are citizen of Poland from " +name);
System.out.println("Thank your for visiting " +name);
}
else {
System.out.println("You are not from Poland!!!" );
System.out.println("There is not city in Poland called" +name);
}
break;
}
}
}`
Using my code I am trying to tell the user to enter not to enter a string until the user an integer but while running the program it is infinite.
public static void main(String[] args) {
int age = 1;
Utilisateur utilisateur = new Utilisateur();
Scanner u = new Scanner(System.in);
System.out.println("Enter your Name: ");
utilisateur.setNom(u.nextLine());
System.out.println("Enter your Surname: ");
utilisateur.setPrenom(u.nextLine());
System.out.println("Enter your Matricule: ");
utilisateur.setMatricule(u.nextLine());
System.out.println("Enter your Sexe: ");
utilisateur.setSexe(u.nextLine());
do {
try {
System.out.println("Enter your Age: ");
utilisateur.setAge(u.nextInt());
System.out.println(utilisateur.detail());
age = 2;
} catch (Exception e) {
System.out.println("Enter a valid age ");
}
}
while (age == 1);
}
}
Okay, so let's start by cleaning up the code a bit. The whole "age" variable is a bit weird. It seems like it's containing some status on whether or not you've read the age. But that's kind of boolean, isn't it? So let's redo the code with that in mind. I'll change the do-while to a simple while first, but we can change it back afterwards. Furthermore, it might be a good idea to rename "u" to "keyboard", or "clavier" if you prefer french.
public static void main(String[] args) {
Utilisateur utilisateur = new Utilisateur();
Scanner clavier = new Scanner(System.in);
System.out.println("Enter your Name: ");
utilisateur.setNom(clavier.nextLine());
System.out.println("Enter your Surname: ");
utilisateur.setPrenom(clavier.nextLine());
System.out.println("Enter your Matricule: ");
utilisateur.setMatricule(clavier.nextLine());
System.out.println("Enter your Sexe: ");
utilisateur.setSexe(clavier.nextLine());
boolean hasEnteredAge = false;
while(!hasEnteredAge) {
System.out.println("Enter your Age: ");
String ageInput = clavier.nextLine().trim(); // remove leading and trailing whitespace. " 21 " becomes "21".
try {
int age = Integer.parseInt(ageInput);
utilisateur.setAge(age);
System.out.println(utilisateur);
hasEnteredAge = true;
} catch (Exception e) {
System.out.println("Enter a valid age.");
}
}
}
}
Notice that I moved the variable to the beginning of the loop, which is where we need to know about this fact, and how we initialized it to false. We now have to set it to be true afterwards.
But there is a bit more to do here I think. We have a bunch of prints, followed by inputs. Surely, this can be farmed out to a method, that makes this look a bit nicer? But before we do that, we should take another look at the loop. We can do the loop in a multitude of ways. We can do
do {
System.out.println("Enter your Age: ");
String ageInput = clavier.nextLine().trim(); // remove leading and trailing whitespace. " 21 " becomes "21".
try {
int age = Integer.parseInt(ageInput);
utilisateur.setAge(age);
System.out.println(utilisateur);
break; // this means that we should exit the loop
} catch (Exception e) {
System.out.println("Enter a valid age.");
}
}while(true); // So if we ever get here, we're not done.
Here, we're relying on the break to get us out of the loop. This works, but personally I don't like it. It's not a wrong thing to do however, so I'll just leave it in. You can also have it like the old do-while loop:
boolean hasEnteredAge = false;
do {
System.out.println("Enter your Age: ");
String ageInput = clavier.nextLine().trim(); // remove leading and trailing whitespace. " 21 " becomes "21".
try {
int age = Integer.parseInt(ageInput);
utilisateur.setAge(age);
System.out.println(utilisateur);
hasEnteredAge = true;
} catch (Exception e) {
System.out.println("Enter a valid age.");
}
} while (!hasEnteredAge);
Whichever you choose though, it's fine.
Now let me just tackle the issue of the printlines and reads:
If you add a method "prompt" that takes a prompt and returns a string, you can simplify this down quite handily like so:
public class EnterNameHere {
private static Scanner clavier = new Scanner(System.in);
public static String prompt(String prompt) {
System.out.println(prompt);
return clavier.nextLine().trim();
}
// ... The rest is as before.
}
Now, the reading in part becomes very simple:
public static void main(String[] args) {
Utilisateur utilisateur = new Utilisateur();
utilisateur.setNom(prompt("Enter your Name: "));
utilisateur.setPrenom(prompt("Enter your surname: "));
utilisateur.setMatricule(prompt("Enter your matricule: "));
utilisateur.setSexe(prompt("Enter your sex: "));
And an important question arises: If we are to do this for string inputs, why not for integer (int) inputs as well?
I propose:
public static int promptInt(String prompt) {
String value = prompt(prompt);
try {
return Integer.parseInt(value);
} catch(NumberFormatException ignored) {
System.out.println("Invalid number: '" + value + "'");
return promptInt(prompt); // We try again!
}
}
Notice if you would be so kind, that if calling the method promptInt doesn't work, we print an error message and just try again. This will only work for a few hundred times before it all crashes, but that should be enough. (You can of course adapt the while-loop approach from earlier if you don't want that to happen.) This trick of a method or function calling itself multiple times until the work is done is called "recursion" and it is as powerful as looping is. It can be confusing to people who are new to programming, but I think this example is straightforward. If it isn't, you can simply substitute the whole loop thing as mentioned. Of course, there is one method called prompt, and another called promptInt. To avoid any confusion we rename the prompt-method to promptString, and the entire program simply becomes:
public class YourNameHere {
private static final Scanner clavier = new Scanner(System.in);
public static String promptString(String prompt) {
System.out.print(prompt);
return clavier.nextLine().trim();
}
public static int promptInt(String prompt) {
String value = promptString(prompt);
try {
return Integer.parseInt(value);
} catch(NumberFormatException ignored) {
System.out.println("Invalid number: '" + value + "'");
return promptInt(prompt); // We try again!
}
}
public static void main(String[] args) {
Utilisateur utilisateur = new Utilisateur();
utilisateur.setNom(promptString("Enter your Name: "));
utilisateur.setPrenom(promptString("Enter your surname: "));
utilisateur.setMatricule(promptString("Enter your matricule: "));
utilisateur.setSexe(promptString("Enter your sex: "));
utilisateur.setAge(promptInt("Enter your age: "));
System.out.println("You have created an utilisateur: " + utilisateur);
}
}
Plus the definition of Utilisateur of course.
I think this is a much simpler way to do it, by creating methods that does the boring work for you, you can read the code in the main method and immediately understand what is going on. If you need to understand how, you can go up and look at the helping prompt-methods.
You should add u.nextLine(); in catch block in order to skip invalid value entered in the scanner.
Here's my output:
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query:1
Enter Your Student ID:1
Enter Your First Name: Respo
Enter Your Middle Name: Topher
Enter Your Last Name: Raspo
Do you want to back to Query?(Yes/No)
Yes
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query: 4
12
Christopher
Reposo
Porras
1
Respo
Topher
Raspo
As you can see in the picture I'm trying to make a simple little system without database but using ArrayList to contain those data now my problem is in the Delete Query. Now in Delete Query I tell the user to type the student number which is 1 then delete the information of it and its contain which is first name, middle name, last name But I don't have much logic in ArrayList to do such thing. By the way is it possible to use only One ArrayList in this case or I need to make many array list to solve my problem.
public static void main(String[] args) {
//initialize Scanner for input process
Scanner scan = new Scanner(System.in);
//initialize needs variable
List<String> list = new ArrayList<String>();
int choose,chooseQuery;
String chooseYesOrNo = " ";
String chooseYesOrNo2 = " ";
do {
//Startup Program
System.out.println("=====-----LibrarySystem-----=====");
System.out.println("[1]Student Information");
System.out.println("[2]Book Information");
System.out.print("Choose Table:");
choose = scan.nextInt();
do {
if(choose == 1) {
System.out.println("-----Query-----");
System.out.println("[1]Update");
System.out.println("[2]Delete");
System.out.println("[3]Search");
System.out.println("[4]Show");
//reserved
//reserved
System.out.print("Choose Query:");
chooseQuery = scan.nextInt();
if(chooseQuery == 1) {
System.out.print("Enter Your Student ID:");
String id = scan.next();
list.add(id);
System.out.print("Enter Your First Name:");
String name = scan.next();
list.add(name);
System.out.print("Enter Your Middle Name:");
String middle_name = scan.next();
list.add(middle_name);
System.out.print("Enter Your Last Name:");
String last_name = scan.next();
list.add(last_name);
System.out.println("Do you want to back to Query?(Yes/No)");
chooseYesOrNo = scan.next();
} else if (chooseQuery == 2) { //Delete Query
System.out.print("Enter Student ID:");
String find_id = scan.next();
} else if(chooseQuery == 3) { //Search Query
} else if(chooseQuery == 4) { //Show Query
for (String s : list) {
System.out.println(s);
}
}
}
} while(chooseYesOrNo.equals("Yes"));
System.out.println("Do you want to get back at tables?(Yes/No)");
chooseYesOrNo2 = scan.next();
} while(chooseYesOrNo2.equals("Yes"));
System.out.println("-----=====Program Terminated=====-----");
}
Create Student object which contains all the fields you need (student id, name, etc)
class Student {
int studentId;
String firstname;
String middlename;
String lastname;
}
Have one array list for Student objects
java.util.List<Student> list = new java.util.ArrayList<Student>();
When Delete operation is selected, iterate through your list to find the object and remove it. Here's nice blog about ways to iterate through arraylist. My favorite method is as follows:
for (Student std:list) {
if (std.studentId == targetId) {
list.remove(std);
break; //since you've removed target, you can exit the loop
}
}
Why when I run my program and enter 5, it allows me to enter my records, but when the main menu runs again and I enter 6, the changePhoneNumber method is not run and it goes back to the main menu. Is the while(true) loop somehow messing things up?
I have a class called Record that looks like:
public static void main(String[] args) {
BankMethods method = new BankMethods();
Scanner input = new Scanner(System.in);
int optionSelected = 0;
while(true){
System.out.println("5. Add a New Record");
System.out.println("6. Change the Phone Number in the Current Record");
optionSelected = input.nextInt();
if (optionSelected == 5){
Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = getRecord.nextLine();
System.out.println("Enter Last Name: ");
String lastName = getRecord.nextLine();
System.out.println("Enter Phone Number: ");
String phoneNumber = getRecord.nextLine();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6){
System.out.println("What would you like to change your phone "
+ "number to? ");
String newNumber = input.nextLine();
method.changePhoneNumber(newNumber);
}
and the other class...BankMethods:
public class BankMethods {
LinkedList recordInformation = new LinkedList();
Bankdata mainMenu = new Bankdata();
public void addNewRecord(String firstName, String lastName,
String phoneNumber){
recordInformation.add(firstName); recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber){
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
The problem is that you are using 2 Scanners to read the one InputStream. When you open the second Scanner you will not be able to read using the original one as the second will have exclusive access to it.
For this application you could easily use a single Scanner.
See: Do not create multiple buffered wrappers on a single InputStream
The correct way is to use one read(scanner) for a input stream. Edited the previous answer to use single read option
Complete program that works is given below
package com.stackoverflow.framework;
import java.util.LinkedList;
import java.util.Scanner;
public class Record {
static Scanner input = new Scanner(System.in);
public static String readData() {
return (input.nextLine());
}
public static void main(String[] args) {
BankMethods method = new BankMethods();
int optionSelected = 0;
while (true) {
System.out.println("5. Add a New Record");
System.out
.println("6. Change the Phone Number in the Current Record");
optionSelected = Integer.parseInt(readData());
if (optionSelected == 5) {
// Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = readData();
System.out.println("Enter Last Name: ");
String lastName = readData();
System.out.println("Enter Phone Number: ");
String phoneNumber = readData();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6) {
System.out.println("What would you like to change your phone "
+ "number to? ");
// Scanner getRecord = new Scanner(System.in);
String newNumber = readData();
method.changePhoneNumber(newNumber);
}
}
}
}
class BankMethods {
LinkedList recordInformation = new LinkedList();
public void addNewRecord(String firstName, String lastName,
String phoneNumber) {
recordInformation.add(firstName);
recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber) {
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
}
I have recently learned about Setters and Getters. I can use them but the problem is that I have to use them in a loop. Some of the code that I am using is mentioned below.
I am entering Student information in a loop, and then editing it in another loop using Set Get methods. I can use the setter and getter methods without the loop but I am not sure how to use them inside the loop. So please guide me to add students in a stu array.
public static void Addstudents()
{
for(int i=0; i<stu.length; i++)
{
stu[i]=new Stuinfo();
System.out.println("Enter name ");
name= sc.next();
System.out.println("Enter id ");
id= sc.next();
}
}
And to edit the data, I want to run a loop and use the setter method to set the values. Something like this:
public void Modify()
{
String Cid;
System.out.println("You r modifying account");
for (int i=0; i<stu.length;i++)
{
stu[i].setId(id)...// dont know what to do in loop hree
}
}
The question is not clear, I think that to modify a specific account of a single student, you need something like this :
public void Modify() {
String Cid;
System.out.println("Enter your ID :");
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
for (int i=0; i<stu.length;i++)
{
if(id == stu[i].getId()) {
//Change your account details
System.out.println("Enter name ");
name= sc.next();
stu[i].setName(name);
}
}
}
In the example above, you are getting an id as input, and then you are looking up in the array for the input id, and if you find one, you are giving the opportunity to the user to change the account details of that specific user ...
While in the first example you have to set your students instance properties using setters :
public static void Addstudents()
{
for(int i=0; i<stu.length; i++)
{
stu[i]=new Stuinfo();
System.out.println("Enter name ");
stu[i].setName( sc.next() );
System.out.println("Enter id ");
stu[i].setId( sc.next() );
}
}
public void Modify() {
System.out.println("You r modifying account");
Scanner sc = new Scanner(System.in);
for (int i=0; i<stu.length;i++)
{
System.out.println("Enter id");
stu[i].setId(sc.nextInt());
System.out.println("Enter name ");
stu[i].setName(sc.nextLine());
}
}