Use multiple methods in Java - java

How to use multiple methods in a code? First it asks for the size of an array, then for the numbers of the element. One method is rounding numbers with a special rule.
Second method is a void method which modifies the array. Third method is making a new array with the modified values and returns to this array.
package tombtombbekerekit;
import java.util.Scanner;
public class TombTombbeKerekit {
public static int round(int osszeg)
{
int last_Digit = osszeg % 10;
if(last_Digit < 3)
return osszeg - last_Digit;
else if(last_Digit > 7)
return osszeg + (10 - last_Digit);
else
return osszeg - (last_Digit) + 5;
}
public static void roundSelf(int [] numbers)
{
int[] array = numbers;
for (int i = 0; i < array.length; i++)
return;
}
public static int [] roundNew(int [] numbers)
{
int [] newArray = new int[numbers.length];
return newArray;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Kérem az összegek számát: ");
int size = sc.nextInt();
System.out.println("Kérem az összegeket: ");
int [] array = new int[size];
for (int i = 0; i < array.length; i ++)
{
array[i] = sc.nextInt();
}
int [] kerek = roundNew(array);
System.out.println("Kerekítve: ");
for (int i = 0; i < kerek.length; i++)
System.out.println(kerek[i]);
}
}

You should write your own function. Just find the rule for the rounding. You can use n%10 to get the last digit of an integer named n.
I've written something but haven't tested it, I believe it should work. Check it out:
public int weirdRounding(int n)
{
int last_Digit = n % 10;
if(last_Digit < 3)
return n - last_Digit;
else if(last_Digit > 7)
return n + (10 - last_Digit);
else // the last digit is 3,4,5,6,7
return n - (last_Digit) + 5;
}
Note: You should probably make this code more readable if you're going to use it. For example define int LOWER_BOUND = 3 and int UPPER_BOUND = 7 instead of using '3' and '7', you could also wrap the ugly expressions with functions (e.g. roundUp, roundToFive ..). #Magic_Numbers_Are_Bad

Related

Maximum Integer Value java

I was trying to solve the Maximum Integer Value problem form Geeksforgeeks.
The problem states the following:
Given a string S of digits(0-9), your task is to find the maximum value that can be obtained from the string by putting either '*' or '+' operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input denoting the string.
Output:
For each testcase, print the maximum value obtained.
this is what I did:
class GFG
{
public static void sort(int[] numbers)
{
int n = numbers.length;
for (int i = 1; i < n; ++i)
{
int key = numbers[i];
int j = i - 1;
while (j >= 0 && numbers[j] > key)
{
numbers[j + 1] = numbers[j];
j = j -1 ;
}
numbers[j + 1] = key;
}
System.out.println(numbers.length - 1);
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
int [] maxNum;
for(int i = 0; i< testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
maxNum = new int [cNumbers.length];
for(int j = 0; j + 1 < cNumbers.length; j++)
{
int sum = 0;
int mult = 0;
sum = cNumbers[j] + cNumbers[j + 1];
mult = cNumbers[j] * cNumbers[j + 1];
int maxNumber = Math.max(sum, mult);
maxNum[i] = maxNumber;
}
sort(maxNum);
}
}
}
an example of Input:
2
01230
891
My Output:
-1
4
Correct Output:
9
73
What is wrong with my code?!
Just quick glance it would seem if your digit is less than two it should be added. 2 or larger should get multiplied. Not at a PC to test though.
The idea is to put the operators alternatively and choose the maximum results.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.parseInt(sc.nextLine());
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
int max = 0;
for (int j = 0; j + 1 < numbers.length(); j++) {
int next = Integer.parseInt(numbers.substring(j, j+1));
if (max + next > max * next)
max = max + next;
else
max = max * next;
}
System.out.println(max);
}
sc.close();
}
}
After the execution of
int testCases = sc.nextInt();
the buffer contains a new line character. So when executing the line
String numbers = sc.nextLine();
it read '\n' into numbers, so you got -1 as the first output.
Also you need to convert character to Integer before using it any arithmetic operations.
sum = cNumbers[j] + cNumbers[j+1];
mult = cNumbers[j] * cNumbers[j+1];
So the above code will give you wrong results.
I tried the following sample and worked.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputAsString = sc.nextLine();
int testCases = Integer.parseInt(inputAsString);
int maxNumber = 0;
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
if(!numbers.matches("\\d+")){
System.out.println("Only numeric values are expected.");
continue;
}
char[] cNumbers = numbers.toCharArray();
int sum = 0;
int mult = 1;
for (int j = 0; j < cNumbers.length; j++) {
int nextNumber = Character.getNumericValue(cNumbers[j]);
sum = sum + nextNumber;
mult = mult * nextNumber;
maxNumber = mult > sum ? mult : sum;
sum = maxNumber;
mult = maxNumber;
}
System.out.println(maxNumber);
}
sc.close();
}
I read your description and what you do is wrong. please read question carefully specially the example in reference site.
as mentioned in comments by moilejter you use sc.nextInt() which doesn't read '\n' and make problem. the next sc.nextLine() will read only a empty string and your program throw exception.
Second problem is that you must calculate max continuously and you don't need an int array (you calculate max result of operation between two successive number and save them in an array which is not correspond to max integer value. you only find max between each two digit but not max of operation on all digit).
Third problem is that you use character as numbers which is made incorrect result. (you must convert them to integer)
So there is a code that works for your output:
public class GFG
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.valueOf(sc.nextLine());
for (int i = 0; i < testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
long maxUntilNow = cNumbers[0] - '0';
for (int j = 1; j < cNumbers.length; j++)
{
int numberOfThisPlace = cNumbers[j] - '0';
maxUntilNow = Math.max(maxUntilNow + numberOfThisPlace,
maxUntilNow * numberOfThisPlace);
}
System.out.println(maxUntilNow);
}
}
}
I hope this is what you want.
As per the problem statement, we need to obtain maximum value from the string by putting either * or + operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
So, this can be solved in O(n) without using any sorting algorithm.
The simple logic behind the solution is whenever you find "0" or "1" in any of the operands use "+" and the rest of the places use "*".
Here is my solution which got successfully submitted:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int T = Integer.parseInt(scan.nextLine());
while(T-- > 0) {
String str = scan.nextLine();
maxValue(str);
}
}
static void maxValue(String str) {
long maxNumber = 0;
for(int i = 0; i < str.length(); i++) {
int n = Character.getNumericValue(str.charAt(i));
if (maxNumber == 0 || maxNumber == 1 ||
n == 0 || n == 1) {
maxNumber += n;
} else {
maxNumber *= n;
}
}
System.out.println(maxNumber);
}
}

Reverse numerical numbers without use of libraries

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.println(reverse);
}
}
}
All numbers reverse well but I have problem with reversing numbers that end with zero e.g numbers like 10000 instead of reversing result being 00001 it gives the result as 1 which is not what the question wants is there a way to use integers or string will be the best and easier approach? Thank you
Try the reversing of string concept
String s ="10000";
String n= "";
for(int i=0; i<s.length(); i++){
n = s.charAt(i) + n;
}
System.out.println(n);
You can create a variable length, and use System.out.printf to format output.
With %0 + length + d, it will add 0 on the left to make the output have this length.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
int length = String.valueOf(number).length();
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.printf("%0" + length + "d", reverse);
}
}
}
You could also solve it with a StringBuilder. It already has a method called reverse:
public String reverseInput(int number) {
String s = Integer.toString(number);
return new StringBuilder(s).reverse().toString();
}
You can't have a Integer beginning with 0 except 0 itself. So you will have to work with Strings or other datastructures.

Why is program behaving this way?

Following is my code which adds products of all 3 digit numbers into an array List. Then prints those numbers which are palindrome. I am getting 121 as output. Why not other palindrome number??
import java.util.ArrayList;
public class eular {
int reverse=0;
public boolean palindrome( Integer num){
int remainder=0;
int n=num;
while(num!=0){
remainder = num % 10;
reverse = reverse * 10 + remainder;
num = num / 10;
}
if(n==reverse)
return true;
else
{
return false;
}
}
public static void main(String args[]){
eular e=new eular();
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=100;i<=999;i++)
for(int j=100;j<=999;j++){
a.add(i*j);
}
for (Integer integer : a) {
if(e.palindrome(integer)){
System.out.println(integer);;
}
}
}
}
Your reverse variable should be initialized every time you call a palindrome method. Move the line int reverse=0; inside that method.
First, you've forgot to declare reverse (edit: or did it in the wrong context as a field of euler class: in that case you have to assign reverse to zero before each call of the palindrome):
// static: you don't want "this"
public static boolean palindrome(Integer num) {
int n = num;
int reverse = 0; // <- this was omitted (or misplaced as a field of euler)
while (num != 0) {
reverse = reverse * 10 + num % 10;
num = num / 10;
}
// ifs can be so ugly...
return n == reverse;
}
Second, you don't want that huge arrays:
...
for (int i = 100; i <= 999; i++)
for (int j = 100; j <= 999; j++) {
int item = i * j;
if (palindrome(item))
System.out.println(item);
}

counting cosecutive numbers in arrays

Problem H [Longest Natural Successors]
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors. Example:
Input
7 2 3 5 6 7 9 10 Output 3
here is my code so far can anyone help me plz
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int x=scan.nextInt();
int[] array= new int[x];
for(int i=0;i<array.length;i++)
array[i]=scan.nextInt();
System.out.println(array(array));
}
public static int array(int[] array){
int count=0,temp=0;
for(int i=0;i<array.length;i++){
count=0;
for(int j=i,k=i+1;j<array.length-1;j++,k++)
if(array[j]-array[k]==1)
count++;
else{if(temp<count)
temp=count;
break;}
}
return temp+1;
}
}
Try this
ArrayList<Integer> outList = new ArrayList<Integer>()
int lastNum = array[0];
for(int i = 1; i < array.length; i++;)
if((lastNum + 1) == array[i])
outList.add(array[i]);
I think the line i=counter; should be i += counter. otherwise, you're always resetting the loop-counter i to zero, and so it never progresses.
You don't need the inner for loop, as this can be done with one single scan through the array:
public static int consecutive(int[]array) {
int tempCounter = 1; //there will always be a count of one
int longestCounter = 1; //always be a count of one
int prevCell = array[0];
for(int i=1;i<array.length;i++) {
if( array[i] == (prevCell + 1)) {
tempCounter++; //consecutive count increases
} else {
tempCount =1; //reset to 1
}
if(tempCounter > longestCounter) {
longestCounter = tempCounter; //update longest Counter
}
prevCell = array[i];
}
return longestCounter;
}
int sequenceStart = 0;
int sequenceLength = 0;
int longestSequenceLength = 0;
for (int item: array) {
if (item == sequenceStart + sequenceLength) {
sequenceLength++;
} else {
sequenceStart = item;
sequenceLength = 1;
}
longestSequenceLength = Math.max(longestSequenceLength, sequenceLength);
}

Using an array as a counter

I am trying to create a module that counts how many times each digits shows up in a given number. The issue I am having is that instead of adding 1 to the array value of the corresponding digit it seems to add 10, that or it concatenates the array's default value ( 0 in this case) although that seems very unlikely.
My module:
public class UtilNumber{
public static int [] Occurence(int nb){
int temp;
int [] t = new int [10];
while (nb !=0){
temp = nb % 10;
for (int i = 0; i < t.length ; i++){
t[temp]++;
}
nb /= 10;
}
return t;
}
}
My main:
import java.util.scanner;
public class Primary{
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
int [] tab;
int nb = keyboard.nextInt();
tab = UtilNumber.Occurence(nb);
for (int i = 0 ; i < tab.length ; i++){
if (tab[i] != 0){
System.out.println(i+" is present "+tab[i]+" time(s).");
}
}
}
}
For example when I enter 888 it should return 3, but instead it returns 30.
It looks like instead of
for (int i = 0; i < t.length ; i++){
t[temp]++;
}
you should just do
t[temp]++;
Or you can write.
public static int [] occurence(long nb){
int[] count = new int [10];
for(;nb > 0;nb /= 10)
count[nb % 10]++;
return count;
}

Categories