Intruduction to JAVA (Practical) Taner ERKAN 2011 By: Andrey Bogdanchikov Page 1 Task1 All task files, first lines, must have descriptive information about you in comments /************************ * Name: Vasya Pupkin * Group: EN1-A-04 * Task: Task1 subtask A * Date: 12.10.2011 ************************/ Deadline 19.10.2011 [Problem A] Write program that reads double numbers A, B and C then finds result of following equation ? Console Sample Enter A:50 Enter B:4 Enter C:14 Result is 100 [Problem B] Write program that asks from user his name and checks if his/her name has ODD or EVEN number of letters. Console Sample Enter your name: Andrey Your name consist of EVEN number of letters [Problem C] Print all numbers from A to B with step 0.5 by use of while statements. A and B is entered from console. Console Sample Enter A: 0 Enter B: 3 0.0 0.5 1.0 1.5 2.0 2.5 3.0 [Problem D] Write program that reads N. Prompts N float numbers and finds MAXIMUM, MINIMUM and MEDIAN value between them. Console Sample Enter N: 5 Enter 1 number: 4.6 Enter 2 number: 1.2 Enter 3 number: -8.2 Enter 4 number: 5.0 Enter 5 number: -3.2 MAXIMUM is 5.0 MINIMUM is -8.2 MEDIAN is -0.12 [Problem E] Create a program that prints and finds sum of all numbers between 1 and 50 that are divisible by 2 or 3 but not divisible by 6.(for cycle) Console Sample Numbers that divisible by 2 or 3 but not 6: 2 3 4 8 9 10 14 15 16 20 21 22 26 27 28 32 33 34 38 39 40 44 45 46 50 Sum is 1275
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 1
Task1
All task files, first lines, must have descriptive information about you in comments
Write program that reads double numbers A, B and C then finds result of following equation
?
Console Sample
Enter A:50 Enter B:4 Enter C:14 Result is 100
[Problem B]
Write program that asks from user his name and checks if his/her name has ODD or EVEN number of letters.
Console Sample
Enter your name: Andrey Your name consist of EVEN number of letters
[Problem C]
Print all numbers from A to B with step 0.5 by use of while statements. A and B is entered from console.
Console Sample
Enter A: 0 Enter B: 3 0.0 0.5 1.0 1.5 2.0 2.5 3.0
[Problem D]
Write program that reads N. Prompts N float numbers and finds MAXIMUM, MINIMUM and MEDIAN value between them.
Console Sample
Enter N: 5 Enter 1 number: 4.6 Enter 2 number: 1.2 Enter 3 number: -8.2 Enter 4 number: 5.0 Enter 5 number: -3.2 MAXIMUM is 5.0 MINIMUM is -8.2 MEDIAN is -0.12
[Problem E]
Create a program that prints and finds sum of all numbers between 1 and 50 that are divisible by 2 or 3 but not divisible by 6.(for cycle)
Console Sample
Numbers that divisible by 2 or 3 but not 6: 2 3 4 8 9 10 14 15 16 20 21 22 26 27 28 32 33 34 38 39 40 44 45 46 50 Sum is 1275
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 2
Task2
All task files, first lines, must have descriptive information about you in comments
Read text from “shortstory.txt” file; change all occurrences of word “SDU” into “Suleyman Demirel University”; then output result to “longstory.txt”
file.
shortstory.txt longstory.txt
I am a student of SDU. I like to study in SDU. I love SDU atmosphere and SDU warmth.
I am a student of Suleyman Demirel University. I like to study in Suleyman Demirel University. I love Suleyman Demirel University atmosphere and Suleyman Demirel University warmth.
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 4
[Problem D]
Create a program that generates 100 random numbers (0<= r <100). Select among them numbers divisible by 2.
Sort and output, first in increasing order then in decreasing order. (Random r = new Random(); int random = r.nextInt(100);)
Create Random N. in range between 1000 and 1000000. Output it. Print all divisors of this number.
Console Sample
Random number: 1013
Divisors: 1 1013
[Problem B(40)]
Fill randomtext.txt with random 1000 letters, CAPITAL or small. Write methods:
a) int numberOfVowels(String a)// that returns number of vowels.
b) boolean isThere SDU(String text)// that checks if in text there word ‘SDU’
c) String longestPalindrome(String line)// that outputs longest palindrome in line.
d) double averageASCII(String all)// finds average ASCII code of all symbols.
Read generated randomtext.txt and apply previous methods on them.
Console Sample
number of vowels: 324 гласная There is word SDU longest Palindrome: ajfgfja Average ASCII is 102.56
[Problem C(20)]
Create class Car that has two fields: type and color. One constructor which creates Object from two String parameters, color should be converted to
small letters and type to capitals. One method that prints text: “This car is #color #type”, where #color and #type are values of corresponding fields.
Create main Class which ask from user to enter parameters of cars, until user enter “no cars”. Output created objects.
Console
Enter car parameters: Blue BMW Enter car parameters: Yellow Zhiguli Enter car parameters: no cars This car is blue BMW This car is yellow ZHIGULI
[Problem D(20)]
Create a program that generates 100 random numbers (0<= r <100).
Create methods that finds maximum digit from any integer.
Sort this numbers by their digits. (i.e number having smallest maximum digit should be first, next after that, and so on) and output them. (if numbers have
same maximum digit then you can place them in any order)
Read multiple line text from file “mupdup.dat” get list of all words from that text.
word - is any set of symbols that is separated by spaces, new line symbols or tabulations.
For each word find (create specific method for each of them):
a) number of Capital letters
b) is Palindrome or not (palindrome is text that is same if you read in reverse order)
c) number of vowels
d) sum of digits if exist
Output result to “mopdop.dat” like it is written in example
mupdup.dat mopdop.dat
I like 11 wow things in university. Wow 1st emotion.
I – 1 Capitals, Palindrome, 1 vowels, 0 is sum like – 0 Capitals, not Palindrome, 2 vowels, 0 is sum 11 – 0 Capitals, Palindrome, 0 vowels, 2 is sum wow – 0 Capitals, Palindrome, 1 vowels, 0 is sum things – 0 Capitals, not Palindrome, 1 vowels, 0 is sum in – 0 Capitals, not Palindrome, 1 vowels, 0 is sum university. – 0 Capitals, not Palindrome, 4 vowels, 0 is sum Wow – 1 Capitals, Palindrome, 1 vowels, 0 is sum 1st – 0 Capitals, not Palindrome, 0 vowels, 1 is sum emotion. – 0 Capitals, not Palindrome, 4 vowels, 0 sum
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 7
[30pt Problem B]
Army
The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the
highest rank.
One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previousi - 1 ranks is impossible.
Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he
can finally realize his dream.
Input
The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two
integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.
Output
Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.
Console Sample
input
3
5 6
1 2
output
5
input
3
5 6
1 3
output
11
[ 40pt Problem C]
Create program that reads from console two numbers N,M. Creates two dimensional array NxM. Realize following methods:
public static void fillRandom(int a[][]); // fill each cell with random number maximum 10
public static int totalSum(int a[][]); // finds total sum of all elements
public static void printArray(int a[][]); // accurately prints two dimensional matrix to screen
public static int[][] sum(int a[][],int b[][]); // sum of two matrixes and return, accepts two identical size matrixes.
public static fillValue(int a[][],int value); // set for each cell given value
Write in main such that all of these methods will be executed (see example):
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 8
Console Sample Enter N: 2
Enter M: 3
Matrix A filled by random values:
6 3 1
3 1 2
Total sum of Matrix A is 16
Sum of matrixes A+A is Matrix B:
12 6 2
6 2 4
Total sum of Matrix B is 32
Printing Matrix A:
6 3 1
3 1 2
Printing Matrix B:
12 6 2
6 2 4
Enter number to fill Matrix A: 3
Fill Matrix A by value 3:
3 3 3
3 3 3
Sum of matrixes A+B is Matrix C:
15 9 5
9 5 7
Total sum of Matrix C is 50
[30pt bonus Problem D]
Create class Complex that has:
Two fields, int real and int imaginary;
Write two constructors, default constructor and constructor with two int arguments;
Write four methods:
1. method print that prints Complex number;
2. method sum that adds two Complex numbers and return results;
3. method subtract that subtracts one Complex from other and return result;
4. method multiply that multiplies two Complex numbers and return Complex number result;
Write Main class that creates objects of Complex numbers and outputs some intermediate results:
Console Number A
Enter real part: 7
Enter imaginary part: 8
Complex A number is:
7 + 8i
Number B
Enter real part: -4
Enter imaginary part: 9
Complex B number is:
-4 + 9i
Sum of A and B is:
3 + 17i
A subtract B is:
11 – 1i
Multiplication of A and B is:
-100 + 31i
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 9
Task6
All task files, first lines, must have descriptive information about you in comments
Однажды к искусному сказочнику дедушке Мефодию, приехал внук Вася. Вася уже слышал от своего папы, что дедушка очень хороший сказочник. И он попросил дудушку Мефодия каждый вечер, перед сном, рассказывать по М сказок, но так чтобы каждая следующая сказка была короче предыдущей. И чтобы М сказок рассказанных в один день отличалась от М сказок остальных дней.
Теперь дед Мефодий гадает сколько же дней у него проживет Вася если он знает всего К сказок.
Все сказки отличаются по длинне.
Формат входных данных
Во входном файле записано два числа K и M. (1 <= K,M <= 20)
Формат выходных данных
Выходной файл должен содержать одно единственное число - количество дней, на сколько хватит деда Мефодия.
Create hierarchy of classes, where class Person is a superclass:
Person has private fields name and surname. Support with needed constructors
Also Person has method whoAmI() that returns String with name and surname.
Student has protected field GPA(assisted by Abdikali) that stores average mark of student, support with corresponding constructors, and
override method whoAmI() that will return text with name, surname and GPA.
Teacher has protected field AdvisingGroup that stores String of group name he is advisor of.
Subclasses of Teacher have static field subjectName.
Subclasses of Student have static field courseNumber
Because all classes are subclasses of Person all of them should override method whoAmI() that will output all possible information about this
object.
Write Main that creates object of each class and executes all possible methods of that objects.
Person
Student
Freshman Sophomore Junior Senior
Teacher
JavaTeacher WebTeacher
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 13
Task 1 A : Answer // Taner ERKAN
import java.util.Scanner; public class A { public static void main(String[]args) { Scanner in = new Scanner(System.in); int A,B,C; double Result; System.out.print("Enter A:"); A = in.nextInt(); System.out.print("Enter B:"); B = in.nextInt(); System.out.print("Enter C:"); C = in.nextInt(); double x=A*B*B; double y=C-6; Result = x/y; System.out.println("Result:"+Result); } }
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 14
Task 1 B : Answer // Taner ERKAN
import java.util.Scanner;
public class B
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter your name:");
String name = in.next();
int c = name.length();
if (c%2==0){
System.out.println("Even");}
else {
System.out.println("Odd");}
}
}
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 15
Task 1 C : Answer // Taner ERKAN
import java.util.Scanner;
public class C
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter A:");
double A = in.nextInt();
System.out.print("Enter B:");
double B = in.nextInt();
while (A<=B) {
System.out.print(A+" ");
A=A+0.5;
}
}
}
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 16
Task 1 D : Answer // Taner ERKAN
import java.math.*;
import java.util.Scanner;
public class D {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter N:");
int N = in.nextInt();
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
for (int x = 1; x<=N ; x++){
System.out.print("Enter "+x+" number:");
double num = in.nextDouble();
if (max <=num)
max = num;
if (min >= num)
min = num;
sum = sum+ num;
}
System.out.println(" MINIMUM is = " + min);
System.out.println(" MAXIMUM is = " + max);
System.out.print(" MEDIAN is = "+(sum/N));
}
}
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 17
Task 1 E : Answer // Taner ERKAN
public class E
{
public static void main(String[]args)
{
int i,sum=0;
for(i=1;i<=50;i++)
{
if ((i%2==0 || i%3==0) && i%6!=0)
System.out.print(i+" ");
sum=sum+i;
}
System.out.println("\n"+"Sum is "+sum);
}
}
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 18
Task 2 A : Answer // Taner ERKAN
import java.util.*;
public class A
{
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter N:");
int N=in.nextInt();
int []a1=new int[N];
for (int i1=0;i1<a1.length;i1++){
a1[i1]=2;}
for (int i1=0;i1<a1.length;i1++){
double c=Math.pow(a1[i1],i1);
System.out.print((int)c+" ");}
System.out.println(Arrays.toString(a1));
}
}
Task 2 B : Answer // Taner ERKAN
import java.util.*;
public class B
{
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
int a1[]=new int[10];
System.out.print("Enter 10 numbers:");
for (int i1=0; i1<10;i1++)
{
int i2=in.nextInt();
a1[i1]=i2;
if (i1%2==0){
a1[i1]=a1[i1]/2;}
else
{a1[i1]=a1[i1]*2;}
System.out.print(a1[i1]+" ");
}
}
}
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 19
Task 2 C : Answer // Taner ERKAN
import java.util.*;
import java.io.*;
public class C{
public static void main(String []args)throws Exception{
Scanner in = new Scanner (new File ("numbers.txt"));
int min= Integer.MAX_VALUE;
int max= Integer.MIN_VALUE;
while (in.hasNextLine())
{
int a=in.nextInt();
if (a<=min) min=a;
if (a>=max) max=a;
}
System.out.println("Min: "+min);
System.out.println("Max: "+max);
in.close();
}
}
//////
Number.txt
4 7 -2 -1 6
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 20
Task 2 D : Answer // Taner ERKAN
import java.util.*;
public class D{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter N:");
int n = in.nextInt();
for (int i = 1; i <= n; i++){
for (int x = 1; x<=n-i; x++)
System.out.print(" ");
for (int y = 1; y<=i*2-1; y++)
System.out.print("*");
for (int x = 1; x<=n-i; x++)
System.out.print(" ");
System.out.println();
}
for (int i = 1; i < n; i++){
for (int x = 1; x<=i; x++)
System.out.print(" ");
for (int y = 1; y<=(n-i)*2-1; y++)
System.out.print("*");
for (int x = 1; x<=i; x++)
System.out.print(" ");
System.out.println();
}
}
}
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 21
Task 2 E : Answer // Taner ERKAN
import java.util.*;
import java.io.*;
public class E{
public static void main (String args[])throws Exception{
Scanner in= new Scanner (new File ("bigtext.txt"));
int a[] = new int[100];
char k=' ';
while (in.hasNextLine())
{
String text=in.nextLine();
for(int i=0; i<text.length();i++)
{
k =text.charAt(i);
if (k>='A' && k<='Z')
a[(int)k-65]+=1;
if (k>='a' && k<='z')
a[(int)k-71]+=1;
}
}
for (int j=0;j<=25; j++)
if (a[j]!=0)
System.out.println((char)(j+65)+"-"+ a[j]);
for (int j=26;j<=51; j++)
if (a[j]!=0)
System.out.println((char)(j+71)+"-"+a[j]);
}
}
//
bigtext.txt
Hello world
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 22
Task 3 A : Answer // Taner ERKAN
import java.util.Scanner;
public class A
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter N:");
int N=in.nextInt();
System.out.print("Enter M:");
int M=in.nextInt();
int a[][]=new int[N][M];
for (int i=0;i<N;i++)
for (int j=0;j<M;j++)
a[i][j]=i*j;
for (int i=0;i<N;i++){
for (int j=0;j<M;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}}
}
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 23
Task 3 B : Answer // Taner ERKAN
import java.util.Scanner;
public class B
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter 10 numbers:");
double a[]=new double[10];
int i,i2,j;
for (i=0;i<a.length;i++){
a[i]=in.nextInt();}
double a2[][]=new double[4][10];
for (j=0;j<10;j++){
a2[0][j]=a[j]*2;
a2[1][j]=a[j]*3;
a2[2][j]=a[j]*5;
a2[3][j]=a[j]*7;}
for (i2=0;i2<4;i2++){
for (j=0;j<10;j++)
System.out.printf("%4.0f",a2[i2][j]);
System.out.println();}
}
}
Intruduction to JAVA (Practical) Taner ERKAN 2011
By: Andrey Bogdanchikov Page 24
Task 3 C : Answer // Taner ERKAN
import java.util.*;
import java.io.*;
public class C
{
public static void main(String[]args)throws Exception{