Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to ask the user to enter up to 10 valid names. In my code I have to have a array with all the full names. Inside that array the full names are a array with the names separated. For each full name - To be valid needs to have at least two names with at least 4 characters. If the user introduces 5 valid full names could digit "fim" to end the program. The max is 10 valid full names, if the user reaches the 10 valid full names the program should end. These code isn't correct because it doesnt end when it reaches 10 valid full names or if the user digits end after 5 or more valid full names.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter up to 10 full names with up to 120 characters and at least two names with at least 4 characters: ");
String[] fullName= new String[10];
String[] separatedName;
String name;
int i = 0;
do {
name = keyboard.nextLine();
fullName[i]=name;
i++;
separatedName = name.split(" ");
//System.out.println(Arrays.toString(separatedName));
int l = 0;
for(int n = 0; n < separatedName .length; n++){
if(separatedName [n].length() >= 4 ) {
l++;
}
}
if(l >= 2 && name.length() <= 120 || name.equalsIgnoreCase("fim") ) {
//System.out.println("Valid name.");
}
else {System.out.println("'" +name+ "'" + " is an invalid name");
}
}
while(i<10);
keyboard.close();
}
Still Not sure what you are trying to do. Try this and this should solve your problem
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter up to 10 full names with up to 120 characters and at least two names with at least 4 characters: ");
String[] fullName= new String[10];
String[] separatedName;
String name;
int i = 0;
int validCount=0;
do {
name = keyboard.nextLine();
fullName[i]=name;
i++;
separatedName = name.split(" ");
//System.out.println(Arrays.toString(separatedName));
int l = 0;
for(int n = 0; n < separatedName .length; n++){
if(separatedName [n].length() >= 4 ) {
l++;
}
}
if(l >= 2 && name.length() <= 120 ) {
validCount++;
//System.out.println("Valid name.");
}
else {System.out.println("'" +name+ "'" + " is an invalid name");
}
if(validCount>=5 || name.equalsIgnoreCase("fim")) {
break;
}
}
while(i<10);
keyboard.close();
}
Related
I'm currently taking a beginning Computer Science course and for one of our assignments we basically have to create a magic eight ball using an array where the user inputs the amount of values in the array and also inputs the values themselves in the array using a loop. After writing the code, I tested it and found that for some reason it wasn't setting the input into the array like it was supposed to it and after hours tweaking and trying to figure out what's wrong with it I still have no clue. Any help would be much appreciated.
Scanner input = new Scanner(System.in);
String answer = "a";
String question = " ";
int currentResponse = 0;
out.println("How many responses would you like there to be?");
int numResponses = input.nextInt();
String[] responses = new String[numResponses];
//This is the loop that's the problem:
for (int i = 0; i < numResponses; i++)
{
out.println("Enter an answer: ");
answer = input.nextLine();
responses[i] = answer; //Should set the array value to the input
input.next(); //It kept skipping the input part the first time
//so I added this
}
//This is where I tried two different ways of printing out the array to
//test it just in case that was the problem:
out.println(Arrays.toString(responses));
for (int i = 0; i < responses.length; i++)
{
System.out.print(responses[i] + " ");
}
while (!question.equalsIgnoreCase("stop"))
{
out.println("What is your question?");
question = input.nextLine();
input.next();
currentResponse = (int)(Math.random()*numResponses);
out.println(currentResponse);
out.println(responses[currentResponse]); //It also doesn't appear to
//actually print this out but I think that that's because the values are //blank
spaces
}
out.println("Thank you for using the Magic Eight Ball");
The output should be something like
How many responses would you like there to be?
4 //The input
Enter an answer:
s
Enter an answer:
d
Enter an answer:
f
Enter an answer:
g
[s,d,f,g]
What is your question?
s
0 //The randomized array index number
s //The value of that index
What is your question?
d
2
f
What is your question?
g
1
g
instead it's currently
4
Enter an answer:
s
Enter an answer:
d
Enter an answer:
f
Enter an answer:
g
[, , , ]
What is your question?
s
0 //the randomized array index number
What is your question?
d
2
What is your question?
g
1
input.nextInt(); only consumes the integer entered, it doesn't consume the newline character entered after it. To get around this you can use input.nextLine(); to consume the newline char after it. Then you should be able to remove the input.next(); from the end of the for loop when taking in the responses.
You can also remove the input.next(); within the question loop later on as that's not needed as well -- the input.nextLine(); consumes the whole line.
Here's the adjusted code:
Scanner input = new Scanner(System.in);
String answer = "a";
String question = " ";
int currentResponse = 0;
System.out.println("How many responses would you like there to be?");
int numResponses = input.nextInt();
input.nextLine();
String[] responses = new String[numResponses];
//This is the loop that's the problem:
for (int i = 0; i < numResponses; i++)
{
System.out.println("Enter an answer: ");
answer = input.nextLine();
responses[i] = answer; //Should set the array value to the input
}
//This is where I tried two different ways of printing out the array to
//test it just in case that was the problem:
System.out.println(Arrays.toString(responses));
for (int i = 0; i < responses.length; i++)
{
System.out.print(responses[i] + " ");
}
while (!question.equalsIgnoreCase("stop"))
{
System.out.println("What is your question?");
question = input.nextLine();
currentResponse = (int)(Math.random() * numResponses);
System.out.println(currentResponse);
System.out.println(responses[currentResponse]); //It also doesn't appear to
//actually print this out but I think that that's because the values are //blank spaces
}
System.out.println("Thank you for using the Magic Eight Ball");
}
Some additional documentation: https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am new to programming, currently my first year in trying this.
Just like the title, i am having a hard time completing this code of mine.
I already searched high and low and couldn't find something.
The code is incomplete and I know i need to change some things.
What can i do to complete this? I am already worn down.
import java.util.*;
public class Ihateyou {
public static void main (String []args) {
Scanner fkc = new Scanner (System.in);
System.out.println("Enter an Element or something: ");
char ch=fkc.next( ).charAt(0);
String unknown = fkc.nextLine();
if (ch=='H' + unknown.substring(unknown.length() - 1))
{
System.out.println("False "+ch+" ends with h");
}
else if ((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println("True "+ch+" ends with no H");
}
}
Scanner fkc = new Scanner (System.in);
System.out.println("Enter an Element or something: ");
String unknown = fkc.nextLine();
char [] arr = unknown.toCharArray();
int lastLetterIndex = arr.length - 1;
if(arr[lastLetterIndex]=='h') {
System.out.println("ends with H");
}
else {
System.out.println("ends with no H");
}
It's nore pretty clear what you want to do, but last letter of the string you can get with str.charAt(str.length() - 1):
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter an Element or something: ");
String str = scan.nextLine();
char lastChar = str.charAt(str.length() - 1);
if (lastChar != 'h')
System.out.println("False " + str + " ends with h");
else if (Character.isLetter(lastChar))
System.out.println("True " + str + " ends with no H");
}
I'm not 100% sure what you want to do, but I've tried to go thru what your code seems to be doing since you seem a little bit unsure of that, and then propose how I would solve the problem I think you have.
public class Ihateyou {
public static void main (String []args) {
Scanner fkc = new Scanner (System.in); // This creates a new scanner, which lets us read from System
System.out.println("Enter an Element or something: ");
char ch=fkc.next( ).charAt(0); // This reads the next sequence terminated by the enter key. Then it stores the single first character of that in a char, ch
String unknown = fkc.nextLine(); // This basically does the same thing, storing it in unknown
if (ch=='H' + unknown.substring(unknown.length() - 1)) // This checks if ch equals H + most of the unknown string. This doesn't make sense for two reasons.
// One problem is that 'H' + unknown is a string, not a char: it doesn't make sense to compare a String with a char.
// The other is that unless unknown is an empty string (""), and char is 'H', even if we could compare they wouldn't be the same
{
System.out.println("False "+ch+" ends with h");
}
else if ((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println("True "+ch+" ends with no H");
}
}
What I think you might be trying to do is to determine whether the thing the user inputs ends with an H. To do this, I would try the following:
public static void main (String []args) {
Scanner fkc = new Scanner (System.in); // This creates a new scanner, which lets us read from System
System.out.println("Enter an Element or something: ");
String userInput = fkc.nextString(); // Store the next String the user inputs in userInput
if(userInput.charAt(userInput.length() - 1)) == 'H'){ // userInput.charAt() gets us the character at a given index in the string. We want the last one, so we get
// the one at userInput.length() - 1. Then we check to see if it is H
{
System.out.println("False "+ch+" ends with h");
}
else{
System.out.println("True "+ch+" ends with no H");
}
}
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;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I tried to print my array using to Arrays.toString(array)); but still it gave me errors... And also ELEMENT IS FOUND is false statement but it mixes with the true statement when i tried to search an element in my array,
for example.....
I searched 4 in my array: 4 , 2, 3 ,5
but ELEMENT IS FOUND is still showing.
import java.util.Scanner;
public class linee {
public static void main(String[] args) {
int String;
int value;
Scanner in = new Scanner(System.in);
System.out.print("Input the Number of Element: ");
String n = in.nextLine();
int num = Integer.parseInt(n);
String array[] = new String[num];
for (int i = 0; i < array.length; i++) {
System.out.print("Input the Number at array index " + i + ": ");
array[i] = in.nextLine();
}
Linear(array);
System.out.print("\nDo you want to continue? YES = 1, NO = 2: ");
value = in.nextInt();
if (value == 1) {
main(args);
} else if (value == 2) {
System.out.println("\nThank you for using the program.");
}
}
public static void Linear(String[] array) {
boolean flag = false;
String key = "";
int index = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number that you want to search: ");
key = in.nextLine();
for (int i = 0; i < array.length; i++) {
if (array[i].equals(key)) {
flag = true;
index = i;
}
}
if (flag == true) {
System.out.println("Elements: " + Arrays.toString(array));
System.out.println("ELEMENT IS FOUND AT INDEX " + index);
} else {
System.out.println("ELEMENT IS NOT FOUND");
}
}
}
From the Object.toString(Object[] a) spec:
Returns a string representation of the contents of the specified
array. If the array contains other arrays as elements, they are
converted to strings by the Object.toString() method inherited from
Object, which describes their identities rather than their contents.
That is, you may want to print your elements in another way. An option is:
System.out.println("Elements: ");
for(String str: array) {
System.out.println(str);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hi there I am trying to create an array of records in java in which you have to enter 3 details, the name of a town, the population and the county in which is resides. Before then outputting all the data on a county which you have asked for. I was wondering if anyone could show me why a null.point.exception occurs if I enter the population of a town when does not occur when i enter another one.
import java.util.*;
public class CathedralTowns
{
public static String name;
String population;
String county;
public static int count = 0;
public static int continuation = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
while (loop1 <= 0) {
System.out.println("Please enter the name of the town. ('no' to end)");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides. ('no' to end)");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town. ('no' to end)");
String populationEntered = input.nextLine();
if (nameEntered.equals("no") || populationEntered.equals("no") || countyEntered.equals("no") ) {
loop1 = 5;
System.out.println("Thank you for entering your county.");
continuation = 1;
}
WorkingDemCathedrals(nameEntered, populationEntered, countyEntered);
}
}
public static void WorkingDemCathedrals(String nameEntered, String populationEntered, String countyEntered) {
Scanner input = new Scanner(System.in);
CathedralTowns[] allTowns = new CathedralTowns[50];
allTowns[count] = new CathedralTowns();
int loop2 = 0;
int loop3 = 0;
while (loop2 == 0){
allTowns[count].name = nameEntered;
allTowns[count].population = populationEntered; //the error relates back to here according to bluej
allTowns[count].county = countyEntered;
if (continuation == 1) {
loop2 = 1;
System.out.println("please enter the name of a county for which you wish to know the details.");
String countyOfChoice = input.nextLine();
while (loop3 > 0){
if ((allTowns[loop3].county).equals(countyOfChoice)){
System.out.println(allTowns[loop3].name);
System.out.println(allTowns[loop3].population);
loop3 = -2;
}
loop3 = loop3 +1;
}
}
count = count + 1;
}
}
}
Elements in an Object array are null by default. Initialialise the elements prior to attempting to access them
for (int i=0; i < allTowns.length; i++) {
allTowns[i] = new CathedralTowns();
}
This lines is very suspicious
allTowns[count] = new CathedralTowns();
You allocate only one object in the array while you have a line before allocated an array of the length 50.
CathedralTowns[] allTowns = new CathedralTowns[50];
Not to mention that it is prone to ArrayIndexOutOfBoundsException if count is equal or more that 50
Then you start to loop and increment count and that's where it happens!
your should loop over the entire array and allocate an object in each slot.
The NullPointerException occurs at "population" and not at "name" is because the "name" field is static, whereas the "population" is non-static.
Also the allocation of the array of CathedralTowns has to be done as per the first answer.
The while (loop2 == 0) could end up in a infinite loop. There is no end condition for this while loop, if the user wants to enter details of more than one county.