Looping in vertical position - java

I am a beginner in java and i will like to seek some help.
Write a method called vertical that accepts a String as its parameter and prints each letter of the string on separate lines. For example, a call of vertical("hey now") should produce the following output:
h
e
y
n
o
w
This is what i have done.
public void vertical(String x){
char OneByOne='x';
for(int i=0;i<=x.length()-1;i++){
OneByOne=x.charAt(i);
}
System.out.print(OneByOne);
}
It gives me w when i call for it.
But i am confused.i create a char container and call out position 0.And loop through it.Shouldn't position 0
starts from h.Instead of giving me a w?
Also,should i use public void vertical(String x){ or public static void vertical(String x){?They give me the same output.I go research on static and they tell me static means single.What does that means?

public void vertical(String x){
int count = x.length();
for(int i=0;i<count;i++){
System.out.println(x.charAt(i));
}
}

You're not printing inside the loop. Also, use println.

you need to print char in each iteration.
public void vertical(String x){
char OneByOne='x';
for(int i=0;i<=x.length()-1;i++){
System.out.println(x.charAt(i));
}
}

In addition to the other answers: You can also use a for each loop:
public static void vertical(String x) {
for (char OneByOne : x.toCharArray()) {
System.out.println(OneByOne);
}
}

I used a more conventional style here:
public void vertical(String x){
for(int i = 0; i < x.length(); i++){
char oneByOne = x.charAt(i);
System.out.println(oneByOne);
}
}
Less than length, i.o. less-equals length - 1.
Local declaration. Vars starting with small letter.
The rest is fine. charAt(i) gives the i'th char, just as conceived.

You should use prinln instead of print
System.out.println(OneByOne);
static keyword means you're able to call this method without having an instance of your class.

Related

Given a fixed-length integer array arr, duplicate each occurrence of zero, shift elements to right

public class Dupzero {
static int dup =0;
public static void duplicateZeros(int[] arr) {
//read all the elememts in arrays
for(int i=0;i<arr.length;i++) {
if(arr[i]==0) {
for(int j=arr.length-2;j>=i;j--) {
arr[j+1]=arr[j];
}
i=i+1;
}
}
System.out.println(Arrays.toString(arr));
}
public static void main(String[] args) {
int []arr = {
1,0,2,3,0,4,5,0
};
duplicateZeros(arr);
}
}
I wrote this code and i get expected output. Previously i was getting wrong output as i missed the statement i=i+1; .. Can you explain me here in the code what is i=i+1 doing ? is it in the right place ?
i = i+1 increments the counter of the outer for-loop by 1. When you copy a 0 to the right you need to ignore that copied 0 value as you continue to step through. Otherwise, you will just fill out the array with 0s.
Is it in the right place? Well, you say its working so it seems to be. Write some tests to verify the expected behavior.

how i can optimize this java code?

In below code string is passed in a method with numbers separated by space,
now we need to provide sum of smallest two numbers in the string.
public class SumNearZero {
public static int SumNearZero(String s) {
String temp=s;
int t1=0;
for (int i = 0; i <s.length(); i++) {
if(temp.contains(" "))
{
t1++;
temp=temp.substring(temp.indexOf(" ")+1);
}
}
int a[]=new int[++t1];
int index=0;
for(int i=0; i<s.length(); i++)
{
if(s.contains(" "))
{
a[index]=Integer.parseInt(s.substring(0,s.indexOf(" ")));
s=s.substring(s.indexOf(" ")+1);
index++;
}
}
a[index]=Integer.parseInt(s);
for (int i = 0; i < a.length; i++) {
for(int j=0; j<a.length-1; j++)
{
int c=a[j],n=a[j+1];
if(c>n)
{
int t=c;
a[j]=n;
a[j+1]=t;
} } }
int result=a.length>1 ? a[0]+a[1]:a[0];
return result;
}
public static void main(String[] args) {
System.out.println(SumNearZero("35 96 10 20 5"));
}
}
Above code is working fine but i want to reduce the code. if you provide some suggestion regarding this, I'll be happy to learn from you.
Restrictions : use of Collections, predefined methods e.g(String.split(),Arrays.sort()...)
I would suggest you not perform your calculation and display in a constructor, create a static method and invoke it. Next, in that method, create a List of Integer by iterating the substrings generated by splitting your input on one (or more) white space characters. Then, sort the List. Finally, return the sum of the first two elements1. It's also a good to do some error checking for one number (or no numbers). That might look something like
public static int sumNearZero(String s) {
List<Integer> al = new ArrayList<>();
for (String str : s.split("\\s+")) {
al.add(Integer.parseInt(str));
}
if (al.isEmpty()) {
return 0;
}
Collections.sort(al);
if (al.size() == 1) {
return al.get(0);
}
return (al.get(0) + al.get(1));
}
Then invoke it like
public static void main(String[] args) {
System.out.println(sumNearZero("35 96 10 20 5"));
}
I get (as I expected)
15
1once sorted the first two are the minimum, and the last two are the maximum
You can make it faster by using for each loop instead of for loop every time, it is more recommended and faster approach whenever loop is increasing for array, lists etc.
Plus more you can get all numbers in string by using split function which retrives you array of those numbers.and then you can put your logic for getting small numbers.this will reduce counting and increase speed highly in general if you want to learn about optimization then this is definitive guide i suggest you to go through it. and see this answer.
Looks like an exercise, so not giving actual code.
Use String.split and Arrays.sort

Java program HugeInteger

I am writing a program that will add 2 arrays that are 40 elements long together. I have to keep the add() method as a HugeInteger (can’t change it to a integer) so when I try to return the sum of the 2 integers it gives me “HugeInteger#77e1ee5d”. Could someone let me know what this means and also tell me how I could fix it.
Thank you
public class HugeInteger {
private int[] integer ;
public HugeInteger(int num[]){
integer =new int [40];
for(int x=1; x<=39; x++){
integer[x]= num[x];
}
}
public void parse(String s){
for(int i=0; i<=s.length(); i++){
integer[i]=Integer.parseInt(s.substring(i,i+1));
}
}
public HugeInteger add(HugeInteger a1){
HugeInteger sum = new HugeInteger(integer);
int cary=0;
for (int i=39; i>=0; i--){
sum.integer[i]=integer[i]+a1.integer[i]+cary;
if(sum.integer[i]>=10){
cary=1;
sum.integer[i]-=10;
}else{
cary=0;
}
}
return sum;
}}
//This is my test program
public class HugeIntegerTest {
public static void main(String[] args) {
int []num={1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
HugeInteger hi= new HugeInteger(num);
System.out.println("Addition: "+hi.add(hi));
}
}
That's the output of the default Object.toString() method. You need to override toString and provide a better implementation yourself. An example:
#Override
public String toString() {
StringBuilder builder = new StringBuilder(integer.length);
for(int digit : integer) {
builder.append(digit);
}
return builder.toString();
}
Note that this implementation does not trim leading zeros, i.e. it will print "0000...000123" instead of just "123". This is left as an exercise for the reader, erm, programmer. ;-)
Another tip: in your constructor, your loop should start at i=0. Otherwise the most significant digit (integer[0]) will always be zero, for example your test program would give you a HugeInteger representing 0 instead of 1039.
You have to write your own version of the toString() for HugeInteger to make it display correctly.

Simple method query

I have the following code which returns an error.
The line:
return first;
says:
incompatible types, required: char[]
It seems like something simple, but I can't figure it out. I am trying to display the values from invoking methodB.
Also, you will notice I have commented an if statement as #4. Can someone further my understanding a bit.
Does this if statement update the value held by the variable first IF the value held in the current element in alphas comes before the current value of first?
Hope this makes sense and someone can help. Getting late and my brain isn't working any more. Java is going to make or break me!
package openuniversity;
public class Main
{
public static void main(String[] args)
{
Main m = new Main();
char [] alp = m.methodB();
for (char b: alp)
{
System.out.println(b);
}
}
public static char[] methodB()
{
char [] alphas = {'s','a','u','s','a','g','e'};
char first = alphas[0];
for (int i= 1; i < alphas.length; i++) //3
{
if (alphas[i] < first) //4
{
first = alphas[i];
}
}
return first;
}
}
package openuniversity;
public class Main
{
public static void main(String[] args)
{
Main m = new Main();
char alp = m.methodB();
System.out.println(alp);
}
public static char methodB()
{
char [] alphas = {'s','a','u','s','a','g','e'};
char first = alphas[0];
for (int i= 1; i < alphas.length; i++) //3
{
if (alphas[i] < first) //4
{
first = alphas[i];
}
}
return first;
}
}
Your function signature says you're returning a char[]:
public static char[] methodB()
But you actually return a char:
char first = alphas[0];
// ...
return first;
It's not entirely clear what you want to do, but you need to either change the signature to return a single char:
public static char methodB()
And change where it's used:
char alp = m.methodB();
Or make methodB actually return a char[]. The problem is I don't know what it's actually supposed to return. I'd suggest giving the function a better name. You may want to take a look at Lists.

question about polynomial multiplication

i know that horners method for polynomial pultiplication is faster but here i dont know what is happening here is code
public class horner{
public static final int n=10;
public static final int x=7;
public static void main(String[] args){
//non fast version
int a[]=new int[]{1,2,3,4,5,6,7,8,9,10};
int xi=1;
int y=a[0];
for (int i=1;i<n;i++){
xi=x*xi;
y=y+a[i]*xi;
}
System.out.println(y);
//fast method
int y1=a[n-1];
for (int i=n-2;i>=0;i--){
y1=x*y+a[i];
}
System.out.println(y1);
}
}
result of this two methods are not same
result of first method is
462945547
and result of second method is
-1054348465
please help
You're using y on the second loop:
y1=x*y+a[i];
This is where writing two function would come in handy - it would be impossible to reuse the same variable.
Look at this loop:
for (int i=1;i<n;i++){
xi=x*xi;
y=y+a[i]*xi;
}
I think you should use
for (int i=0;i<n;i++){
xi=x*xi;
y=y+a[i]*xi;
}

Categories