[Go to site: main page, start]

0% found this document useful (0 votes)
17 views12 pages

Java Scanner Input and Usage Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views12 pages

Java Scanner Input and Usage Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1)Write a program to input your roll no, name, age, fees paid, sex from keyboard and

print them.(Use of Scanner class and BufferedReader class)

import [Link];

public class StudentInfo {

public static void main(String[] args)


{
Scanner scanner = new Scanner([Link]);

[Link]("Enter your roll number: ");


int rollNo = [Link]();

[Link](); // To consume the newline left by nextInt()

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Enter fees paid: ");


double feesPaid = [Link]();

[Link](); // To consume the newline left by nextDouble()

[Link]("Enter your sex (M/F): ");


char sex = [Link]().charAt(0);

[Link]("\nStudent Details:");
[Link]("Roll Number: " + rollNo);
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Fees Paid: " + feesPaid);
[Link]("Sex: " + sex);

[Link]();
}
}
2)Write a program to check and print the first Armstrong number starting from your roll
no. Take input from the command line arguments.

import [Link];
public class armstrong
{

public static void main(String[] args)


{

int n,arm=0,r,c;
Scanner scanner = new Scanner([Link]);

[Link]("Enter 3 Digit Number");


n= [Link]();
[Link]();
c=n;

while(n>0)
{
r=n%10;
arm=(r*r*r)+arm;
n=n/10;
}

if(c == arm)
[Link](" Armstrong number");
else
[Link](" not Armstrong number");
}
}

3)Write a program to display following patterns


A
AB1
ABC22
ABCD333

import [Link];
public class PatternDisplay {
public static void main(String[] args) {
int rows = 4; // Number of rows in the pattern

for (int i = 0; i < rows; i++) {


// Print leading spaces
for (int j = rows - 1; j > i; j--) {
[Link](" "); // Two spaces for alignment
}
for (char ch = 'A'; ch <= 'A' + i; ch++) {
[Link](ch + " ");
}

for (int j = 1; j <= i; j++) {


[Link](i + " "); // Print the row number (1-based)
}
[Link]();
}
}
}
4)Write a program to create class that stores a string and all its status details such as
number of upper case characters, vowels, and so on

import [Link];

public class StringStatus {

static int upper = 0, lower = 0, number = 0, spaces = 0, special = 0;

StringStatus(String str){

for (int i = 0; i < [Link](); i++)

char ch = [Link](i);

if (ch >= 'A' && ch <= 'Z')

upper++;

else if (ch >= 'a' && ch <= 'z')

lower++;

else if (ch >= '0' && ch <= '9')

number++;

else if (ch == ' ')

spaces++;

else

special++;

[Link]("Lower case letters : " + lower);

[Link]("Upper case letters : " + upper);

[Link]("Number : " + number);

[Link]("Spaces : " + spaces);

[Link]("Special characters : " + special);


}
public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");

String str = [Link]();

new StringStatus(str);

}
}
5)Write a program to calculate the area of different shapes (circle, triangle, rectangle,
square) by using method overloading

import [Link].*;

class Area {
double area(int r) {
return 3.14 * r * r;
}

double area(int b, float h) {


return (b * h) / 2;
}

double area(float s) {
return s * s;
}

double area(int w, int l) {


return w * l;
}
}

public class AreaCalculator {


public static void main(String[] args) {
int r, b, w, l;
float h, s;
Scanner sc = new Scanner([Link]);

[Link]("Enter radius: ");


r = [Link]();

[Link]("Enter base: ");


b = [Link]();

[Link]("Enter height: ");


h = [Link]();

[Link]("Enter side of square: ");


s = [Link]();

[Link]("Enter length: ");


l = [Link]();

[Link]("Enter width: ");


w = [Link]();

Area ac = new Area();

[Link]("Area of circle: " + [Link](r));


[Link]("Area of triangle: " + [Link](b, h));
[Link]("Area of square: " + [Link](s));
[Link]("Area of rectangle: " + [Link](w, l));

[Link](); }
}
7)Write a program to perform matrix multiplication and transpose of a matrix.

import [Link];
public class matrix {
public static void main(String[] args) {
int[][] mat = new int[2][2];
int[][] trans = new int[2][2];
Scanner sc = new Scanner([Link]);
[Link]("Enter matrix elements (2x2):\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
mat[i][j] = [Link]();
}
}

// Display the original matrix


[Link]("Matrix elements:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
[Link](mat[i][j] + " ");
}
[Link]();
}

// Calculate the transpose


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
trans[j][i] = mat[i][j]; }
}

[Link]("Transpose of the matrix:");


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
[Link](trans[i][j] + " ");
}
[Link]();
}

[Link](); }
}
10)Create class Student (Roll No, name), class Test(Marks1,Marks2) inherits Student class.
Create class Result which extends Test and has a method named Calculate which finds total
as (Total=Marks1+Marks2) and method which display all the details.

import [Link];
interface Test
{
void totalmarks();
}

class Student
{
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2)
{
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display()
{
[Link] ("Name of Student: "+name);
[Link] ("Roll No. of Student: "+roll_no);
[Link] ("Marks of Subject 1: "+mark1);
[Link] ("Marks of Subject 2: "+mark2);
}
}

class Result extends Student implements Test


{
Result(String n, int r, int m1, int m2)
{
super(n,r,m1,m2);
}
public void totalmarks()
{
int total=(mark1+mark2);
[Link] ("Total Marks: "+total);
}
void display()
{
[Link]();
}
}

public class MultipleInh


{
public static void main(String[] args)
{
Result R = new Result("Shravan",36,85,87);
[Link]();
[Link]();
}}
11)Create an Interface ‘Vehicle’ which has abstract methods changeGear(),
speedUp(),applyBrakes().Create a classes like ‘Bike’ ,’Car’ which will implement
functionality of ‘Vehicle’ in their own way
import [Link];

interface Vehicle
{

void changeGear(int a);

void speedUp(int a);

void applyBrakes(int a);

class Bicycle implements Vehicle


{

int speed;

int gear;

@Override

public void changeGear(int newGear){

gear = newGear;

@Override

public void speedUp(int increment){

speed = speed + increment;

@Override

public void applyBrakes(int decrement){

speed = speed - decrement;

public void printStates() {

[Link]("speed: " + speed

+ " gear: " + gear);

class Bike implements Vehicle {

int speed;

int gear;

@Override
public void changeGear(int newGear){

gear = newGear;

@Override

public void speedUp(int increment){

speed = speed + increment;

@Override

public void applyBrakes(int decrement){

speed = speed - decrement;

public void printStates() {

[Link]("speed: " + speed

+ " gear: " + gear);

class PresentState {

public static void main (String[] args) {

Bicycle bicycle = new Bicycle();

[Link](2);

[Link](3);

[Link](1);

[Link]("Bicycle present state :");

[Link]();

Bike bike = new Bike();

[Link](1);

[Link](4);

[Link](3);

[Link]("Bike present state :");

[Link]();

}
12) Create a abstract class AbstractSum which has abstract methods sumofTwo() and
sumofThree().Create a class Sum which extends AbstractSum and implement its methods.

import [Link];
abstract class AbstractSum {
abstract int sumOfTwo(int a, int b);

abstract int sumOfThree(int a, int b, int c);


}

class Sum extends AbstractSum {

int sumOfTwo(int a, int b) {


return a + b;
}

int sumOfThree(int a, int b, int c) {


return a + b + c;
}
}
public class abstractMain {
public static void main(String[] args) {
Sum sum = new Sum();

int result1 = [Link](5, 10);


[Link]("Sum of two numbers (5 + 10): " + result1);

int result2 = [Link](5, 10, 15);


[Link]("Sum of three numbers (5 + 10 + 15): " + result2);
}
}

13)Write a program to create your own exception. The exception will be thrown if number
is odd.
class OddNumberException extends Exception {
public OddNumberException(String message) {
super(message);
}
}
public class CustomExceptionExample {
static void checkEven(int number) throws OddNumberException {
if (number % 2 != 0) {
throw new OddNumberException("The number " + number + " is odd.");
} else {
[Link]("The number " + number + " is even.");
}
}

public static void main(String[] args) {


int[] numbers = {2, 3, 4, 5, 6};
for (int number : numbers) {
try {
checkEven(number);
} catch (OddNumberException e) {
[Link]([Link]());
}
}
15)Write a program to print table of any number using Synchronized method.

import [Link];
class Table {

synchronized void printTable(int number) {


for (int i = 1; i <= 10; i++) {
[Link](number + " x " + i + " = " + (number * i));
try {
[Link](500);
}
catch (InterruptedException e) {
[Link](e);
}
}
}
}

class TableThread extends Thread {


Table table;
int number;

TableThread(Table table, int number) {


[Link] = table;
[Link] = number;
}

public void run() {


[Link](number);
}
}

public class SynchronizedTable {


public static void main(String[] args) {
Table table = new Table();

TableThread thread1 = new TableThread(table, 5);


TableThread thread2 = new TableThread(table, 10);

[Link]();
[Link]();
}
}
9)Create a vector Student with their name. Write a program to add, remove and display students name from vector.

import [Link];

import [Link];

public class vector {

public static void main(String[] args) {

Vector<String> students = new Vector<>();

Scanner scanner = new Scanner([Link]);

int choice;

do {

[Link]("\nStudent Management System");

[Link]("1. Add Student");

[Link]("2. Remove Student");

[Link]("3. Display Students");

[Link]("4. Exit");

[Link]("Enter your choice: ");

choice = [Link]();

[Link]();

switch (choice) {

case 1:

[Link]("Enter student name to add: ");

String nameToAdd = [Link]();

[Link](nameToAdd);

[Link](nameToAdd + " has been added.");

break;

case 2:

[Link]("Enter student name to remove: ");

String nameToRemove = [Link]();


if ([Link](nameToRemove)) {

[Link](nameToRemove + " has been removed.");

} else {

[Link](nameToRemove + " not found.");

break;

case 3:

[Link]("List of Students:");

if ([Link]()) {

[Link]("No students in the list.");

} else {

for (String student : students) {

[Link](student);

break;

case 4:

[Link]("Exiting...");

break;

default:

[Link]("Invalid choice. Please try again.");

break;

} while (choice != 4);

[Link]();

Common questions

Powered by AI

The custom exception class 'OddNumberException' is designed to handle odd numbers, extending the 'Exception' class. The 'checkEven' method throws 'OddNumberException' if the given number is odd by checking the modulus condition (number % 2 != 0). In the main method, each number in the array is processed within a try-catch block, catching the custom exception when triggered, and responding accordingly .

The 'Vehicle' interface defines abstract methods—'changeGear', 'speedUp', and 'applyBrakes'—that 'Bike' and 'Bicycle' classes must implement, thereby enforcing these operations while allowing each class to define specific functionality. 'Bike' and 'Bicycle' both implement 'Vehicle', but the underlying state changes (e.g., adjustments to gear and speed) can be tuned uniquely, reflecting polymorphic design. This setup allows distinct operational behaviors despite sharing a common interface .

The 'Scanner' class provides a simpler and more convenient way to parse primitive types and strings from input sources like input streams. It is commonly used for interactive console input due to its ease of use for reading space-separated tokens. In contrast, 'BufferedReader' is often used for reading larger amounts of input and lines of text more efficiently, as it buffers the input and can read a whole line at a time .

The 'interface' defines a contract for classes, specifying methods that must be implemented, but does not contain implementation itself. The 'Test' interface stipulates that implementing classes must define the 'totalmarks' method. Inheritance allows 'Result' to extend 'Student', inheriting attributes and methods, so 'Result' can use 'Student's details directly. 'Result' further implements 'Test' to provide a specific implementation of 'totalmarks'. This design leverages polymorphism and shared behavior while allowing additional behavior through interface implementation .

The 'Vector' class in Java, part of the Collection Framework, is used to store dynamic lists of objects. It provides synchronized methods to add, remove, and manipulate elements. In the program, student names are managed within a 'Vector'. The 'add' method appends a name, 'remove' deletes a specified name after checking its presence, and all names are accessed through iteration for displaying them to the user, using standard input to choose among these operations .

Abstract classes allow providing default method implementations, sharing common state with protected or public fields, and support method and constructor declaration. 'AbstractSum' offers a framework for methods that can have specific implementations in derived classes. However, a class can only extend one abstract class due to Java's single inheritance model, limiting flexibility compared to interfaces that a class might implement multiple of, each allowing behavior extension of varied parts of a system .

Synchronized methods are used in Java to ensure that a particular resource or piece of code is accessed by only one thread at a time, thereby preventing data inconsistency and race conditions. In printing multiplication tables, the 'printTable' method is synchronized to ensure that even if multiple threads are calling this method, only one can execute it at a time. This guarantees that a complete table is printed before another thread starts, avoiding jumbling of output .

In the Java program, matrix multiplication could be achieved by iterating through rows of the first matrix and columns of the second matrix, accumulating products in a result matrix (though not explicitly shown in the code snippets). The transpose operation is implemented by swapping elements across the main diagonal, i.e., switching rows and columns for each element in the matrix, thus storing transposed values in a new matrix .

Method overloading in Java allows multiple methods to have the same name with different parameter lists within the same class. It is used to perform different operations based on the input parameter types. In the given program, method overloading facilitates calculating areas of various shapes like circles, triangles, rectangles, and squares by defining methods with distinct parameter lists for each shape type .

An Armstrong number (also known as a Narcissistic number) is a number that is equal to the sum of its digits each raised to the power of the number of digits. The provided Java program checks for a 3-digit Armstrong number by iterating over each digit, cubing it, and summing the results. If the summed result equals the original number, it confirms that the number is an Armstrong number .

You might also like