Why is my program outputing the results twice in a row? - java

I'm in the process of making a program that can take the #'s from a credit card and check to see if it's valid.
here is my code so far:
import java.util.Scanner;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader=new Scanner(System.in);
System.out.println("Please enter your credit card #");
String Ccard=reader.nextLine();
int length=Ccard.length();
doubleDig(Ccard,length);
int []digits=doubleDig(Ccard,length);
/*for(int x=0;x<digits.length;x++){
System.out.println(digits[x]);
}test array*/
}
public static int[] doubleDig(String cardNum,int length){
int []nums=new int[length];
for(int x=0;x<cardNum.length();x++){
nums[x]=cardNum.charAt(x);
System.out.println(cardNum.charAt(x));
}//makes array
//System.out.println(nums.length);
for(int x=nums.length;x<0;x-=2){
nums[x]=nums[x]*2;
}
return nums;
}//end doubleDig
}
I went to see if the array was set up correctly so I used:
System.out.println(nums[x]); in the loop but got values that I didn't understand. I then went and used:
System.out.println(cardNum.charAt(x)); in the loop to see what was up.
I then noticed that the array was somehow being displayed a 2nd time. The size of the array should be equal to the length of the string the user put in (I'm using 5491946915444920 as my test value), which is 16 in this case. 16 numbers display, but then it loops over itself again somehow and the values display a 2nd time(displaying 32 total #'s). Any clues?

you can use this:
public static int[] doubleDig(String cardNum, int length) {
int[] nums = new int[length];
int num;
for (int x = 0; x < cardNum.length(); x++) {
nums[x]=Integer.parseInt(cardNum.substring(x, x+1));
}
System.out.println(nums.length);
return nums;
}

Because at this line of code nums[x] = cardNum.charAt(x); you are actually printing char values i.e [53, 52, 57,etc] for 5491946915444920

Related

error with returning a value from a method in java

hello in the code below I am sorting (sort method) a small array to find the largest number. I then print the answer in the (display method).
But to extend my knowledge I want to mass the max value back to them main in a return statement and then print from there....simply to learn how to return a value.
package christmas;
public class maxvalue
{
public static void main(String[] args)
{
int[] data={10,90,30};
sort(data);
System.out.println("\nmax number is :");
display(data);
System.out.println(data);
}
static int display(int num[])
{
System.out.print(num[0] + " ");
return num[0];
}
static void sort(int num[])
{
int i, j, temp;
for(i=0; i<num.length-i;i++)
{
for(j=0; j<num.length-i-1;j++)
{
if(num[j]<num[j+1])
{
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
}
}
the output is:
max number is :
90 [I#4617c264
90 is the max value as printed by the display value. But after this I have a return of the max value and then I try and print the return. But instead of an integer it looks like a memory location is being printed.
Any ideas please - I am student but this is not homework - simply trying to catch up. I appreciate that there are more elegant ways to calculate the max value in an array but what I am trying to learn is the passing of arguments to and from a method.
The reason is that you are trying in your last System.out to print data, which is an array, and that's the reason why you see a memory address.Try printing display(data) and you will see as the output the desired number.
try System.out.println(data[0]);
data is your array therefore printing data without an index will only print its memory location
Instead of printing the returned value, you are printing the data array memory location:
System.out.println(data);
You should change that line with:
System.out.println(display(data));
With that line we have:
Your display method is called and it prints the max value
Your display method returns the max value
println takes that returned value and prints it
private static int sort(int[] array){
int a, b, max = 0;
for (int i = 1;//If i was 0, it would have thrown an ArrayIndexOutOfBoundsException.
i < array.length; i++){
a = array[i-1];//The first element in the array.
b = array[i];//The second one, and so on.
if (a > b) max = a;//Check the bigger number.
else max = b;
}
return max;
}
private static void display(int nr){
System.out.print(nr);//Or what you want to do with the number.
}
public static void main(String[] args){
int[] data={10,90,30};
display(sort(data));
//Or do it like this.
int max = sort(data);
display(max);
}

Trying to set array elements constraints

1.Output: print remainder when sum is divided by max element.
2.Constraints: 1<=n<=100;
0<=A[i]<=1000
I need this code to validate array elements as such:
pseudocode:
if (arr_elmt>=0 and arr_elmt<=1000) ->Then execute succeeding commands.
else ->stop program, even though other elements obey constraint
3.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner val = new Scanner(System.in);
System.out.print("Enter no of values:");
int n;
int A[] = new int[n=val.nextInt()];
//First constraint
if(n>=1 && n<=100)
{
int i=0;
for(i=0;i<A.length;i++)
{
A[i]=val.nextInt();
}
for(i=0;i<A.length;i++)
{ //Second constraint
if(A[i]>=0 && A[i]<=1000)
{
int sum=0;
//Using for-each loop to print array values and get total sum
for(int t:A)
{
System.out.print(t+" ");
sum+=t;
}
//To get largest value
int largest=A[0];
for(i=0;i<A.length;i++)//i=1 can work
{
if(A[i]>largest)
{
largest=A[i];
}
}
//To get and print remainder
int rem;
rem=sum%largest;
System.out.print("\n"+ rem);
}
}
}
}
}
e.g: input: 3;
Values: 2988 67 5.
I expect an error due to 2988>1000, but the code
still runs and gives me output! output obtained:(2988+67+5)mod(2988)
Hi so your problem is that you do not specified that program should stop (or do whatever you want) when find number which does not match your second constraint.
So right now when does not match second constraint for 2688 it keeps iterating to second item and keep executing rest of your code.
So to make your program end when second constraint is not match you should add something like this
import java.util.Scanner;
public class test {
public static void main(String args[]) {
Scanner val = new Scanner(System.in);
System.out.print("Enter no of values:");
int n;
int A[] = new int[n=val.nextInt()];
//First constraint
if(n>=1 && n<=100)
{
for(int i=0;i<A.length;i++)
{
A[i]=val.nextInt();
}
for(int i=0;i<A.length;i++)
{ //Second constraint loop through all elements of A[]
// if one of it does not obey constraint exit the program
if(A[i]<=0 || A[i]>=1000) // notice here I change '>'
{
System.exit(0); // this else is attached to your second constraint
}
}
for(int i = 0; i < A.length; i++){
int sum=0;
//Using for-each loop to print array values and get total sum
for(int t:A)
{
System.out.print(t+" ");
sum+=t;
}
//To get largest value
int largest=A[0];
for(int j=0;j<A.length;j++)//i=1 can work
{
if(A[j]>largest)
{
largest=A[j];
}
}
//To get and print remainder
int rem;
rem=sum%largest;
System.out.println(rem);
}
}
}
}

Terminated due to timeout in hacker rank for large inputs

This code shows "Terminated due to timeout" error on some large inputs on Hackerrank but works fine for the rest of the cases. Help me improve this code please.
John Watson performs an operation called a right circular rotation on an array of integers, . After performing one right circular rotation operation, the array is transformed from to .
Watson performs this operation times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks queries, where each query consists of a single integer, , for which you must print the element at index in the rotated array (i.e., the value of ).
Input Format
The first line contains space-separated integers, , , and , respectively.
The second line contains space-separated integers, where each integer describes array element (where ).
Each of the subsequent lines contains a single integer denoting .
Constraints
Output Format
For each query, print the value of the element at index of the rotated array on a new line.
Sample Input
3 2 3
1 2 3
0
1
2
Sample Output
2
3
1
MY CODE
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n,k,q,temp=0,c=0;
Scanner sc=new Scanner(System.in);
try{
n=sc.nextInt();
k=sc.nextInt();
q=sc.nextInt();
int[] arr=new int[n];
int qrr[]=new int[q];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
while(sc.hasNext()){
qrr[c++]=sc.nextInt();
}
for(int j=1;j<=k;j++){
temp=arr[n-1];
for(int i=n-2;i>=0;i--){
arr[i+1]=arr[i];
}
arr[0]=temp;
}
for(int i=0;i<q;i++){
System.out.println(arr[qrr[i]]);
}
}
catch(Exception ae){
System.out.println(ae.getMessage());
}
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static int m,n,k,q,i=0,c=0;
public static int errorflag = 0;
public static int array[];
public static int rotated[];
public static Scanner in = new Scanner(System.in);
public static int[] getArray(int n){
array = new int[n];
for(i=0;i<n;i++){
array[i] = in.nextInt();
}
return(array);
}
public static int[] rotate(int[] original){
int[] rotated = new int[original.length];
for(i=0;i<original.length;i++){
rotated[(i+k)%original.length] = original[i];
}
return(rotated);
}
The above function works with a worst case O(n) complexity.
Basically what you're doing is assigning a new index for the elements such that they are right rotated or incremented by an amount k and the overflow is taken care of by the modulus operation.
public static void main(String[] args) {
n = in.nextInt();
k = in.nextInt();
q = in.nextInt();
array = getArray(n);
int m[] = new int[q];
for(i=0;i<m.length;i++){
m[i] = in.nextInt();
}
rotated = rotate(array);
for(i=0;i<m.length;i++){
System.out.println(rotated[m[i]]);
}
}
}

Java Bubble sorting not working

I just want to write a program that sorts 3 integers. The integers are entered from the input dialog. My code is really simple. I just need to get some data and put them in array called num. and then I create a method to sort the data by using bubble-sort logic. that method called sort. I have added command to display the sorted result with System.out.println("Sorted Result : "+Arrays.toString(num)) but that's not working.
The output just let me input data and then nothing happen.
Can anyone please tell me something I miss or what I did wrong?
Thank you.
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
for(int i=0;i<=num.length-1;i++){
for(int j=0;j<=num.length-i;j++){
if(num[j-1]>num[j]){
int temp = num[j];
num[j] = num[j-1];
num[j-1] = temp;
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
}
I believe you need a boolean flag to implement a bubble sort as you cannot know in advance how many times the loop will perform the swapping of consecutive elements.
Try this:
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
boolean swapped = true;
while(swapped){
swapped = false;
for(int i=0;i<num.length-1;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
Note that it can still be slightly improved: each time around the loop the largest number will end up as far as it can get towards the end of of the array: there's no need to check or swap till the end each time.
By using a variable as the upper limit of the index i and decreasing its value after the for loop you can reduce the total number of iterations.
int end = num.length-1;
while(swapped){
swapped = false;
for(int i=0;i<end;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
end--;
}

string array; java.lang.ArrayIndexOutOfBoundsException: 10

I have two classes that basically function as the most simplest database, where the user is supposed to enter a string and the program adds it in the array using a class that holds all the methods. Except that when i enter the first name it gives me java.lang.ArrayIndexOutOfBoundsException: 0. I know this means that no memory is being allocated for the array but i thought i did this in my second class where there is a constructer that defines the size of the array. Im not experienced enough with arrays to fix this debug on my own. Much help would be appreicated!
import java.util.*;
public class TestDatabase {
//contant value for data base 'size' of array
public static final int constant = 10;
public static void main (String[] args){
//Database object sets the array size to constant value
Database get = new Database(constant);
//input stream
Scanner in = new Scanner (System.in);
//varaibles for the count and index; prompt
int count = 0;
int index = 0;
System.out.println("Please enter 10 names to add them to the database. Name: " + (count += 1));
//while the count is lower than or equal to 10...
while(count<=10){
//input stream equal to input
String input = in.nextLine();
//if the count equals, stop the loop
if (count == 10)
{
//breaks the loop
break;
}
//prints out the current name
System.out.print(" Name: " + (count +=1));
//adds the input to the array
get.add(index,input);
//increments index by 1
index++;
}
//prints the array
get.print();
}
}
Here is my class with my all my methods:
import java.util.*;
public class Database{
//size of array
public int _size;
//array which has a varaible size
String[] userArray = new String[_size];
//contructer for the array size
public Database(int size){
_size = size;
}
//add method which adds a value to an index of an array
public void add(int index, String name){
//the values of string is placed into some index of the array
userArray[index] = name;
}
//print method which prints the contents of the array
public void print(){
//prints array
System.out.println(Arrays.toString(userArray));
}
//sort method which sorts the array
public void sort(){
//sorts the array
Arrays.sort(userArray);
}
//find method which finds a particular string in any index
public void find(String value){
Arrays.asList(userArray).contains(value);
}
}
Your ArrayList is never instantiated properly, you need to move it into your constructor so when the new operator is called, then the arraylist is created with the size variable that is passed, so something like this:
public Database {
private String[] data;
public Database(int size){
this.data = new String[size];
}
}
With your current code, the array is created before the size is actually given, so it defaults to a size of 0.
userArray init with zero length before your constuctor set _size. Create userArray in constructor.
there next steps performed when you create class:
_size init with 0
userArray init with zero length array
_size init with size value.
Change the code as below
String[] userArray;
public Database(int size){
_size = size;
userArray = new String[_size];
}

Categories

Resources