This question already has answers here:
Check if String contains only letters
(17 answers)
Closed 7 years ago.
I am writing some code but am unsure how to set it so users can only input certain letters for grade. (A,B,C,D,F)
import java.io.IOException;
import java.util.Scanner;
public class Forloop {
public static void main(String[] someVariableName) throws IOException {
String Grade1;
String Grade2;
String Grade3;
String Grade4;
String Grade5;
Scanner in = new Scanner( System.in );
System.out.println("This program will ask you to input five grades \n");
System.out.println("Please enter leter grade one. \n");
Grade1 = in.next();
System.out.println("Please enter leter grade two. \n");
Grade2 = in.next();
System.out.println("Please enter leter grade three. \n");
Grade3 = in.next();
System.out.println("Please enter leter grade four. \n");
Grade4 = in.next();
System.out.println("Please enter leter grade five. \n");
Grade5 = in.next();
System.out.println("Your grades are ==>");
System.out.println(Grade1);
System.out.println(Grade2);
System.out.println(Grade3);
System.out.println(Grade4);
System.out.println(Grade5);
}
}
Variables should start with lowercase letter.
To ensure only valid data is entered, loop back and ask again if it's wrong.
Letter is spelled with 2 t's.
Use nextLine(), not next().
Easiest way to check valid text (for this case), is a regular expression, e.g.
String grade1;
do {
System.out.println("Please enter letter grade one: ");
grade1 = in.nextLine();
} while (! grade1.matches("[ABCDF]"));
Use this approach.
import java.io.IOException;
import java.util.Scanner;
public class Forloop {
public static void main(String[] someVariableName) throws IOException {
String[] grades = new String[5];
Scanner in = new Scanner( System.in );
System.out.println("This program will ask you to input five grades \n");
for(int i = 0; i < grades.length; i++) {
System.out.println("Please enter letter grade " + i + "\n");
grades[i] = in.nextLine();
while(!grade[i].matches("[abcdfABCDF]")) {
System.out.println("Please enter a grade from A to F");
grades[i] = in.nextLine();
}
}
System.out.println("Your grades are ==>");
for(int i = 0; i < grades.length; i++) {
System.out.println(grades[i]);
}
}
}
Related
I am looping five times and taking user inputs using util.Scanner, I am stuck with the part where I have to prompt user for correct input, and when the correct input is given and is to be stored in the array. Then the loop continues.
while(a<5){
Scanner input = new Scanner(System.in);
System.out.println("Please enter the value: ");
int x = input.nextInt();
//what code should be added here to prompt user if input is not in 1-10
//and after checking only, the value should be stored in the array
userInputs[a] = x;
a++;
}
First, ask the user for an input and based on that you loop and take input using scanner.
Scanner input= new Scanner(System.in);
System.out.println("Enter Five Numbers");
The looping part:
int num;
int [] arr= new int[5];
for(int i=0; i<arr.length(); i++)
{
System.out.println("Enter Input "+i);
number=input.nextInt();
TakeInput ti= new TakeInput();
if(ti.validate_input(number)==true) arr[i]=number;
else{
System.out.println("Enter Number "+i+" Again");
number=input.nextInt();
}
}
You can try:
import java.util.Arrays;
import java.util.Scanner;
public class TakeInput {
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
System.out.println("Enter Five Numbers Between 1 and 10");
double number;
//set length of array which stores the user input
double [] arr= new double[5];
for(int i=0; i<5; i++)
{
System.out.println("Enter Input "+i);
//accept input from users
number=input.nextDouble();
TakeInput ti= new TakeInput();
//prompts to renter value if value is not valid
if(ti.validate_input(number)==true)
{
arr[i]=number;
}
else
{
System.out.println("Enter Number "+i+" Again");
number=input.nextDouble();
}
}
System.out.println("Array List: "+Arrays.toString(arr));
}
//validate user input, ensure that input is not out of range
public boolean validate_input(double input)
{
boolean response;
if(input<=1 || input >=10)
{
response=false;
}
else
{
response=true;
}
return response;
}
}
Im trying to ask the user for two numbers. I want to check if those inputs are in fact numbers but the code I have so far does not let me enter a second value if the first input is a string.
So the scanner does not read anything the else statement.
How could I make it work?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fname = console.nextLine();
System.out.print("Please enter your last name: ");
String lname = console.nextLine();
System.out.print("Please enter your first number: ");
if (console.hasNextInt()) {
int number1 = console.nextInt();
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
}
} else
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
// this part does not work
}
}
}
You just need to add console.nextLine(); after your else statement, because the Scanner.hasNextInt method does not move cursor past your previous input (if it is a string).
I've been instructed to create a code that takes a user's first 5 inputs (doubles) and finds the average. My only problem is creating an exception if a user inputs anything other than a number. Could someone show how I can add this exception to my code?
import java.util.*;
public class Test1
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
System.out.println("Please enter a number: ");
double first = numbers.nextInt();
System.out.println("Please enter a number: ");
double second = numbers.nextInt();
System.out.println("Please enter a number: ");
double third = numbers.nextInt();
System.out.println("Please enter a number: ");
double fourth = numbers.nextInt();
System.out.println("Please enter a number: ");
double fifth = numbers.nextInt();
System.out.println("The average is\t" + ((first + second + third + fourth + fifth)/5)+"\t");
}
}
This will handle the user typing non Integers.
It also removes the static Scanner userInput which isn't being used.
public class HelloWorld
{
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
int total =0;
int numberOfQuestion = 5;
for (int i = 0; i < numberOfQuestion ; i ++) {
System.out.println("Please enter a number: ");
while (!numbers.hasNextInt()) {
System.out.println("Input was not a number, please enter a number: ");
numbers.next();
}
total = total + numbers.nextInt();
}
System.out.println("The average is\t" + (total/numberOfQuestion)+"\t");
}
}
Read in information for ALL students before doing any calculations or displaying any output. Verify
that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered.
Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid,
display an error message and allow the user to re-enter that invalid score. Once all student info is read
in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s
exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade,
based on the following percentages:
90-100 A, 80-89.9 B, 70-79.9 C, 60-60.9 D, Below 60 F
This is what i have typed out already but its giving me some errors and I'm not sure I'm assigning the values correctly.
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
int [] exams = new int[4];
int student = 1;
do
{
String [] names = new String[student];
System.out.print("PLease enter the name of student" + student );
names[student-1] = s.nextLine();
for ( int i = 1; i < exams.length; i++){
if(i==4){
System.out.print("Please enter score for Final Exam: ");
}
System.out.print("Please enter score for Exam" + i);
exams[i] = s.nextInt();
if((exams[1]<0||exams[1]>50)||(exams[2]<0||exams[2]>50)||(exams[3]<0||exams[3]>50)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[4]<0||exams[4]>100){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
System.out.println("do you wish to enter another?");
again = s.nextLine();
student++;
}while (again.equalsIgnoreCase ("y"));
}
}
This is the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Proj4.main(Proj4.java:32)
But its confusing because line 32 is just a } so i really don't know exactly what it means,
i know i probably need to reduce the length of one of the inputs for the arrays but I'm not sure which or if there's even more wrong than that.
EDIT:
Sorry here is my question, Would you guys help me figure out the problem and/or tell me if or what i am doing wrong to get the output required of me?
Array exams has 4 elements only but you try to access 5th element with index 4 here exams[4]<0. First index of array is 0 (not 1).
Does the below work for you?
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String again = "y";
int[] exams = new int[4];
int student = 1;
do {
String[] names = new String[student];
System.out.print("PLease enter the name of student" + student);
names[student - 1] = s.nextLine();
for (int i = 0; i < exams.length; i++) {
System.out.println(i + " i");
if (i == 3) {
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
if (exams[3] < 0 || exams[3] > 100) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
} else {
System.out.print("Please enter score for Exam " + i);
exams[i] = s.nextInt();
if ((exams[i] < 0 || exams[i] > 50)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.println("do you wish to enter another?");
again = s.next();
student++;
} while (again.equalsIgnoreCase("y"));
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loop Keyword Program Homework
s I'm having a problem with this program. The user will enter a keyword, and then after that will enter a sentence. I need the program to output how many sentences contain the keyword, and the average starting position of the keyword in the strings. This is what I have so far. Whenever the program outputs, it doesn't give me the correct # of times the keyword is entered. It just gives me the # of sentences. Can somebody please help me? Thanks.
import java.util.Scanner;
public class Lab6Loops {
public static void main(String[] args) {
String keywordString;
String inputString;
Scanner keyboard = new Scanner (System.in);
int numofSentences = 0;
int numofKeyword = 0;
System.out.println ("Enter a keyword. We will search each sentence for this word.");
keywordString = keyboard.nextLine ();
System.out.println ("Please enter a sentence or type 'stop' to finish");
inputString = keyboard.nextLine ();
while( !inputString.equals ("stop"))
{
if(inputString.contains (inputString));
numofSentences = numofSentences + 1;
if(inputString.contains (keywordString));
numofKeyword = numofKeyword + 1;
System.out.println ("Enter a line of text or 'stop' to finish");
inputString = keyboard.nextLine();
}
System.out.println ("You entered " + numofSentences + " sentences");
System.out.println ("You have " + numofKeyword + "sentences that contain the keyword");
}
}
Maybe without the ; after the if statements it will work better :-)
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter a keyword. We will search each sentence for this word.");
String keywordString = keyboard.nextLine();
System.out.println("Please enter a sentence or type 'stop' to finish");
String inputString = keyboard.nextLine();
int numofSentences = 0;
int numofKeyword = 0;
while (!inputString.equals("stop"))
{
if (inputString.contains(inputString))
numofSentences++;
if (inputString.contains(keywordString))
numofKeyword++;
System.out.println("Enter a line of text or 'stop' to finish");
inputString = keyboard.nextLine();
}
System.out.println ("You entered " + numofSentences + " sentences");
System.out.println ("You have " + numofKeyword + "sentences that contain the keyword");
}