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!
Related
The thing i'm hoping to do is read a csv file with 6 rows and 6 columns in it using Java. I then need to print out each row and allow the user to select 1 option. Here is what I have, I know my code chooses 1 and prints it, but I don't know how to change it from printing one random row, to printing all 6 rows. Probably in an ArrayList or 2dArray?
package theContest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;
public class theContest {
// The main() method
public static void main(String[] args) throws FileNotFoundException {
//
String fileName = "contest.csv";
File file = new File(fileName);
if (!file.isFile()) {
System.err.println("Cannot open file: " + fileName + ".");
System.exit(0);
}
//
int numContest = 0;
Scanner input = new Scanner(file);
while (input.hasNext()) {
input.nextLine();
numContest++;
}
input.close();
System.out.println("Total of " + numContest + " contestants.");
//
int winner = 0;
Random random = new Random();
winner = random.nextInt(numContest) + 1;
System.out.println("The winner is contestant number " + winner + ".");
//
String winnerDetails = "";
input = new Scanner(file);
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
input.close();
System.out.println("Winner is: " + winnerDetails);
//
String id = "";
String name = "";
String seats = "";
String trans = "";
String rate = "";
String price = "";
input = new Scanner(winnerDetails);
input.useDelimiter(",");
id = input.next();
name = input.next();
seats = input.next();
trans = input.next();
rate = input.next();
price = input.next();
input.close();
System.out.println("Details are:");
System.out.printf("%-5s : %s\n", "ID", id);
System.out.printf("%-5s : %s\n", "Name", name);
System.out.printf("%-5s : %s\n", "Seating", seats};
System.out.printf("%-5s : %s\n", "Transfer", trans};
System.out.printf("%-5s : %s\n", "Rate", rate};
System.out.printf("%-5s : %s\n", "Price", price};
}
}
Here:
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
Your file has N rows. The above code iterates all lines, and stores the result in a single variable. In each iteration, you overwrite what you put there before. So, what your code does is: it reads N lines, and throws away everything prior the last row.
In other words: if you have 6 lines, and you want to print all of them ... then that all your processing needs to be "part" of a loop, too.
For example, you could turn winnerDetails into an array of String, and then put each line in its own slot. Then you loop over the array, and print each slot.
And as you already know about ArrayList, best use that then. That also means: you need to read the file only once. Open the file, read each line, and push that into an ArrayList. Afterwards, you can do whatever you want with that list.
And note: that is actually the point you should start with. Dont solve your whole problem at once. Slice it into smaller parts. Like: reading data from CSV ... has nothing to do with later processing the lines and printing those. You can write code that just takes an ArrayList, processes those and prints stuff. Which you can ... test on its own, as you can hardcode such lists in your code.
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
I have tried putting two user inputs but can't seem to find a way to exit this loop after conducting a binary search to find an item in an array list. I need this to return a string to use the input as the name for my game. This is what I have got so far:
public String chooseBird() { //bird chosen will be depending on user input and binary search
String chosenBird = "";
String[] tempArr = new String[myBirdList.size()];//breks birds into array list string
tempArr = myBirdList.toArray(tempArr);
String selectBird ;
System.out.println("Enter the bird you wish to use for the adventure: ");
Scanner mySearch = new Scanner(System.in); //assign my search as
selectBird = mySearch.nextLine();
System.out.println("Hit 'begin' to start or 'end' to stop");
Scanner myInput = new Scanner(System.in);
String myValue = "";
int result = binarySearch(tempArr, selectBird);
do{
myValue = myInput.nextLine();
if (result == -1) {
System.out.println("We could not find this bird, please enter a bird from the list above");
}
else {
chosenBird = selectBird; //chosenBird is assigned as the return value to assign as the game name
System.out.println("\n" + selectBird + " was chosen and found at index " + result); //bird has been found in the list and selected for the adventure
}
} while (!myValue.contains("end") || result != -1); //keep prompting for input until we find a bird, bird found when result does not = -1
return chosenBird;
}
you need to use break statement for this:
chosenBird = selectBird; //chosenBird is assigned as the return value to assign as the game name
System.out.println("\n" + selectBird + " was chosen and found at index " + result); //bird has been found in the list and selected for the adventure
break;
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.
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;