How can I change the code so that it outputs my prompt? - java

Trying to write a program where it outputs the user entered number if it is between 30 and 70.If not, it should prompt the user to reenter. This is what I have so far, but the code is not running at all.
What should I change?
I tried debugging but it seems like it just gives me random quick fixes that jumble up my original code.
here is the code:
package chpt5_project;
import java.util.Scanner;
public class chpt5_project {
//variables
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count1 = input.nextInt();
while (count1 > 70 || count1 < 30){
System.out.println("Enter a value between 30 and 70: ");
input.close();
}
}
}

Move input.nextInt() into the while loop and don't close input until after the loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count1 = 0;
while (count1 > 70 || count1 < 30){
System.out.print("Enter a value between 30 and 70: ");
count1 = input.nextInt();
}
input.close();
}

// no need to close Scanner for System.in
Scanner scan = new Scanner(System.in);
// create an loop
while (true) {
System.out.print("Enter a value between 30 and 70: ");
int num = scan.nextInt();
// exit the loop if number is correct
if (num > 30 && num < 70)
break;
}

Related

How to apply operations on scanner inputs in java?

I have the following code:
import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = keyboard.nextDouble();
while (go){
String next = keyboard.next();
if (next.equals("done") || next.equals("calculate")){
System.out.print(grade);
go = false;
}else{
grade+=keyboard.nextInt();
}
}
I am trying to find the average as it is a grade calculator, what i want to know is how would I apply The addition operation only to scanner inputs, and then ultimately find the average by how mnay inputs were entered.
Sample input:
60
85
72
done
Output:
72 (average) ===> (217/3)
You need a counter (e.g. count as shown below). Also, you need to first check the input if it is done or calculate. If yes, exit the program, otherwise parse the input to int and add it to the existing sum (grade).
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = 0;
int count = 0;
while (go) {
String next = keyboard.nextLine();
if (next.equals("done") || next.equals("calculate")) {
go = false;
} else {
grade += Integer.parseInt(next);
count++;
}
}
System.out.println((int) (grade / count) + " (average) ===> (" + (int) grade + "/" + count + ")");
}
}

Input a number until -1

Create a program that asks the user to input numbers (integers). The program prints "Type numbers” until the user types the number -1. When the user types the number -1, the program prints "Thank you and see you later!" and ends.
This is the code:
import java.util.Scanner;
public class TheSumOfSetOfNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number=0, sum=0, count=0, even=0, odd=0;
double average=0;
System.out.println("Type numbers: ");
while(true)
{
number=Integer.parseInt(reader.nextLine());
if(number==(-1)) break;
}
}
When I check it, this is the error :
remember to read user input with Integer.parseInt( reader.nextLine() );
call it only once!
If I only call it once, how it will be possible to scan a lot numbers?
This is what you will use in this scenario. Using a do while loop, you can get your output
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int num = 0;
do {
System.out.println("Enter Numbers");
num = scan.nextInt();
} while (num != -1);
System.out.println("Thanks ! See you later");
}
Note: This runs until the user enters -1:
while (reader.hasNextLine()) {
number = Integer.parseInt(reader.nextLine());
if (number == -1) {
System.out.println("Thank you and see you later!");
break;
}
}
If you are always typing numbers I will use this:
final Scanner scanner = new Scanner(System.in);
boolean exit = false;
System.out.println("Type numbers:");
while (!exit){
if (scanner.nextInt() != -1)
exit = true;
}
System.out.println("Thank you and see you later!");
But you have to call scanner object each time you would like to read something from the imput.
You need to put System.out.println("Type numbers: "); inside while loop.
Since you are giving only integers as input, no need to parse it.
Below is required code:
import java.util.Scanner;
public class TheSumOfSetOfNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number=0, sum=0, count=0, even=0, odd=0;
double average=0;
// we need to loop "Type numbers:" each time umtil "-1" is pressed
while(number != -1)
{
System.out.println("Type numbers: ");
number=reader.nextInt();
}
// user must have been typed "-1" therefore it exits from whle loop
System.out.println("Thank you and see you later!");
// now there is nothing in main() fxn, therefore, the program will stop
}
}
Output:
Type numbers:
1
Type numbers:
3
Type numbers:
8
Type numbers:
9
Type numbers:
0
Type numbers:
-1
Thank you and see you later!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = -1;
do {
System.out.println("Welcome to Java Programming!");
System.out.println("Print Again? (y/n)");
num = input.nextLine();
} while (num.equalsIgnoreCase(-1));
}
}
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int flag=0,n;
while(flag!=1){
n=sc.nextInt();
if(n==-1){
flag=1;
}
}
System.out.print("Thank you and see you later!");
}
}

How do I add the ability for the program to continue even after the first input is given?

I'm writing a Hailstone Sequence program and I want to add the ability for the program to keep calculating even after the first input and output is already printed. Basically, instead of re-running the program, you could keep giving inputs.
public class HailStoneSequence {
static Scanner MyScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter a number to generate the Hailstone Sequence for that number. ");
int num = MyScanner.nextInt(); //Taking input from user
while (num>1)
{
if (num%2 == 0)
{
num /= 2;
System.out.print(num+" ");
}
else
{
num = (num*3)+ 1;
System.out.print(num+" ");
}
}
}
}
Just surround the block of code with a while loop that checks if the input is for example 0, in that case 0 would mean the end of the execution.
import java.util.Scanner;
public class HailStoneSequence {
static Scanner MyScanner = new Scanner(System.in);
public static void main(String[] args) {
int num = 1;
while(num != 0) {
System.out.println("Enter a number to generate the Hailstone Sequence for that number. ");
num = MyScanner.nextInt(); //Taking input from user
while (num>1)
{
if (num%2 == 0)
{
num /= 2;
System.out.print(num+" ");
}
else
{
num = (num*3)+ 1;
System.out.print(num+" ");
}
}
}
}
}
You can use a while loop to keep your program running like so:
System.out.println("Enter a number to generate the Hailstone Sequence for that number:(0 to quit) ");
int num = MyScanner.nextInt(); //Taking input from user
while(num != 0){
//logic
System.out.println("Enter a number to generate the Hailstone Sequence for that number:(0 to quit) ");
num = MyScanner.nextInt(); //Taking input from user
}
Then at the end of your logic take the input again. the program will continue to run until the user enters a key(in this case, 0)
You can do something like this:
String input = "";
do {
// Your code here
System.out.println("Continue?");
input = MyScanner.next();
} while (!input.equals("exit");

cannot catch the exception more than one time

when running the code, if I input any character other than number, the exeception "java.util.InputMismatchException" gets catched, but next time if I input any character other than number, the program gets terminated with error "Exception in thread "main" java.util.InputMismatchException". how to make it able to catch more than one simultaneous exceptions untill a valid input is given.
/*
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the
student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses
in an integer array and determine the frequency of each rating.
*/
import java.util.Scanner;
public class StudentPoll
{
static Scanner input=new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Rate the quality of food from 1 to 5." +
"\n1 being “awful” and 5 being “excellent”.\n");
int[] array=new int[10];
int num =0;
for(int i=0;i<array.length;i++)
{
do{
System.out.println("Student "+(i+1)+" Enter Your Response:");
try
{
num=input.nextInt();
}
catch(java.util.InputMismatchException e)
{
System.out.println("Enter numbers only.");
input.nextLine();
num=input.nextInt();
}
if(num<=0 || num>5)
{
System.out.println("Enter 1 to 5 only.");
}
}while(num<=0 || num>5);
array[i]=num;
}
int[] frequency=new int[6];
for ( int i = 0; i < array.length; i++ )
{
frequency[array[i]]=frequency[array[i]]+1;
}
System.out.printf("* :%d (awful)\n",frequency[1]);
System.out.printf("** :%d\n",frequency[2]);
System.out.printf("*** :%d\n",frequency[3]);
System.out.printf("**** :%d\n",frequency[4]);
System.out.printf("*****:%d (excellent)\n",frequency[5]);
}
}`
Because when first exception occur in the try block that is caught by the catch block. And if the user again give a invalid input then again the exception thrown. But there is no mechanism in your code to catch that exception. Therefore the main thread stopped. Catch block will not responsible to catch exception that is throw inside that block.
import java.util.Scanner;
public class StudentPoll
{
static Scanner input=new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Rate the quality of food from 1 to 5." +
"\n1 being “awful” and 5 being “excellent”.\n");
int[] array=new int[10];
int num =0;
for(int i=0;i<array.length;i++)
{
do{
System.out.println("Student "+(i+1)+" Enter Your Response:");
try
{
num=input.nextInt();
}
catch(java.util.InputMismatchException e)
{
input.next(); // consume the leftover new line
System.out.println("Enter numbers only.");
}
if(num<=0 || num>5)
{
System.out.println("Enter 1 to 5 only.");
}
}while(num<1 || num>5); // change in the logic
array[i]=num;
}
int[] frequency=new int[6];
for ( int i = 0; i < array.length; i++ )
{
frequency[array[i]]=frequency[array[i]]+1;
}
System.out.printf("* :%d (awful)\n",frequency[1]);
System.out.printf("** :%d\n",frequency[2]);
System.out.printf("*** :%d\n",frequency[3]);
System.out.printf("**** :%d\n",frequency[4]);
System.out.printf("*****:%d (excellent)\n",frequency[5]);
}
}
Your Problem statements is after the wrong input the program doesn't wait for next user input
You can achieve this my accepting the input via java.util.Scanner & making for loop within do while.
try the below code it should work as per your need.
/*
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the
student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses
in an integer array and determine the frequency of each rating.
*/
import java.util.Scanner;
public class StudentPoll {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Rate the quality of food from 1 to 5."
+ "\n1 being “awful” and 5 being “excellent”.\n");
int[] array = new int[10];
int num = 0;
do {
for (int i = 0; i < array.length; i++) {
System.out.println("Student " + (i + 1)
+ " Enter Your Response:");
Scanner sc = new Scanner(System.in);
try {
num = sc.nextInt();
} catch (java.util.InputMismatchException e) {
System.out.println("Enter numbers only.");
num = 0;
--i;
continue;
}
if (num <= 0 || num > 5) {
System.out.println("Enter 1 to 5 only.");
num = 0;
--i;
continue;
}
array[i] = num;
}
} while (num <= 0 || num > 5);
int[] frequency = new int[6];
for (int i = 0; i < array.length; i++) {
frequency[array[i]] = frequency[array[i]] + 1;
}
System.out.printf("* :%d (awful)\n", frequency[1]);
System.out.printf("** :%d\n", frequency[2]);
System.out.printf("*** :%d\n", frequency[3]);
System.out.printf("**** :%d\n", frequency[4]);
System.out.printf("*****:%d (excellent)\n", frequency[5]);
}
}
Because you do not have another try-catch statement in your catch statement, you can just re-run the loop if you want to catch the exception again. So you would replace:
catch(java.util.InputMismatchException e)
{
System.out.println("Enter numbers only.");
input.nextLine();
num = input.nextInt();
}
with:
catch(java.util.InputMismatchException e)
{
System.out.println("Enter numbers only.");
input.nextLine();
continue;
}

input number of students java program

I need help making a program that will take the int input of the user as the number of students. At the moment I have to manually add the students in the code if I want more student. ive added my other class aswell. please help if possible.
import java.util.Scanner;
// the name of our class its public
public class ClassArray {
//void main
public static void main (String[] args){
//declare class
Student[] s = new Student[2];
s[0] = new Student();
s[1] = new Student();
//call functions
s[0].getdata();
s[1].getdata();
s[0].finalmark();
s[1].finalmark();
s[0].finalgrade();
s[1].finalgrade();
System.out.printf("Name\tDefinitive\tLetter\tTest 1\tTest 2\tAssignments\tFinalExam \n");
s[0].print();
s[1].print();
}
}
}
//declare class
public static class Student {
//declare variables.
private Double finalmark;
private int test1,test2,assignments1,finalexam;
private String studentname,finalgrade;
//functions should be public if needed to access from other class
public void getdata()
{
//print message to enter numbers
Scanner input = new Scanner(System.in);
System.out.println("Enter name of student:");
studentname = input.next();
while (!studentname.matches("[a-zA-Z]+")) { // Checks to see if only letters are used in the name
System.out.println("Please re-enter your name, use alphabets only");
studentname = input.nextLine(); // if anything other than letters are used, the user must re-enter his/her name using letters
}
System.out.println("Enter mark test 1 for student:");
test1 = input.nextInt();
while (test1 > 100 || test1 < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next();
}
test1 = input.nextInt();
}
System.out.println("Enter mark test 2 for student:");
test2 = input.nextInt();
while (test2 > 100 || test2 < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next() ;
}
test2 = input.nextInt();
}
System.out.println("Enter mark assignments for student:");
assignments1 = input.nextInt();
while (assignments1 > 100 || assignments1 < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next() ;
}
assignments1 = input.nextInt();
}
System.out.println("Enter mark final exam for student:");
finalexam = input.nextInt();
while ( finalexam > 100 || finalexam < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next() ;
}
finalexam = input.nextInt();
}
}
public void finalmark(){
finalmark = (test1 * 0.15) + (test2 * 0.25) + (assignments1 * 0.25) + (finalexam *
0.35);
}
public void finalgrade()
{
if(finalmark >= 100)
finalgrade="A+";
else if(finalmark >= 90)
finalgrade="A+";
else if(finalmark >= 80)
finalgrade="A";
else if(finalmark >= 75)
finalgrade="B+";
else if(finalmark >= 70)
finalgrade="B";
else if(finalmark >= 65)
finalgrade="C+";
else if(finalmark >= 60)
finalgrade="C";
else if(finalmark >= 50)
finalgrade="D";
else
finalgrade="F";
}
public void print(){
System.out.printf("%s\t%.2f\t%s\t%d\t%d\t%d\t\t%d\n", studentname, finalmark,
finalgrade, test1, test2, assignments1, finalexam);
}
}
Something like this:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Number of Students:\t");
int numStudents = Integer.parseInt(scanner.nextLine());
Your complete code would be:
import java.util.Scanner;
public class ClassArray {
public static void main (String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Number of Students:\t");
int numStudents = Integer.parseInt(scanner.nextLine());
Student[] s = new Student[numStudents];
for(int i = 0; i < numStudents; i++ ){
s[i] = new Student();
s[i].getdata();
s[i].finalmark();
s[i].finalgrade();
}
System.out.printf("Name\tDefinitive\tLetter\tTest 1\tTest 2\tAssignments\tFinalExam \n");
//Here it will iterate and print out the stored data as soon as the user has finished adding it.
for(int j = 0; j < numStudents; j++ ){
s[j].print();
}
}
Simply,
import java.util.Scanner;
public class ClassArray {
public static void main (String[] args) {
Scanner input= new Scanner(System.in); // create Scanner object
System.out.print("Enter The Number of Students: ");
int numOfStudents = input.nextInt(); // input an integer value
// do whatever you like
}// Ends main
}
Here I created an object of class Scanner as input and I've called the method nextInt() by the object of class Scanner (input).
See this post for user input: How can I get the user input in Java?
You also should not use an array which you have defined as having a set number of elements, in your example 2. Instead, consider an ArrayList of objects type Student which for your purposes can accept any number of Students.
ArrayList<Student> s = new ArrayList<Student>();
//Example add student
Student student1 = new Student();
s.add(student1);
See this post for ArrayList: Java: ArrayList of String Arrays

Categories