I'm making a program where a user enters how many inputs the user wants. Example if the user enter's 3, then 3 user inputs will appear. The output of this program goes something like this:
----------------------------------
Enter How Many Inputs: 3
enter name:
rendell //value to be outputted
enter age:
20 //value to be outputted
enter gender:
male //value to be outputted
-----------------------------------
Now, I want to store those entered values somewhere to be outputted separately after but I have no idea how to do it. I tried to use the ctr1 variable but it only outputs the value of the last user input.
Here is my code:
Object stud1 [][] = {{1,2,3},{"enter name:","enter age:","enter gender:"}};
String ctr1;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
for (int i = 0; i<num1;i++){
System.out.println(pers[1][i]);
ctr1 = in.readLine();
}
The problem is that you are only assigning all the input in one reference to the String thus you can print all the input the user just gave.
solution:
You can use an array of String to put all the values from the inputted data if the user
sample:
String [] choices = { "enter name:","enter age:","enter gender:"};
String ctr1[];
Scanner scan = new Scanner(System.in);
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(scan.nextLine());
ctr1 = new String[num1];
for (int i = 0; i < num1; i++) {
System.out.println(choices[i]);
ctr1[i] = scan.nextLine();
}
for(int i = 0; i < ctr1.length; i++)
{
if(i == 0)
System.out.println("Name: "+ ctr1[i]);
else if( i == 1)
System.out.println("Age: "+ ctr1[i]);
else if( i == 2)
System.out.println("Gender: "+ ctr1[i]);
}
result:
Enter How Many Inputs: 3
enter name:
Rod_algonquin
enter age:
12
enter gender:
male
Name: Rod_algonquin
Age: 12
Gender: male
Related
I write 2 ArrayList type String contains the days and possible times , and I want the user to enter input , then check if the input is not from the array it will show a message that the input is invalid and the user enter again . but the result to my code give me the opposite :( when I enter something outside the array it will accept it
what's wrong with my code??
and please show me the right code :(
package javaapplication19;
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> dayArray = new ArrayList<>();
ArrayList<String> timeArray = new ArrayList<>();
dayArray.add("sunday");
dayArray.add("monday");
dayArray.add("tuesday");
dayArray.add("wednesday");
dayArray.add("thursday");
timeArray.add("8am");
timeArray.add("9am");
timeArray.add("10am");
timeArray.add("11am");
timeArray.add("12pm");
timeArray.add("1pm");
timeArray.add("2pm");
timeArray.add("3pm");
timeArray.add("4pm");
System.out.println("please enter day :");
String a1 = input.nextLine();
for (int g = 0; g < dayArray.size(); g++){
if (dayArray.get(g).equals(a1))
System.out.println("invalid day , please enter another day : ");
a1 = input.nextLine();
}
System.out.println("please enter time : ");
String a2 = input.nextLine();
for (int s = 0; s < timeArray.size(); s++) {
if (timeArray.get(s).equals(a2))
System.out.println("invalid time , please enter another time : ");
a2 = input.nextLine();
}
}
}
You can use below code and find change in if condition.
System.out.println("please enter time : ");
String a2 = input.nextLine();
for (int s = 0; s < timeArray.size(); s++) {
if (!timeArray.get(s).equals(a2))
System.out.println("invalid time , please enter another time : ");
a2 = input.nextLine();
}
You can do it like this :
String a1 = input.nextLine();
if (!dayArray.contains(a1))
System.out.println("invalid day , please enter another day : ");
else {
System.out.println("day really nice day");
}
There is no need to iterate over the array. The method contains() does it for you
your code should be like this.
System.out.println("please enter day :");
boolean validDate = false;
while(!validDate){
String a1 = input.nextLine();
if(dayArray.contains(a1)){
System.out.println("invalid day , please enter another day : ");
}else{
validDate=true;
}
}
boolean validHour = false;
System.out.println("please enter a time : ");
while(!validHour){
String a2 = input.nextLine();
if(timeArray.contains(a2)){
System.out.println("invalid time , please enter another time : ");
}else{
validHour=true;
}
}
I did refactor your code and put some comments to easier to follow
Scanner input = new Scanner(System.in);
List<String> dayArray = Arrays.asList("sunday","monday","tuesday","wednesday","thursday");
List<String> timeArray = Arrays.asList("8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm");
String a1 = "";
String a2 = ""; //Store user input
boolean nextInput = false; // flag indicate we continue or we force user re-enter information
//try to read the day input
while (!nextInput) {
System.out.println("please enter day :");
a1 = input.nextLine();
nextInput = dayArray.contains(a1);
}
//try to read the time input
nextInput = false; //<= reset flag
while(!nextInput) {
System.out.println("please enter time : ");
a2 = input.nextLine();
nextInput = timeArray.contains(a2);
}
System.out.println("day :" + a1);
System.out.println("time :" + a2);
System.out.println("program finished");
input.close(); //close scanner
write like this
System.out.println("please enter day :");
String a1 = input.nextLine();
while (!dayArray.contains(a1)){
System.out.println("invalid day , please enter another day : ");
a1 = input.nextLine();
}
System.out.println("please enter time : ");
String a2 = input.nextLine();
while (!timeArray.contains(a2)){
System.out.println("invalid time , please enter another time : ");
a2 = input.nextLine();
}
I've been working on the following assignment:
This program should create an ArrayList called Book List. The program
should display a menu to allow the user to choose from the following options:
Enter 1 to add a book to the list:
Enter 2 to edit a book to the list:
Enter 3 to remove a book from the list:
Enter 4 to display the list of books:
Enter 5 to quit:
The program should use a case/switch statement and switch on the users choice. The program should continue until the user enters 5 to quit.
Case 1 should use BookList.add to add books to the ArrayList.
Case 2 should use BookList.set to edit books to the ArrayList.
Case 3 should use BookList.remove to remove a name from the list (Ask the user to enter the index number of the book to delete from ArrayList).
Case 4 should use a for loop to display all books in the ArrayList
along with their index number.
(Sample output) Your output should look similar to:
**********The Book List*********
Index: 0 Name: Stranger in a Strange Land
Index: 1 Name: PHP and MySQL
Index: 2 Name: HTML & CSS
Index: 3 Name: Love Story
Index: 4 Name: The Day the Earth Stood Still
I am having trouble with ArrayList.set. I can not figure out how to take user input (the index number and the corrected book title) to update the array list. That's not the end of my issues with this program, but any help on ArrayList.set would be greatly appreciated.
import java.util.ArrayList;
import java.util.Scanner;
public class BookList {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//Create array
ArrayList<String> bookList = new ArrayList<String>();
//Add a few books to the array bookList
bookList.add("A Game of Thrones");
bookList.add("A Clash of Kings");
bookList.add("A Storm of Swords");
bookList.add("A Feast for Crows");
bookList.add("A Dance with Dragons");
//Display the items in bookList array and their indices.
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
System.out.print("\n");
//declaring variables
int menuID = 0;
int changeIndex = 0;
int delIndex = 0;
String addTitle = "";
String corrTitle = "";
//Menu
System.out.println("Enter 1 to add a book to the list");
System.out.println("Enter 2 to edit a book in the list");
System.out.println("Enter 3 to remove a book from the list");
System.out.println("Enter 4 display the list of books");
System.out.println("Enter 5 to quit");
System.out.println("Enter a menu number (1-4 or 5 to Exit): ");
menuID = input.nextInt();
while (menuID != 0)
{
if (menuID >=1 && menuID <= 4)
{
switch (menuID)
{
case 1:
System.out.println("Enter the book to add: ");
addTitle = keyboard.nextLine();
bookList.add(addTitle);
System.out.print("\n");
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
break;
case 2:
System.out.println("Enter index number of the book to change: ");
changeIndex = keyboard.nextInt();
System.out.println("Enter the corrected book name: ");
corrTitle = keyboard.nextLine();
bookList.set(changeIndex, corrTitle);
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
break;
case 3:
System.out.println("Enter index number of the book to remove: ");
delIndex = keyboard.nextInt();
bookList.remove(delIndex);
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
break;
case 4:
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
break;
case 5:
System.out.println("Goodbye!");
break;
}}
else if (menuID >=1 && menuID <= 4)
System.out.println("You must enter a number 1-5:");
System.out.println("Enter a menu number (1-4 or 5 to Exit): ");
menuID = input.nextInt();
}
}
}
You should be using only one Scanner object with the same source, unless you had a really complicated way to traverse the input, which probably isn't the case here. So your code should look something like this:
// Scanner keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
// ...
menuID = input.nextInt();
while (menuID != 0)
{
if (menuID >=1 && menuID <= 4)
{
switch (menuID)
{
case 1:
// ...
addTitle = input.nextLine();
// ...
Now, there's another issue because you're calling Scanner.nextInt, which gets you the next integer, but won't consume the rest of the line after taking the integer, so when you call Scanner.nextLine it will get you the rest of that previous line instead of the new line you're expecting. To fix that, you could call a dummy Scanner.nextLine after each Scanner.nextInt, like this:
menuID = input.nextInt();
input.nextLine(); // Consumes the rest of the line
Or you could get the whole line every time and parse the integer it contains, using Integer.parseInt, like this:
menuID = Integer.parseInt(input.nextLine());
Here's the working code using the second option (which I find better for this case)
As a side note, you're asking the user to exit with 5, but your while depends continues as long as the menuID is not 0
I am suppose to make a one dimensional array until the user enters "alldone", however i dont know how to make it . This what i have and i know it is wrong .
The instruction are "Design a solution that requests and receives student names and an exam score for each. Use one-dimensional arrays to solve this.
The program should continue to accept names and scores until the user inputs a student whose name is “alldone”.
After the inputs are complete determine which student has the highest score and display that student’s name and score.
Finally sort the list of names and corresponding scores in ascending order."
Code so far:
String name = "";
String highName = "";
int highScore = 0;
while (name != "alldone") {
System.out.println("Enter name of student");
name = input.nextLine();
System.out.println("Enter grade of student.");
int score = input.nextInt();
if (name != "alldone" && score > highScore)
highName = name;
highScore = score;
// System.out.println("Enter name"); name = input.nextLine(); }
// System.out.println(highName + " had the highest score which was "
// + highScore);
}
now i have done this
Scanner in = new Scanner(System.in);
int size= 1;
String[] studentNames= new String[size];
System.out.println("Enter name of student");
String input = in.nextLine();
String name = input;
if (!name.equals("alldone")) {
for (int i = 0; i < size; i++)
studentNames[i]= in.nextLine();
}
else return;
for (int k = 0; k<studentNames.length; k++) {
System.out.println(studentNames[k] + " "); //so it can display names
you should use this instead:
if (!name.equals("alldone"))
im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}
I am really a novice at Java but I'm giving it a shot with this program. This is a program to perform basic mathematical calculations, but with input from user.
import java.io.*;
import java.util.Scanner;
public class Math
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
int sa1, sa2, ss1, ss2, sm1, sm2, s;
boolean c = false;
double sd1, sd2;
while(c==false)
{
System.out.print("Do you want to: \n[1] Add. \n[2] Subtract. \n[3] Multiply. \n[4] Divide. \n[5] Exit \nPlease insert an option number below and press enter: ");
s = in.nextInt();
if (s==1)
{
System.out.print("You have chosen option 1 \nPlease enter your first number: ");
sa1 = in.nextInt();
System.out.print("Please enter your second number: ");
sa2 = in.nextInt();
System.out.print(sa1+ " + " +sa2+ " = " +(sa1+sa2));
}
if (s==2)
{
System.out.print("You have chosen option 2 \nPlease enter your first number: ");
ss1 = in.nextInt();
System.out.print("Please enter your second number: ");
ss2 = in.nextInt();
System.out.println(ss1+ " - " +ss2+ " = " +(ss1-ss2));
}
if (s==3)
{
System.out.print("You have chosen option 3 \nPlease enter your first number: ");
sm1 = in.nextInt();
System.out.print("Please enter your second number: ");
sm2 = in.nextInt();
System.out.println(sm1+ " x " +sm2+ " = " +(sm1*sm2));
}
if (s==4)
{
System.out.print("You have chosen option 4 \nPlease enter your first number: ");
sd1 = in.nextDouble();
System.out.print("Please enter your second number: ");
sd2 = in.nextDouble();
System.out.println(sd1+ " divided by " +sd2+ " = " +(sd1/sd2));
}
if(s>=6)
{
System.out.println("You have entered an incorrect option");
}
System.out.print("Would you like to try again? (Y/N): ");
String ans = in.nextLine();//prob with this line
char ans1 = ans.charAt(0);//or this line
if (ans1=='N' || ans1=='n')
{
c = true;
}
if(s==5)
{
c = true;
}
}
}
}
When I complile it I get an error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Math.main(Math.java:58)
I've tried searching everywhere for an answer. Can anyone help me with this? It needs to be able to read either a 'Y' or a 'N' from the user.
You get the exception when you run it. Not when you compile it. And the error message says:
you're trying to get the char at index 0 of a string, but the String has no index 0. This exception happens at line 58 of Main.java.
A String which doesn't have a char at index 0 is an empty string.
This probably happens because the last thing you read from SYstem.in() is a number, and reading a number doesn't consume the end-of-line that comes after. Add a call to readLine() before reading Yes or No from the user. And don't assume that the user will do what you tell him to do. That's almost never true. Validate the inputs you read.