Resetting array back to array[0] in a while loop java - java

I am trying to get my while loop always reset to array[0]. I am trying to make it so that I can say what my favorite class is, and if need be change my mind after I have chosen the first one. Currently the code only lets me output array[0] then [1] then [2] or [2] > [3] or [1] > [3] but not [2] > [1] or [3] > [1]. Thanks. I am using Java. edit** If it wasn't clear I am talking about the second while loop.
import java.util.*;
public class Hobby1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numClass;
int a;
int b;
String j;
System.out.println("How many classes");
numClass = scan.nextInt();
j = scan.nextLine();
String[] Class = new String[numClass];
a = 0;
while (a < numClass) {
System.out.println("What is class " + a + "?");
Class[a] = scan.nextLine();
a++;
}
System.out.println("Which class is most important");
String input = scan.nextLine();
b = 0;
boolean be = true;
while (be == true) {
if (input.contains(Class[b])) {
System.out.println("The class " + Class[b] + " is most important");
input = scan.nextLine();
}
b++;
}
}
}

You have few problems here:
while (be == true) - you can just use while (be) // be is boolean
you never put be = false;, so you will have an infinite loop
how you iterate the array Class to compare to each value of it? you just check once in increment order b, you need to loop all array not only the current element on b
Ex:
for(String currentClass: Class){
if (currentClass.equals(input)) {
System.out.println("The class " + currentClass + " is most important");
}
}
Check this and try to fix your code.

Related

Using variables outside while loops in java

I'am trying to write a program in Java that collects users favorite names within an array and then prints these names at the end.
NOTE: the length of the array should be defined by the number of names a user enters.
Please take a look at the code and tell me how to fix it. Here is what I have done so far
Scanner input = new Scanner(System.in);
System.out.println("What are your most favorite names?");
String[] favNames = new String[i];
int i = 1;
while (true){
System.out.print("Please enter favorite name number" + i + ": ");
favNames[i-1] = input.next();
System.out.print("Is that all?");
String ans = input.next().toLowerCase();
if(ans.startsWith("y")){
System.out.print("Here is the completed list of your favorite names:\n" + Arrays.toString(favNames));
break;
}
i++;
}
This is the error code I get:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: variable i
location: class JavaApplication13
at JavaApplication13.main(JavaApplication13.java:52)
Java Result: 1
I tried moving the first parts of the code inside the loop but it only prints one of the names the user enters.
//These parts:
String[] favNames = new String[i];
int i = 1;
If I swap the places between the first and second line. The array gets only 1 entry from the user.
//Only gets one entry
int i = 1;
String[] favNames = new String[i];
Variables should be declared before use. This is why your program is not working.
Change
String[] favNames = new String[i];
int i = 1;
To
int i = 1;
String[] favNames = new String[i];
But, keep in mind that in this case the used can only input 1 time(because arrays have fixed size). If you want to use an arbitrary number of input, you have to use ArrayList or similar types.
declare variables before using them:
int i = 1;
String[] favNames = new String[i];
However, an array of size 1, will only work for 1 entry. If you would like the user to be able to enter more than that you need a bigger array.
I would suggest an arbitrarily large size (say 100), then check that the entry fits in the array; if it doesn't, game over.
String[] favNames = new String[100];
int i = 1;
while (true) {
System.out.print("Please enter favorite name number" + i + ": ");
favNames[i - 1] = input.next();
System.out.print("Is that all?");
String ans = input.next().toLowerCase();
if (ans.startsWith("y")) {
System.out.print("Here is the completed list of your favorite names:\n" + Arrays.toString(favNames));
break;
}
i++;
if (i > favNames.length)
System.out.print("Can't accept more than "+favNames.length+" entries, here is the completed list of your favorite names:\n" + Arrays.toString(favNames));
}
The issue then is that Arrays.toString will print null for the empty entries.
I would make a custom routine to print the array that ends on the first null:
static String printFavNames(String[] favNames) {
String output = "[";
for (String s : favNames) {
if (s==null)
break;
if (output.length() > 1)
output += ", ";
output += s;
}
output += "]";
return output;
}
related question: How to print all non null elements of an array using Array.toString()
full code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What are your most favorite names?");
String[] favNames = new String[100];
int i = 1;
while (true) {
System.out.print("Please enter favorite name number" + i + ": ");
favNames[i - 1] = input.next();
System.out.print("Is that all?");
String ans = input.next().toLowerCase();
if (ans.startsWith("y")) {
System.out.print("Here is the completed list of your favorite names:\n" + printFavNames(favNames));
break;
}
i++;
if (i > favNames.length)
System.out.print("Can't accept more than "+favNames.length+" entries, here is the completed list of your favorite names:\n" + printFavNames(favNames));
}
input.close();
}
static String printFavNames(String[] favNames) {
String output = "[";
for (String s : favNames) {
if (s==null)
break;
if (output.length() > 1)
output += ", ";
output += s;
}
output += "]";
return output;
}
}
Just move the i++ to inside the while loop and all be good!

Replacing Position in Array Amongst Other Methods

Firstly - I thank anyone who takes the time to actually look at this since I feel like it's a rather annoying request.
I just completed a large challenge at the end of a series of Java 101 videos. The challenge is to design a guest list method ( as in for a restaurant or a party ) and some features along with it. This is really the first time I've written anything with multiple methods.
As the final step in this challenge, I need to design a method that allows the user to insert a new guest at a certain position while not removing any other guests. In other words, inserting a new guest and shifting the remaining guests downwards by a single index.
The issue I have is that the new guest is always inserted not only for the position I want, but also the position one after. It inserts itself twice and ends up over-writing the previous guest in the process.
import java.util.Scanner;
import java.io.*;
import java.lang.*;
import java.util.*;
public class GuestList_Edited {
public static void main(String[] args) {
// Setup for array, setup for scanner
String[] guests = new String[11];
Scanner scanner = new Scanner(System.in);
// A method to put these here so we don't always have to add guests. This method automatically inserts five guests into the guest list.
InsertNames(guests);
// Do-while loop to make sure that this menu screen shows up every time asking us what we want to do.
// It also makes certain that the menu shows up when we initially run the program.
do {
displayMenu(guests);
// This must remain in main for the rest of the program to reference it.
int option = getOption();
// If loop that will allow people to add guests
if (option == 1) {
addGuest(guests);
} else if (option == 2) {
RemoveGuest(guests);
} else if (option == 3) {
RenameGuest(guests);
} else if (option == 4) {
insertGuest(guests);
} else if (option == 5) {
System.out.println("Exiting...");
break;
}
} while (true);
}
// This displays the starting menu
public static void displayMenu(String SentArr[]) {
System.out.println("-------------");
System.out.println(" - Guests & Menu - ");
System.out.println();
GuestsMethod(SentArr); // Makes all null values equal to --
System.out.println();
System.out.println("1 - Add Guest");
System.out.println("2 - Remove Guest");
System.out.println("3 - Rename guest");
System.out.println("4 - Insert new guest at certain position");
System.out.println("5 - Exit");
System.out.println();
}
// This prints all the guests on the guest list and also adjusts the guest list when a guest is removed
public static void GuestsMethod(String RecievedArr[]) {
// If loop which prints out all guests on the list.
// "Null" will be printed out for all empty slots.
for (int i = 0; i < RecievedArr.length - 1; i++) {
// Make all null values and values after the first null value shift up in the array.
if (RecievedArr[i] == null) {
RecievedArr[i] = RecievedArr[i + 1];
RecievedArr[i + 1] = null;
}
// Make all null's equal to a string value.
if (RecievedArr[i] == null) {
RecievedArr[i] = " ";
}
// If values are not equal to a blank string value, assign a number.
if (RecievedArr[i] != " ") {
System.out.println((i + 1) + ". " + RecievedArr[i]);
}
// If the first value is a blank string value, then print the provided line.
if (RecievedArr[0] == " ") {
System.out.println("The guest list is empty.");
break;
}
}
}
// I've really got no idea what this does or why I need a method but the course I'm taking said to create a method for this.
// It gets the desired option from the user, as in to add a guest, remove a guest, etc.
static int getOption() {
Scanner scanner = new Scanner(System.in);
System.out.print("Option: ");
int Option = scanner.nextInt();
return Option;
}
// Allows users to add guests
public static String[] addGuest(String AddArr[]) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < AddArr.length; i++) {
// The below if statement allows the program to only ask for a name when a given space is "null", meaning empty.
if (AddArr[i] == " ") {
// so the loop runs until it hits a null value.
System.out.print("Name: ");
AddArr[i] = scanner.nextLine();
// Then that same value which was null will be replaced by the user's input
break;
}
}
return AddArr;
}
public static String[] RemoveGuest(String RemoveArr[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RemoveArr.length; i++) {
if (RemoveArr[number] != null) {
RemoveArr[number] = null;
break;
}
}
return RemoveArr;
}
// This inserts names into the array so we don't have to add guests everytime.
public static String[] InsertNames(String InsertNames[]) {
InsertNames[0] = "Jacob";
InsertNames[1] = "Edward";
InsertNames[2] = "Rose";
InsertNames[3] = "Molly";
InsertNames[4] = "Christopher";
// guests[5] = "Daniel";
// guests[6] = "Timblomothy";
// guests[7] = "Sablantha";
// guests[8] = "Tagranthra";
return InsertNames;
}
public static String[] RenameGuest(String RenamedGuests[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RenamedGuests.length; i++) {
if (RenamedGuests[number] != null) {
RenamedGuests[number] = null;
System.out.println("What would you like the guest's name to be?");
String NewName = scanner.next();
RenamedGuests[number] = NewName;
break;
}
}
return RenamedGuests;
}
// The final method which I am struggling with.
public static String[] insertGuest(String NewPositionArray[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int num = scanner.nextInt();
scanner.nextLine();
if (num >= 1 && num <= 10 && NewPositionArray[num - 1] != null)
System.out.print("Name: ");
String name = scanner.nextLine();
for (int i = 10; i > num - 1; i--) {
NewPositionArray[i] = NewPositionArray[i - 1];
NewPositionArray[num - 1] = name;
}
if (num < 0 || num > 10) {
System.out.println("\nError: There is no guest with that number.");
}
return NewPositionArray;
}
}
Once again, thanks. I realize I've probably done 1000 things wrong here. I appreciate your consideration.
I recommend you to declare ArrayList object instead of the normal array declaration; to avoid heavy work on the code where you can add an element into the ArrayList object with predefined add(int position, an element with your data type) method in a specific position and the ArrayList automatically will shift the rest elements to the right of it.
and for several reasons.
for more info about ArrayList in Java, please look at: -
Array vs ArrayList in Java
Which is faster amongst an Array and an ArrayList?
Here an example of add() method; which inserts the element in a specific position: -
Java.util.ArrayList.add() Method

Searching String trouble in single array for java

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.

Java iterate through array [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am trying to write a java program with 2 arrays 1 for name (String) and the other representing age (integer) the program should iterate and ask for a max of 10 names and ages of each, then display all array items as well as max and min ages of each, or unless the user enters 'done' or 'DONE' mid-way through.
I have the following code although struggling to loop around and ask user for names and ages x10.
Any suggestions?
Thank you.
import java.util.Scanner;
public class AgeName {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int numTried = 1;
int ageTried = 1;
boolean stop = false;
String name = "";
String[] num = new String[10];
int[] age = new int[10];
while(numTried <= 10 && ageTried <=10 && !stop){
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
if(name.toUpperCase().equals("DONE")){
stop = true;
}else{
num[numTried - 1] = name;
age[ageTried -1] = userAge;
}
numTried ++;
ageTried ++;
}
for(String output : num){
if(!(output == null)){
System.out.print(output + "," );
}
}
input.close();
}
}
You can use a Map<String,Integer>:
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] num = new String[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
num[i] = name;
map.put(name, userAge);
}
for (String output : num) {
if (!(output == null)) {
System.out.print(output + ","+ map.get(output));
}
}
Map as its name suggests allows you to map one object type to another. the .put() method adds a record that contains a pair of String and an integer and maps the string to the int. The String has to be UNIQUE!!
You should ask in any iteration if the user is done. For example you could set a string variable as answer = "NO", and ask the user at the end of any iteration if he is done. If you try this remember to replace stop variable with answer at your iteration block condition.
System.out.println("Are you done: Choose -> YES or NO?");
answer = input.nextLine();
if (answer == "YES")
break;

How do I sort an array ignoring capitalization?

I use sort() to sort my array alphabetically, but it does so from A-Z to a-z. I try to capitalize each word beforehand, but it doesn't work unless it's being printed out, which should be happening after the sorting. At the moment, with this code, it will list the pupils with capital letters, but if it was inputted as lowercase, it will be sorted as lowercase. Putting the capitalize() in the initial for loop, right after assigning the input to the array, doesn't work. Any solutions?
import java.util.Scanner;
import java.util.Arrays;
public class Pupils {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean loop = true;
int names = 0;
String[] ay = new String[1000];
for(int i = 0; loop == true; i++) {
System.out.println("Enter name: ");
ay[i] = scan.nextLine();
names++;
if (ay[i].equals("0")) {
loop = false;
ay[i] = " ";
}
}
String[] aay = new String[names - 1];
for(int i = 0; i < aay.length; i++) {
aay[i] = ay[i];
}
if (names == 1) {
System.out.print("There are no people in our class.");
} else if (names == 2) {
System.out.print("The person in our class is ");
} else {
System.out.print("The people in our class are ");
}
Arrays.sort(aay);
for(int i = 0; i < names - 1; i++) {
if(i == names - 2) {
System.out.print(capitalize(aay[i]) + ".");
} else if (i == names - 3) {
System.out.print(capitalize(aay[i]) + " and ");
} else {
System.out.print(capitalize(aay[i]) + ", ");
}
}
}
public static String capitalize(String line)
{
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
}
What about using Arrays.sort() with a Comparator? Note that there is a suitable comparator defined in String, so:
Arrays.sort(aay, String.CASE_INSENSITIVE_ORDER);
should do the job.
I suggest storing all the data in the array in lowercase. It will simplify sorting as well as search (if you search for a student in the array, and it was entered as, say "Walter" and you are looking for "walter", you won't find it. If you use lowercase both for storage and for search, it will work).
And since you capitalize the names for printing anyway, the names will still be displayed capitalized.
So instead of doing
ay[i] = scan.nextLine();
You can do:
ay[i] = scan.nextLine().toLowerCase();

Categories

Resources