For loop that takes user input 5 times - java

I was to make a for loop that repeats 5 times. Each time it asks you to enter a grade, takes your input using System.in.read();, then says what you entered. For some reason the output looks strange and it isn't working right. The output looks like this:
Enter a letter grade for your class
(the letter you enter ex. a)
Grade entered = a
Enter a letter grade for your class
Grade entered =
the above repeats 3 times then ends with the "thanks, keep up the good work!" line ^
The output should look like
Enter a letter grade for your class
(entered letter ex. b)
Grade entered = b
And it does this 5 times ^
Sorry if it isn't indented properly or the solution is obvious, new to programming.
char g;
{
for (int x = 0; x < 5; x++) {
System.out.println("Enter a letter grade for your class");
g = (char) System.in.read();
System.out.println("Grade entered = " + g); }
System.out.println("Thanks, keep up the good work!"); }

Some points regarding your code. Firstly, format it correctly. Your problem currently is that your for-loop is only running for the System.out.println statement, and the rest is ignored. Don't omit brackets when you write for-loops, its not a very good habit. Since this is homework, I will not give you the code, but I will give you the code structure:
public class Main {
public static void main(String[] args) {
for (int x = 0; x < 5; x++) { //looping 5 times
System.out.println("Enter a letter grade for your class"); //print statement
//code here to get character
System.out.println("Grade entered = " + g);
}
//print final statement outside the for-loop.
System.out.println("Thanks, keep up the good work!");
}
}
Next point: I would not recommend using System.in.read() for reading the input from the console. Reason for this, is because it will include the carriage return when you press 'Enter' - you would need to specifically look out for that in your code. In order to avoid this, use a Scanner, and get the first character of the returned Scanner string using charAt(0).

Related

How do I prevent an error message from repeating in Java?

I'm trying to write a program to calculate factorial but I can't figure out why the Error message displays twice if I enter a letter instead of an integer.
I feel like the issue has to do with Line 29 c = sc.next().charAt(0);, but am not sure how to fix it. Any help is appreciated.
My program:
public class Factorials {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = 'Y';
int num = 0;
do
{
System.out.print("Enter a number to calculate its factorial: ");
while (!sc.hasNextInt()) {
System.out.println("Invalid Entry - Enter only Integers! Try Again: ");
sc.nextLine();
}
int result = 1;
num = sc.nextInt();
for(int i = 1; i <= num; i++) {
result = result * i;
}
System.out.println("The factorial of " + num + " is: " + result);
System.out.println("Do you wish to continue? Y/N: ");
c = sc.next().charAt(0);
}while(c == 'y' || c == 'Y');
sc.close();
}
}
Simple fix: Change the sc.nextLine(); in your code to a sc.next() and you should be good to go. This error occurs because .nextLine() considers the enter/return key as a separate character, while .next() doesn't. (The enter key when you press it after entering either 'y' or 'n': if you try it, the error message doesn't print twice if you enter a letter the first time you run the program).
Side note: You probably want it to be a .print(/*invalid input sentence*/) instead of a .println() to go along with how you take in your other number values.
Otherwise, you're good!
Finds and returns the next complete token from this scanner.
A complete token is preceded and followed by input that matches
the delimiter pattern
As jdk doc shows, the 'sc.next' method will return when it reaches space, enter or return. So when you enter 'y' with enter, the enter character is still in buffer. You can assign sc.nextLine to a variable, like
String str = sc.nextLine();
System.out.println(str);
You can see the enter character and your input character.
Both #TheSj and #Lahiru Danushka answer could solve this problem.
add sc.nextLine(); after c = sc.next().charAt(0);

Scanner object executes only one time in while loop

I have a situation where the program will take input for total no of string to be inputted.
Once inputted it will print odd and even indexes of the string in one line separated by a space.
For illustration this should be the output for the follwing input:
2
input
ipt nu
output
otu upt
my logic seems fine but when I am trying to execute the program runs for only one time whatever be the input. Can anyone please let me know what am I missing here.
Code snippet
import java.util.Scanner;
public class javatest
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
String input_string;
int inputs = scan.nextInt();//total inputs to be accepted
int i=0;
while(i<inputs)
{
input_string = scan.nextLine();
//for even places
for (int j = 0; j < input_string.length(); j += 2)
{
if (j % 2 == 0)
{
System.out.print(input_string.charAt(j));
}
}
System.out.print(" ");
//for odd places
for (int k = 1; k < input_string.length(); k += 2)
{
if (k % 2 == 1)
{
System.out.print(input_string.charAt(k));
}
}
i++;
}
}
}
The above code is producing the output as
3
hello
hlo el
(execution ended)
The issue is that scan.nextInt() does not read the enter pressed while inputing the number. Due to this issue your program runs 1 iteration lesser than the input.
I ran your exact code without any modification and it runs twice for input 3.
The first call to scan.nextLine() gives an empty string.
The alternative can be replacing
scan.nextInt() with Integer.valueOf(scan.nextLine());
which will read the enter/new line character also.
By pressing enter upon entering the amount of inputs you are creating a newline \n character which is consumed by the input_string = scan.nextLine(); in your while loop. So directly after entering the amount of inputs the while loop will increment the value of i to 1 as it processes the \n character.
As a workaround you could fetch the amount of expected inputs as a String and parse it to an int like this:
int inputs = 0;
try {
inputs = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
// handle exception gracefully, maybe by showing a message to the user.
}
Also to make it more clear for the user to understand that an input is expected you might want to add a message that makes it clear a new input is expected:
System.out.println("Please provide the next input: ");
input_string = scan.nextLine();

Program only prints out second last letter. want the whole word backwards instead

import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word;
String c;
int x, count, count1;
System.out.println("Please enter a word:");
word=in.nextLine();
x=word.length();
for(count=0;count<x;count++) {
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
}
}
}
All this program does is print out the second to last character of the word that the user enters. I'm confused as to why it is doing this and want to know how to print out the whole word backwards. Someone help please.
You don't need a loop to reverse a string.
Ref - StringBuilder#reverse
Scanner in = new Scanner(System.in);
System.out.println(new StringBuilder(in.nextLine()).reverse());
If you want to print characters in reverse, then forget the substring-ing.
String word = in.nextLine();
int x = word.length();
for(count = x - 1; count >= 0; count--) {
System.out.println(word.charAt(count));
}
Take count1=x; assignment out of the loop. Also make count--; after printing the letter.
You are correct up until x = word.length(). It is printing the second from last character because you keep setting the value of count1 to length of word and you substract it by 1. Therefore, it keeps referring to the second last character. To fix that, do the following instead:
count1=x;
for(count=0;count<x;count++) {
c=word.substring((count1)-1,count1);
System.out.println(c);
count1--;
}
Every time the loop is running, you are resetting the count1 value to x (count1=x). So c will always be the same value.
To make this work, try taking count1 = x out of the loop so that every time the loop is running, count1 value will be reduced as expected providing the required sub-string.
Into the loop for(count=0;count<x;count++)
Every loop you did the same thing
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
This block has no relation with the loop!
Thats why you are getting the second last character!
To fix this:
Solution 1: (Just reverse the String)
word=in.nextLine();
System.out.println(new StringBuilder(word).reverse());
or Solution 2: (Using loop using your code)
x=word.length();
for(count= x-1; count >= 0; count--) {
c = word.substring((count)-1, count);
System.out.print(c);
}
If at all you want to do it the hard way by traversing, do the following changes.
for(count=x;count>=0;count--) {
System.out.println(word.substring(count - 1,count));
}
Update: You can use charAt#String to easily get the character at some position.
for(count=x-1;count>=0;count--) {
System.out.println(word.charAt(count));
}

How can I input an if statement inside a while loop?

import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
I'm trying to place a conditional statement inside the while loop. The condition is to test for would be that of, if num is a negative number, S.O.P.("You entered a negative #"); in other words,
if(num<0)
S.O.P.("You entered a negative #");
However it doesn't print it properly.
If you check inside the loop then it will not work it will still multiply the fact. You need to make sure that the num is not negative before you start the while loop.
int num = 0;
do {
if (num<0){
System.out.println("You printed out a negative number");
}
System.out.println("Enter a natural number ");
int num=type.nextInt();
} while (num<0);
Also on a side note you should probably close your scanners when you are done using them.
The question is hard to understand but from what i read it appears you want a loop to run until a value is entered that meets your pre-condition of being positive
System.out.println("Enter a non negative number :: ");
int num = type.nextInt();
while(num < 0){
System.out.println("The number you entered was negative!");
System.out.println("Enter a non negative number :: ");
num = type.nextInt();
}
Loops like this are crucial to making sure the data that you are using is within the pre-condition of your operation which could cause DivideByZero errors or other problems. This loop should be placed before you ever use the value of num so you can make sure it is within context of your program.
The problem is that if the num is negative, it won't go inside the while loop that is because before the while loop you have initialize i=1, since any negative number is lesser than 1 the condition for while loop become false. If you want to check whether num is negative insert the if condition before the while loop as follows
import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
if(num < 0) {
System.out.println("You entered a negative #");
}
else{
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
}
To answer your question .... like this:
int i = 1; // HERE
while (i <= num) {
if (num < 0) {
System.out.println("You entered a negative #");
}
fact *= i;
i++;
}
However that is not going to work.
Suppose that "num" that you read is less than zero.
At the statement labeled "HERE", we set "i" to one.
In the next statement, we test "i < num".
Since "num" is less than zero, that test gives "false" and we skip over the entire loop!
That means that your conditional statement in the loop body would not be executed ... if "num" is less than zero.
Since this is obviously homework, I will leave it to you to figure out what you should be doing here. But (HINT!) it is not putting the conditional inside the loop.
(Please note: I have corrected a number of style errors in your code. Compare your original version with mine. This is how you should write Java code.)
You basically have to check whether the number is less than 0. This is to be done while taking the input. You can just take the input inside a while loop in this manner:
System.out.println("Enter a natural #");
while(true){ //loop runs until broken
num = type.nextInt();
if(num>=0)
break;
System.out.println("Wrong input. Please enter a positive number");
}
The program control breaks out of the loop if num>=0, i.e., positive, else, it continues to the next part of the loop and displays the error message and takes the input again.
Please note that natural numbers are the ones >= 1. In your program, you are actually trying to input a whole number which is >= 0.

How do I count too see how many numbers and letters are in a user inputted string?

I have been asked to write an application that prompts the user for a String that contains at least five letters and at least five digits. Continuously reprompt the user until a valid String is entered. Display a message indicating whether the user was successful or did not enter enough digits, letters, or both.
I am a beginner programmer and I need help figuring out how too make this application work correctly. My issue is I am unable to figure out how to make my program interpret the letters and numbers from user input. Here is what I have so far:
public static void main(String[] args) {
// Declare variables.
String message;
int numLetters = 0;
int numDigits = 0;
boolean letters = false;
boolean digits = false;
// Input.
Scanner input = new Scanner(System.in);
System.out.println("Type a message with 5 letters and 5 digits: ");
message = input.nextLine();
// Loop through string.
The dark art of regular expressions can crush this problem with just one method call:
public static boolean check(String input) {
return input.matches("(?i)(?=(.*?[a-z]){5})(?=(.*?\\d){5}).*");
}
Breakdown:
the matches() method accepts a regex that must match the whole string to return true
the basic matching regex is .*, which matches everything
(?i) means "ignore case"
[a-z] is a character class as means "any lowercase letter"
.*?[a-z] means "0-n chars (but the smallest number possible) then a letter"
(.*?[a-z]){5} means "5 copies of the above"
(?=(.*?[a-z]){5}) is a "look ahead", which asserts, but does not consume the input (so you can fire another one) and means "there must be at least 5 letters in the input"
(?=(.*?\\d){5}) is similar, but asserts there are at least 5 numbers
Create a method to check if it has 5 letters and 5 digits:
public boolean check(String input){
int numDigits = 0;
int numLetters = 0;
for(int i=0; i<input.length();i++){
if(Character.isLetter(input.charAt(i))) numLetters++;
if(Character.isDigit(input.charAt(i))) numDigits++;
}
return (numDigits >= 5) && (numLetters >= 5);
}
Then you can add this method to a while loop:
while(!check(message)){
// get the input again and assign it to message
}
HA!!!! I GOT IT... For all you kids out there that need an answer to REFERENCE, check this out! Since everyone likes to dance around giving a good answer here is copy and paste code that will work. (Please dont hand it in as your own, but check out how this PITA code works!
//Date: 5/31/2015
//Subject: Mod 4, pg 389, Question 3
//Purpose:User is to input 5 digits and 5 letters. It will re prompt user until at least 5 digits and 5 letters are typed in.
import java.util.Scanner;
public class FiveLettersAndFiveDigits
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int numDigits = 0;
int numLetters = 0;
String message;
System.out.println("Please enter a 5 letter word and 5 digits.");
message = keyboard.nextLine();
while(numLetters < 5 &&numDigits <5)
{
for(int i=0; i < message.length();i++)
if(Character.isLetter(message.charAt(i))) ++numDigits;
for(int j=0; j < message.length();j++)
if(Character.isDigit(message.charAt(j))) ++numLetters;
if(numLetters >= 5 && numDigits >= 5)
{
System.out.println("You have " +numDigits+ " numbers and " +numLetters+ " letters, great job.");
}
else
{
System.out.println("You have typed in "+numDigits+" letters and "+numLetters+" numbers. Please try again.");
System.out.println("Please enter a 5 letter word and 5 digits.");
message = keyboard.nextLine();
continue;
}
}
System.out.println("This problem was no fun, hahaha. Took me like 3 hours!");
}
}
And that is that folks! Thank your lucky stars you had a reference online that was straight forward! hahaha Nothing sucks more than looking for some kind of direction and all you get is half #$$3D hints. Feel free to check out how this works.

Categories

Resources