How do you print x number of lines at a time - java

I have a program that prints the instance variables of objects stored in an arraylist.
I want to add a feature to this program so it only prints the instance variables for first 10 objects, then ask the user to press enter to continue, then continues with the next 10 objects and so on.
Here is an example of how the printing loop looks without the function i'm asking for:
for (int i = 0; i < myList.size(); i++)
{
System.out.println(myList.get(i).getName();
}
The "Press enter to continue" part is easy enough:
import java.util.*;
...
Scanner input = new Scanner(System.in);
input.nextLine()
but how do i create a conditional loop that stops after 10 prints and then resumes after the "Press enter to continue" event??

for (int i = 0; i < myList.size(); i++)
{
System.out.println(myList.get(i).getName();
if(i % 10 == 0){
input.nextLine()
}
}

You could use System.in.read(), It reads a character and hence when the user presses any key, it continues.
Other wise waits for the user to input.
for (int i = 0; i < myList.size(); i++)
{
System.out.println(myList.get(i).getName();
if(i % 10 == 0){
System.out.println("Press any key to continue!");
char ch = (char) System.in.read();
}
}

Try this code:
for(int index = 0; i <myList.size(); i++){
/*check if it has printed 10 times first or else, it'll be printed 11 times first*/
if( i % 10 == 0 && i!=0 ){
System.out.println("Press enter to continue...");
//Prompt the user of course...
input.nextLine();
}
System.out.println(myList.get(i).getName());
}
as commented in the code above, you need to check if it is printed 10 times first. #bmscomp's code might have a bug if it has more than 10 entries.

I decided to go with my own approach.
I wish i could credit everyone with an answer-tick as my suggestion is a combination of them all:
for (int i = 0; i < myList.size(); i++)
{
if(i % 10 == 0 && i != 0){
System.out.println("Press enter to continue...");
input.nextLine();
}
System.out.println(myList.get(i).getName());
}
Putting the printing outside the if statement makes more sense.
Now it properly prints 10 statements the first time instead of 11.

I believe you can have a better idea on what to be done on receiving user input.
Please try following:-
`
import java.util.Scanner;
public class GetInputFromUser {
public static void main(String args[]) {
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}

Related

invalid value user input ask again to place into array

Scanner scanner = new Scanner(System.in);
int grade[] = new int[3];
for (int i = 0; i < grade.length; i++) {
System.out.println("Enter your test score:");
grade[i] = scanner.nextInt();
}
I've been trying to figure out how to make it so if the user input is below 0 or above 100 it will ask again. I'm very new to Java and this is the first language I'm learning. I would appreciate any pointers. Do I need to use a do-while loop instead of a for loop for this? Or do I implement an if statement into the for loop?
You can validate the input by putting an if block inside the for loop.
However, since your loop will only execute three times, you should change your increment condition only when user enters correct input or else not.
You also can use while loop here.
Here is some example code:
for (int i = 0; i < grade.length; i++)
{
System.out.println("Enter your test score:");
if(grade[i] < 0 || grade > 100)
{
i--;
continue;
}
grade[i] = scanner.nextInt();
}
The if block will check that if the input is outside boundaries, decrement i and restart the loop.
What I suggest is, instead of incrementing i in loop, you can increase the value in if condition. Like below,
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int grade[] = new int[3];
for (int i = 0; i < grade.length;) {
System.out.println("Enter your test score:");
int temp = scanner.nextInt();
if (temp >= 0 && temp <= 100) {
grade[i] = temp;
i++;
}else {
System.out.println("Please enter valid score");
}
}
scanner.close();
}
This basically gets a input value from user, if the value is greater or equal to 0 && lesser or equal to 100,then adds it to the Array and increments the loop count(array index value we can call it), else, prints message asking for valid input.
Instead of shoving the validation logic somewhere within the loop, you could also write a small utility method which neatly asks for valid input, and continues to do so until the user finally inputs something valid:
int promptInt(Scanner scanner, int min, int max, String errorMessage) {
while (true) {
int input = scanner.nextInt();
if (min <= input && input <= max) {
return input;
}
else {
System.out.println(errorMessage);
}
}
}
You could then simplify the loop:
int grade[] = new int[3];
for (int i = 0; i < grade.length; i++) {
System.out.println("Enter your test score:");
grade[i] = promptInt(0, 100, "Please enter a valid number");
}

How to seperate a string by " " and store them into 2 different arrays?

I am trying to solve a competitive programming practice set. I am only a beginner so please bear with me.
Here is the problem
The history teacher at your school needs help in grading a True/False test using his designed
scoring technique. Each correct answer is awarded two points, each wrong answer gets one
point deducted, and no answer gets a zero.
Your task is to help the teacher automate this task.
Input
The first entry in the file contains answers to the test in the form:
TFFTFTFTFFFTTTTFTFTF
The next line is the number test cases, i.e. number of students who took the test.
Every other entry in the file is the student ID, followed by a blank, followed by the student's
responses. For example, the entry:
S2013-1-1003 TFTFTFTT TFTFTFFTTFT
indicates that the student ID is S2013-1-1003 and the answer to question 1 is True, the
answer to question 2 is False, and so on. This student did not answer question 9. The exam, in
this example, has 20 questions.
Output
The output should be the student's ID, followed by the answers, followed by the test score,
followed by the test grade. Assume the following grade scale: 90%-100%, A; 80%-89.99%, B;
70%-79.99%, C; 60%-69.99%, D; and 0%-59.99%, F.
Sample Input
TTTTTFFFFF
3
S2013-1-2345 TTTTTFFFFF
S2013-1-1266 TFTFTFTFTF
S2012-2-0006 T T TF F F
Sample Output
S2013-1-2345 TTTTTFFFFF 20 A
S2013-1-1266 TFTFTFTFTF 8 F
S2012-2-0006 T T TF F F 12 D
*/
My code :
public class Score {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//input answer to the test
String correctAnswer = sc.nextLine();
//input number of test cases
int numberOfStudents = sc.nextInt();
String studentID[] = new String[numberOfStudents];
String studentAnswer[] = new String[numberOfStudents];
int studentScore[] = new int[numberOfStudents];
char studentGrade[] = new char[numberOfStudents];
//ask user to input data
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter student details");
studentID[i] = sc.nextLine();
studentAnswer[i] = sc.nextLine();
}//end of first for loop
//checks whether the student has the correct score
for(int y = 0; y < correctAnswer.length(); y++) {
if(studentAnswer[y].charAt(y) == correctAnswer.charAt(y)) {
studentScore[y]++;
}//end of if
}//end of for
for(int y = 0; y < numberOfStudents; y ++) {
double percentage = (studentScore[y] / correctAnswer.length()) * 100 ;
//check the letter grade of the student
if(percentage >= 90) {
studentGrade[y] = 'A';
}//end of first if
else if(percentage >= 80 && percentage <= 89) {
studentGrade[y] = 'B';
}//end first else if
else if(percentage >= 70 && percentage <= 79) {
studentGrade[y] = 'C';
}//end of second else if
else if(percentage >= 60 && percentage <= 69) {
studentGrade[y] = 'D';
}//end of third else if
else {
studentGrade[y] = 'F';
}//end of last else
}//end of for
//close the scanner to avoid any memory leaks
//display the score
for(int i = 0; i < numberOfStudents; i++) {
System.out.printf("%d\t%d\t%d\t%d", studentID[i], studentAnswer[i], studentScore[i], studentGrade[i]);
}//end of first for
}//end of main
}//end of class
The program compiles and all however once I input my test data, i received an outofBounders error from my compiler. Then I realized that I had made a mistake in this code
System.out.println("Enter student details");
studentID[i] = sc.nextLine();
studentAnswer[i] = sc.nextLine();
}//end of first for loop
if StudentID and studentAnswer is an integer then I can seperate them by using space and enter my data in one line. However I forgot that when I use space as a seperator, it is not seperated as space is still considered a string. My main question here is how do I ask the user to input his student ID and his answer in one line seperated by a string so that I can store then into my arrays such as studentID array and studentAnswer array.
The format specifier that you use for display the score is wrong! you can can change it as below:
//display the score
for(int i = 0; i < numberOfStudents; i++) {
System.out.printf("%s\t%s\t%d\t%s", studentID[i], studentAnswer[i], studentScore[i], studentGrade[i])
}//end of first for
You are taking input using sc.nextLine(). What does nextLine() do is, it reads all character from input buffer until \n or newline character is found.
So you can ask user to give input something like this way:
StudentID \n studentAnswer
Another way you can modify your input taking array as like as this:
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter student details");
String line = sc.nextLine();
char[] chars = line.toCharArray();
String fs = "";
String sc = "";
boolean flag = false;
for(int j=0;j<chars.length;j++){
if(chars[j]==' ') {
flag = true;
continue;
}
if(flag ==false) fs += chars[j];
else sc += chars[j];
}
studentID[i] = fs;
studentAnswer[i] = sc;
}

Using java, how do count the occurrences of a character in a string, and then format an output with text listing the locations using loops

I understand how to count the occurrences of specific characters in a string. What I am struggling is printing "The specific character is at location x, y, z". If I place the text within the loop that tests for location, the text is printed multiple times. I do not want that to happen.
There are other constraints as well. I must keep the program basic, and I am limited to using the charAt() and string.lenghth() functions. The program should only exit when the user enters "-1". When the user enters the string, the program should read through the characters, output the location of the specific characters, and then prompt the user to enter a new string. I am also struggling with allowing the user to enter a new string and running the loop again.
Here is the code I have so far
import java.util.Scanner;
public class GimmeAW {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Line\nEntering -1 exits the program")
String aLine;
aLine = input.nextLine();
char one = aLine.charAt(0);
char two = aLine.charAt(1);
if (one == '-' && two == '1') {
System.out.println("System Exit");
System.exit(1);
}
for (int i = 0; i < aLine.length(); i++) {
if (aLine.charAt(i) == 'w' || aLine.charAt(i) == 't') {
int location = i;
System.out.print(" " + i);
}
}
}
To avoid printing the msg multiple times, just keep the msg outside of the counting loop and print it once for each character ...
char[] ch = {'w', 't'}; // characters to count
int l = aLine.length();
for(int i = 0; i < ch.length; i++) {
System.out.print("The character " + ch[i] + " is at locations ");
// searching
for(int j = 0; j < l; j++) {
if(aLine.charAt(j) == ch[i]) {
System.out.print(j + " ");
}
}
System.out.println();
}
And you can put all the code you want to repeat inside a do-while loop and run it until the user wants to.
String choice = "yes";
do {
// code
// want to repeat ??
choice = in.nextLine();
} while(choice.equals("yes"));

Where should I put the variable scanner declaration? "int figureNumber = stdin.nextInt();"

I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...

How to check if an int contains a letter

I am trying to validate my code by error checking. I want to make sure the integer people enter does not contain a letter or more.
Here is my code. I am supposed to solve this problem using a one dimensional array. I got the code working but I am having problems with adding the error checking in.
Any help would be appreciated. Thanks
public void getNumbers() {
Scanner keyboard = new Scanner(System.in);
int array[] = new int[5];
int count = 0;
int entered = 0;
int k = -1;
while (entered < array.length) {
System.out.print("Enter a number ");
int number = keyboard.nextInt();
if (10 <= number && number <= 100) {
boolean containsNumber = false;
entered++;
for (int i = 0; i < count; i++) {
if (number == array[i]) // i Or j
{
containsNumber = true;
}
}
if (!containsNumber) {
array[count] = number;
count++;
} else {
System.out.println(number + " has already been entered");
}
} else {
System.out.println("number must be between 10 and 100");
}
//what does %d do?
for (int j = 0; j < count; j++) {
System.out.printf("%d ", array[j]);
}
System.out.println();
}
}
}
I'm assuming that you would want your program to ask the user to re-enter a number if they do not input a number the first time. In this scenario you might want to try something along the lines of this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while(!sc.hasNextInt()) {
//print some error statement
sc.nextLine();
}
int number = sc.nextInt();
System.out.println("Number is: " + number); // to show the value of number
// continue using number however you wish
Since hasNextInt() returns a boolean determining whether or not the input is an Integer, the program will never leave the while-loop until the program can confirm that the user has entered an integer.
keyboard.nextInt() will throw a InputMismatchException if you input a String.
If you want to check whether Scanner has an integer to read, you can use keyboard.hasNextInt().
Alternatively, you can read the input as
String s = keyboard.next() which will take the input as a String, and then use s.matches(".*\\d+.*") to detect whether or not it is an integer.
UPDATE: To answer questions -
keyboard.hasNextInt() will return a boolean. So for example, after System.out.print("Enter a number"), you could have an if statement checking to see if keyboard can receive numerical input, ie. if(keyboard.hasNextInt). If this is true, that means the user has entered numerical input, and you could continue with sayingint number = keyboard.nextInt(). If it is false, you would know that the user input is non-numerical.

Categories