My program wont catch an exception - try-catch

Why wont this code catch the error if the user inputs a negative number?
public class Lab12 {
public static void main(String[] args) {
Course[] course1 = courses();
print(course1);
}//end main
public static Course[] courses() throws IllegalArgumentException{
Scanner input = new Scanner(System.in);
System.out.println("How many courses?");
int numCourses = input.nextInt();
Course[] array = new Course[numCourses];
int s = 0;
boolean b = true;
for(int i = 0; i<numCourses; i++){
System.out.println("Enter the course title.");
String t = input.nextLine();
t = input.nextLine();
System.out.println("Enter the corresponding major.");
String m = input.nextLine();
do{
try{
System.out.println("Enter the number of students taking this course.");
s = input.nextInt();
b = false;
}//end try block
catch(IllegalArgumentException ex){
System.out.println("Input error."+
"\nPlese enter a positive number for students.");}//end catch
}while(b);
//Right here I dont see why my try catch wont work
Course c = new Course(t,m,s);
array[i] = c;
}//end for loop
input.close();
return array;
}//end courses method
public static void print(Course[] c){
for(int i = 0; i<c.length; i++){
System.out.println("Course title: "+c[i].getTitle()+
"\nMajor: "+c[i].getMajor()+
"\nNumber of Students: "+c[i].getStudents());
}//end for loop
}//end
}//end lab12
Here is the class associated with the main:
public class Course {
private String title;
private String major;
private int students;
public Course(String t, String m, int s){
title = t;
major = m;
students = s;
if(students<0){
throw new IllegalArgumentException("Wrong Argument.");
}
//my instruction were to throw an exception in the constructor is this correct
}//end constructor method
public String getTitle(){
return title;
}//end get title
public String getMajor(){
return major;
}//end get major
public int getStudents(){
return students;
}//end get students
public void setTitle(String t){
title = t;
}//end set title
public void setMajor(String m){
major = m;
}//end set major
public void setStudents(int s){
students = s;
}//end set students
}//end Class Course

In order to catch an exception in Java, you need to surround the code that throws the exception in a try/catch block.
Change your main for loop to something like this:
for(int i = 0; i<numCourses; i++){
System.out.println("Enter the course title.");
String t = input.nextLine();
t = input.nextLine();
System.out.println("Enter the corresponding major.");
String m = input.nextLine();
// Need to declare the Course object outside of the do/while so that it stays
// in scope afterwards
Course c = null;
do{
try{
System.out.println("Enter the number of students taking this course.");
s = input.nextInt();
b = false;
// Create the Course here so that the try/catch will correctly catch
// the IllegalArgumentException
c = new Course(t,m,s);
}//end try block
catch(IllegalArgumentException ex){
System.out.println("Input error."+
"\nPlease enter a positive number for students.");
}//end catch
} while(b);
array[i] = c;
}//end for loop

Related

It should continue to accept a price of an item and displays the current total while the user input is not equals to zero

/* I need some help. I'm stuck with this code. It should continue to accept a price of an item and displays the current total while the user input is not equal to zero. However, output for the current total won't show the current amount. */
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String customerName;
char promtSenior;
int num = 1;
double itemPrice;
double currentTotal = 0;
ArrayList<Double> amounts = new ArrayList<Double>();
System.out.print("Please enter customer name: ");
customerName = scanner.nextLine();
while (true) {
System.out.print("Please enter item " + num++ + " price or 0 to quit: ");
itemPrice = scanner.nextDouble();
amounts.add(itemPrice);
scanner.nextLine();
for (double i : amounts) {
currentTotal = currentTotal + i ;
}
System.out.println(currentTotal);
if (itemPrice == 0) {
System.out.println("Are you a Senior Citizen? [Y/N]: " + customerName);
promtSenior = scanner.next().charAt(0);
if (promtSenior == 'N') {
System.out.println("No Discount");
}
}
}
}
}
while (true) {
System.out.print("Please enter item " + num++ + " price or 0 to quit: ");
itemPrice = scanner.nextDouble();
amounts.add(itemPrice);
scanner.nextLine();
for (double i : amounts) {
currentTotal = currentTotal + i ;
System.out.println(currentTotal);
}
should be this as previously you where printing the total after the for loop not during
i think you accidentally messed up your curly brackets and indented before

Have loop repeat after invalid entry

All calculating is fine. I run into a problem when I get an invalid entry and the user enters a new positive integer. It doesn't start the loop over again. Any advice is greatly appreciated!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int start;
int i;
double squareRoot;
System.out.println("Please enter a positive integer: ");
start = in.nextInt();
if (start > 0){
do {
squareRoot = Math.sqrt(start);
start--;
System.out.printf("%.4f", squareRoot);
System.out.println();
}
while (start >= 0);
}
else {
System.out.println("The number you entered is not a postive integer.");
System.out.println("Please enter an integer greater than zero: ");
start = in.nextInt();
}
}
}
If you need to go over the same steps over and over, you need a loop. So add a while loop with a simple condition and get it going over and over.
Here is a sample code. I had to give an option to quit, so took -1 as the cue.
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int start;
int i;
double squareRoot;
System.out.println("Please enter a positive integer: ");
boolean quit = false;
while (!quit) {
System.out.println("Enter the integer");
start = in.nextInt();
if (start > 0){
do {
squareRoot = Math.sqrt(start);
start--;
System.out.printf("%.4f", squareRoot);
System.out.println();
}
while (start >= 0);
}
else if (start == -1) {
quit = true;
}
else {
System.out.println("The number you entered is not a postive integer.");
System.out.println("Please enter an integer greater than zero: ");
}
}
}
}

This loop to modify a arraylist of numbers based on arraylist of strings isnt working

So, in my program you input employee information and the salary you input depends on what you input for designation. If temporary, yo input how much they make per hour, if permanent you input what they make per year. At the end, you have the option to sort by salary, so if they choose that then I must multiply the temporary's per-hour by a set number (1920) in order to convert it to what they make per year. I tried this but I got the messages
" The type of the expression must be an array type but it resolved to java.util.ArrayList"
and "The type of the expression must be an array type but it resolved to java.util.ArrayList", I got that second one twice.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String Continue = "y";
int Count = 0;
int SortingChoice;
ArrayList<String> Names = new ArrayList<String>();
ArrayList<String> Department = new ArrayList<String>();
ArrayList<String> Designation = new ArrayList<String>();
ArrayList<Float> Salary = new ArrayList<Float>();
//******************************************************//
do
{
System.out.println("Enter Employee Name: ");
String x = in.next();
Names.add(x);
System.out.println("Enter Employee Designation ('temporary or permanent'): ");
String y = in.next();
Designation.add(y);
System.out.println("Enter Employee Department: ");
String z = in.next();
Department.add(z);
System.out.println("Enter Employee Salary: ");
float i = in.nextFloat();
Salary.add(i);
System.out.println("Do you wish to add another employee? ('y'/'n'): ");
Continue = in.next();
Count = Count + 1;
}
while(Continue.equals("y"));
//***********************************************************************//
System.out.println("Enter sorting Criterion Number: 1. Name, 2.Department, 3. Salary. ");
SortingChoice = in.nextInt();
if(SortingChoice == 1)
{
Collections.sort(Names);
for(int i=0; i<Names.size(); i++)
{
System.out.println(Names.get(i));
}
}
if(SortingChoice == 2)
{
Collections.sort(Department);
for(int i=0; i<Department.size(); i++)
{
System.out.println(Department.get(i));
}
}
if(SortingChoice == 3)
{
for(int k=0; k<Salary.size(); k++)
{
if(Designation[k].equals("temporary"))
{
Salary[k] = Salary[k]*1920;
}
}
Collections.sort(Salary);
for(int i=0; i<Salary.size(); i++)
{
System.out.println(Salary.get(i));
}
}
}
What I am most concered about if the loop under if(SortingChoice==3)

reached end of file while parsing,

what is wrong with this , i am getting an error that states: reached end of file while parsing. what do i do to fix this?
i have tried several thing with no result
public class FindMin
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int smallest = 9999999;
String userInput;
boolean quit = false;
System.out.println("This program finds the smallest number"
+ " in a series of numbers");
System.out.println("When you want to exit, type Q");
while(quit != true)
{
System.out.print("Enter a number: ");
userInput = keyboard.next();
if(userInput.equals("Q")) userInput.equals("q");
{
if(quit == true) {
}
else
{
int userNumber = Integer.parseInt(userInput);
if(UserNumber < smallest)
smallest = userNumber;
}
}
System.out.println("The smallest number is " + smallest);
System.exit(0);
}
Check your braces: they don't match up, which is why the compiler complains:
FindMin.java:35: reached end of file while parsing
Besides there's a typo and some other issues with that program. See other answers for reference :)
It was just too messy, try this
import java.util.Scanner;
public class FindMin{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int smallest = 9999999;
String userInput;
boolean quit = false;
System.out.println("This program finds the smallest number"
+ " in a series of numbers");
System.out.println("When you want to exit, type Q");
while(true)
{
System.out.print("Enter a number: ");
userInput = keyboard.next();
if(userInput.equalsIgnoreCase("q"))
break;
else{
int userNumber = Integer.parseInt(userInput);
if(userNumber < smallest)
smallest = userNumber;
}
}
System.out.println("The smallest number is " + smallest);
}
}

Replacing already printed numbers in C

I am writing a program in C language which is an India Game called Thambola(similar to Bingo).
In this game the user gets a 3x9 ticket and the computer asks the user to enter the number which the second program(this picks numbers randomly from 1-90) picked. If the entered number exists in the ticket, the number should be changed to 'x' meaning the number has been stricken off. I need help here. How to replace an already printed number with 'x'? i read this C - Remove and replace printed items but it doest help because i have 27 numbers to be changed.Please help me. Here is the part of the code:
int number,i,j;
const char x='x';
printf("\nEnter the number:");
scanf("%d",&number); // number entered by the user from the Picker
for (i=0;i<3;i++)
for (j=0;j<9;j++)
{if (ticket[i][j]==number)
ticket[i][j]=x;
printf("%d",ticket[i][j]); //if the input number is present in the ticket, this should change it to 'x
}
getchar();
}
Main problem of your code snippet is your logic behind assigning values to variables.
As anyone can see, you have an array of integers but you want to assign a char to one of its elements. Actually you can do it by casting, but the result will be the ASCII value of the 'x'.
{if (ticket[i][j]==number) // number is an integer
ticket[i][j]=x; // x is a char
Since 'x' has the ASCII value of 120,which is out of range from the possible numbers in the ticket, you can safely cast 'x' to its integer value and then assign it to its array element. In printing, if you see 120 print 'x'.
In the situations where your char's integer value is in the range of the other possible integer values, pick another integer value and treat this value as 'x' in logic flow (for example, pick 0 for the corresponding integer, if 0 comes print 'x').
You can use ncurses or simply print a ticket state then clear the screen just before printing modified ticket for output.
public class sample1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<int[]> outer = new ArrayList<int[]>(9);
List<int[]> inner = new ArrayList<int[]>(9);
int[][] final_arr = new int[9][18];
int[][][] final_arr2 = new int[6][3][9];
int[][] multi = new int[][]{
{2,3,5,7,9,12,13,15,17},
{1,3,4,5,6,7,11,14,16,18},
{1,2,4,6,8,9,12,13,17,18},
{3,5,7,9,10,11,12,14,15,16},
{1,4,6,7,8,10,11,13,14,18},
{2,3,5,8,9,12,13,15,16,17},
{1,2,4,6,7,10,11,13,17,18},
{1,3,5,8,9,12,13,15,16,18},
{2,4,6,7,9,10,11,14,15,16,17}
};
for( int i=0;i<9;i++){
outer.add(multi[i]);
}
for(int x=0;x<9;x++){
int [] temp = new int[18];
for(int k=0;k<outer.get(x).length;k++){
//System.out.print(outer.get(x)[k]-1 +" ");
int row = outer.get(x)[k]-1;
temp[row]=1;
}
//System.out.println();
inner.add(temp);
}
System.out.println();
int count=1;
for(int i=0;i<9;i++){
List<Integer> temp = new ArrayList<Integer>();
for(int k=0;k<outer.get(i).length;k++){
temp.add(count);
count++;
}
Collections.shuffle(temp);
int index_of_temp=0;
for(int j=0;j<18;j++){
if(inner.get(i)[j]==1){
inner.get(i)[j]=temp.get(index_of_temp);
index_of_temp++;
}
//System.out.print(inner.get(i)[j]+ " ");
}
//System.out.println();
}
for(int i=0;i<9;i++){
for(int j=0;j<18;j++){
final_arr[i][j]=inner.get(i)[j];
}
}
System.out.println();
for(int i=0;i<18;i++){
for(int j=0;j<9;j++){
//System.out.print(final_arr[j][i]+ " ");
final_arr2[i/3][i%3][j]=final_arr[j][i];
}
}
for(int k=0;k<6;k++){
for(int i=0;i<3;i++){
for(int j=0;j<9;j++){
System.out.print(final_arr2[k][i][j]+ " ");
}
System.out.println();
}
System.out.println();
}
}
}

Resources