How to get user input x times and print outside of loop - java

Im creating an easy blood transfusion game. I want to get the names and blood type then print them to the console. My code below does this but I cant print it to the console because the variable is inside the loop. How do I fix this?
for ( int i = 0; i < 26; i++)
{
System.out.println("Type your full
name first: ");
String donor = in.next();
System.out.println("Now type your blood type: ");
String bloodType = in.next();
}

If you will first gather all data and then print it out, you should temporarily store them somewhere. A good choice is string array or ArrayList.
ArrayList<String> names = new ArrayList<>(26); // 26 is the initial capacity
ArrayList<String> bloodTypes = new ArrayList(26);
for (int i = 0; i < 26; i++) {
System.out.println("Type your full name first: ");
String donor = in.next();
names.add(donor);
System.out.println("Now type your blood type: ");
String bloodType = in.next();
bloodTypes.add(bloodType);
}
Now you can iterate over the ArrayLists and print out your stored values:
for (int i = 0; i < names.size(); i++) {
System.out.println("Blood type of " + names.get(i) + " is " + bloodTypes.get(i));
}

Related

Java array linear search always returns "Book is not found"?

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.

asking for a name of each customer with array size in for loop

I'm a beginner and I've been really stuck on this problem. I'm not really sure how I can display the number of customer(in an arraySize) (customer #1, customer #2...) and ask for their name in a for loop.
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + arraySize + ": "
}
I've tried dinerArray.length and then i, arraySize with i, (i=0;i<=arraySize;i++) with arraySize/i.. but nothing seems to work. It would either only print once with customer#0 or print nothing at all
You need to change arraySize to i. That way it will produce customer#1,customer#2 etc....
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + i+ ": ");
}
If you just want to read them from the console, you can use a Scanner:
Scanner input = new Scanner(System.in);
int arraySize = 10;
String[] dinerArray = new String[arraySize];
for(int i = 0; i < arraySize; ++i)
{
System.out.print("Enter the name of customer#" + (i + 1) + ": ");
dinerArray[i] = input.nextLine();
}
input.close();
im no Java dev but this is pretty basic.
The problem is that your for loop is just running if i is equal to arraySize, but this never happen.
So, try to change your '==' to a '<='
My solution:
Scanner scan = new Scanner(System.in);
int arraySize = 5;
String[] dinerArray = new String[arraySize];
for(int i = 1; i <= dinerArray.length; i++) {
ystem.out.print("pleas enter name for customer#" + i);
dinerArray[i - 1] = scan.nextLine();
}
Im not sure about the scanner think.

Filling and sorting parallel arrays from single user input

I have to accept a single user input of a string and an int ten times, separate them at the space into two parallel arrays. I then have to sort them, find average, etc. Everything I have found on parallel arrays has two different inputs for the string and int. How can I separate the single input into the two arrays?
public static void main(String args[]){
//double[] gradeArray = new double[10];
//String[] nameArray = new String[10];
String name = " "; //name substring
String num = " "; //int substring
String s = " "; //input String
int grade = Integer.parseInt(num); //parsing the numerical string to an int
int x = s.indexOf(' '); //index of " " space
name = s.substring(0, x);
num =s.substring(x + 1);
Scanner input = new Scanner(System.in);
int[] gradeArray = new int[10];
String[] nameArray = new String[10];
//looping to gather 10 user inputs
for(int k = 0; k < 10; k++){
System.out.println("Input Student name and grade: ");
s = input.nextLine();
//not sure how to sepearate String s into String name and String num
}
System.out.println("Highest Grade: " + Grades.highestGrade(gradeArray));
System.out.println("Lowest Grade: " + Grades.lowestGrade(gradeArray));
System.out.println("Class Average: " + Grades.classAverage(gradeArray));
for(int i = 0; i < nameArray.length; i++){
System.out.print(nameArray[i] + ", ");
System.out.print(gradeArray[i]);
System.out.println();
// System.out.print(sort());
}
How can I separate the single input into the two arrays?
First, we will use the already declared array of double to store the grades.
double[] gradeArray = new double[10];
Second, we will use the already declared array of String to store the names.
String[] nameArray = new String[10];
Now, going on to the for loop, we can use the String#split() method to separate the name and the grade on the delimiter " " considering that there will be whitespace between the name and grade as you've mentioned.
for(int k = 0; k < 10; k++){
System.out.println("Input Student name and grade: ");
s = input.nextLine();
String[] tempArray = s.split(" ");
nameArray[k] = tempArray[0]; // store name to nameArray
gradeArray[k] = Double.parseDouble(tempArray[1]); // store grade to gradeArray
}

What is wrong? Get no specific error

I want to insert data in a String array. But I get the error, that the code was suspended (for example in in this part: System.out.println("What is the name of the table? ");
But why?
Here is the rest of the code.
static Scanner input = new Scanner(System.in);
private static String tabName = "";
private static int tabSpaltenAnz = 0;
private static String[] spaltenName = new String[tabSpaltenAnz];
public static void abfrageTabellenInformationen() {
System.out.println("What is the name of the table? ");
tabName = input.nextLine();
System.out.println("How many columns?");
tabSpaltenAnz = input.nextInt();
for(int i = 1; i <= tabSpaltenAnz; i++) {
int k = 0;
System.out.println("Insert name, data type and constraint for the " +
i + ". column.");
String eingabeSpaltenAnz = input.nextLine();
spaltenName[k] = eingabeSpaltenAnz;
k++;
}
}
The array spaltenName is always going to be size 0. You should put spaltenName = new String[tabSpaltenAnz]; after tabSpaltenAnz = input.nextInt(); in the method.
You also do not need the variable k. You can replace k with i, start i at 0 in the for loop and make your output statement System.out.println("Insert name, data type and constraint for the " + i+1 + ". column.");

Print a value from 2d array in Java

I am working on a program that allows a user to add values to a 2d array and then search the array and display the value. The information is being stored properly, but all I can get to display is the animal name and not the food. Before I get grilled I've searched and implemented a bunch of different methods trying to get the correct output. I'm sure my error is pretty simple if someone could just help me understand, thanks!
/*This program will allow a user to enter information into the zoo
or search by animal for the type of food it eats*/
import java.util.Scanner;
class zoo {
//create array
static String[][] animalFood;
String[][] addArray(int x) {
animalFood = new String[x][2];
Scanner in = new Scanner(System.in);
//loop through array and add amount of items user chose
for (int row = 0; row < animalFood.length; row++){
System.out.print("Enter an animal name: ");
animalFood[row][0] = in.nextLine();
System.out.print("Enter the food the animal eats: ");
animalFood[row][1] = in.nextLine();
}
System.out.println("Thank you for adding information to the zoo!");
System.out.println("You entered the following information: ");
//loop through and print the informationa added
for(int i = 0; i < animalFood.length; i++)
{
for(int j = 0; j < animalFood[i].length; j++)
{
System.out.print(animalFood[i][j]);
if(j < animalFood[i].length - 1) System.out.print(" - ");
}
System.out.println();
}
//prompt the user to search or quit
System.out.println("Please enter the name of the animal to search for or Q to quit: ");
String animalName = in.nextLine();
animalName = animalName.toUpperCase();
if(animalName.equals("Q")){
System.out.println("Thanks for using the program!");
}
else {
searchArray(animalName);
}
return animalFood;
}
String[][] searchArray(String name) {
String matchResult = "There was no " + name + " found in the zoo!";
String itemToMatch = name.toUpperCase();
String arrayItem = "";
String food = "";
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
arrayItem = animalFood[i][j];
arrayItem = arrayItem.toUpperCase();
if(arrayItem.equals(itemToMatch)){
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
}
else {
//nothing found
}
}
}
System.out.println(matchResult);
if (food != null) {
System.out.println(food);
}
return animalFood;
}
//constructor
public zoo() {
}
//overloaded constructor
public zoo(int x) {
int number = x;
animalFood = addArray(x);
}
//method to get users choice
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
System.out.println("Please make a choice in the menu below");
System.out.println("-------------------------\n");
System.out.println("1 - Add animals and the food they eat.");
System.out.println("2 - Search for an animal in the zoo.");
System.out.println("3 - Exit the program");
selection = input.nextInt();
return selection;
}
//main method
public static void main(String[] args) {
//create a new object
zoo myZoo = new zoo();
//variables and scanner
int userChoice;
int numberAnimals;
String animalName = "";
Scanner input = new Scanner(System.in);
//call the menu
userChoice = menu();
//actions based on user choice
if (userChoice == 1) {
System.out.println("How many animals would you like to enter information for?");
numberAnimals = input.nextInt();
myZoo.addArray(numberAnimals);
}
if (userChoice == 2) {
System.out.println("Please enter the name of the animal to search for: ");
animalName = input.nextLine();
myZoo.searchArray(animalName);
}
if (userChoice == 3) {
System.out.println("Thank you for using the program!");
}
}
}
It looks to me like your problem is in searchArray. Your nested for loops are iterating over the size of only one dimension of the array:
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
...
}
}
Replace animalFood.length with animalFood[i].length, like you did correctly in the addArray method.
EDIT
It also looks like your output method is incorrect.
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
In this line, animalFood[j] should be animalFood[i][j]. The strange output you're seeing is Java's attempt at converting an array into a String.
2nd Edit
After examining the addArray method, it seems I've made an incorrect assumption about your array. It appears your array is structured such that each index has 2 items, the animal, and its food. So it looks like so:
animalFood[0][0] = 'Cat'
animalFood[0][1] = 'Cat food'
animalFood[1][0] = 'Dog'
animalFood[1][1] = 'Dog food'
etc.
If this is the case, then you're going to want to change your loop to only iterate over the outer index. This means removing the inner for loop inside of searchArray. Then, you're only going to compare the first index of the inner array to the item you want to match, and if there's a match, then the food will be the second index. I'll leave implementation up to you (since this looks like a homework question). If something I've said here sounds wrong, let me know.

Categories

Resources