Java Help

0 Yasser Taha · November 1, 2014
I have Assignment that must be submitted by tomorrow, i was able to solve 4 of the 5 questions. 
Well, i am stuck in this



Write a program that reads in from the user an integer (num) between 1000 and 9999. Then it prompts
the user to enter an integer (d) between 0 and 9 and a character (ch). Your program should replace the 
second and the last digit in num with d and it should display the character that precedes (ch) followed by 
the number after the change and then the character that comes after (ch). Use the division and modulus 
operators to extract the digits from num.

Sample run:

Enter an integer between 1000 and 9999: 2134
Enter a digit (between 0 and 9): 6
Enter a character: b
Number was 2134. Result: a2636c.





and this what i did for now


package question2;
import java.util.Scanner;

public class Question2 {
   
  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter an integer between 1000 and 9999: ");
    int num = input.nextInt();
    System.out.println("Enter a digit (between 0 and 9): ");
    int d = input.nextInt();
    System.out.println("Enter a character: ");
    char ch = input.nextChar();
        
   }
    
}


Still i need to figure out how to replace 2nd and 4th in num and replace it with integer d.
As well display the precedent and the letter that comes after ch before&after the number.

Post a Reply

Replies

Oldest  Newest  Rating
+2 Homer Simpson · November 1, 2014
Here's what I came up with, I wrote this assuming the user will enter in the correct data. 


import java.util.Scanner;

public class Practise {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int num, d, num1, num2;
char ch, ch1, ch2;
String result;

System.out.println("Enter an integer between 1000 & 9999");
num = input.nextInt();
System.out.println("Enter an integer between 0 & 9");
d = input.nextInt();
System.out.println("Enter a character.");
ch = input.next().charAt(0);

ch1 = (char) ((char) ch - 1);
ch2 = (char) ((char) ch + 1);

num1 = num / 1000;
num2 = (num % 100) / 10;

result = "" + ch1 + num1 + d + num2 + d + ch2 + ".";

System.out.println("Number was " + num + ". Result: " + result);

input.close();
}
}

If you need me to explain anything I did just pm me. 
  • 1

Java / Android Development

107,139 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator