The problem I am having is that when I enter for example Gina Charlene Doe it will print out enelr.
import java.util.Scanner;
import java.io.*;
public class test_1
{
static Scanner in = new Scanner(System.in);
public static void main() {
String name, middle;
System.out.println("Enter your first, middle, and last name ");
name=in.nextLine();
int space1=name.indexOf(" ");
int space2=name.lastIndexOf(" ");
middle=name.substring(space1+1,space2);
for (int x=middle.length();x>=space1;x--)
{
System.out.print(middle.substring(x-1,x));
}
}
}
Sorry I am new to posting things to here so I hope it's formatted well enough.
Based on your output, your loop is working but terminating too early. So something is wrong with your for loop
for (int x=middle.length();x>=space1;x--)
Your condition, x>=space1, is the source of error because you set it to 5 here:
int space1=name.indexOf(" ");
So in your loop, it works down your string from 8 and terminates when x = 4, which is midway through your string, obviously not what you want. So the correct fix is
for (int x=middle.length();x>0;x--)
Your for loop is just logically flawed. Here is the correct code
import java.util.Scanner;
public class Middle
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String name, middle, reversed = "";
System.out.println("Enter your first, middle, and last name ");
name=in.nextLine();
int space1=name.indexOf(" ");
int space2=name.lastIndexOf(" ");
middle=name.substring(space1+1,space2);
for(int i=middle.length(); i > 0; i--)
{
reversed = reversed + middle.charAt(i-1);
}
System.out.println(reversed);
}
}
Try this way!
import java.util.Scanner;
public class Middle{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter your first, middle and last name.");
String[] name = in.nextLine().split(" ");
for(int i=name[1].length()-1; i>=0; i--){
System.out.print(name[1].charAt(i));
}
}
}
How to print the middle name in reverse order?
The straight answer is new StringBuilder(middle).reverse().toString();
Solution:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// input
System.out.println("Enter your first, middle, and last name ");
String fullname = in.nextLine();
// split
String[] fullnameArray = fullname.trim().split("\\s");
// parse
String first = fullnameArray[0];
String middle = fullnameArray[1];
String last = fullnameArray[2];
// reverse middle name
String middleReversed = new StringBuilder(middle).reverse().toString();
// output
System.out.println("First name:" + first);
System.out.println("middle name (reversed):" + middleReversed);
System.out.println("last name:" + last);
}
Related
package stringvars;
import java.util.Scanner;
public class ConcertID {
public static void main(String[] args) {
try (Scanner userInput = new Scanner (System.in)) {
String yourName;
System.out.print ("enter the last letter of your second name: ");
yourName = userInput.next();
String yourDOB;
System.out.print ("enter your Year Of Birth: ");
yourDOB = userInput.next();
String ConcertID;
ConcertID = yourName + " " + yourDOB;
System.out.println("your concert ID is " + ConcertID);
}
}
}
I'm trying to get the code to take the user input, add a number between 1 and 10 at the end and print it as Y18867. Currently it prints as Y 1886.
(And I've yet to figure out the math.random part.)
Let me recommend you start using the StringBuilder class to create concatenated strings. It has a better performance regarding time consuming to concatenate strings.
The following code generates the random number as well as the concertId string that you are trying to get.
public class ConcertID
{
public static void main(String[] args)
{
try (Scanner userInput = new Scanner(System.in))
{
String yourName;
System.out.print("Enter the last letter of your second name: ");
yourName = userInput.nextLine();
String yearOfBirth;
System.out.print("Enter your Year of Birth: ");
yearOfBirth = userInput.nextLine();
StringBuilder concertId = new StringBuilder();
concertId.append(yourName);
concertId.append(yearOfBirth);
concertId.append(generateNumber());
System.out.println(concertId.toString());
}
}
public static int generateNumber()
{
int number = 0;
Random random = new Random();
number = random.nextInt(1, 10);
return number;
}
}
found this code on the internet, it's missing the while loop logic "while(i....)" for some reason and though I found other working solutions for the PigLatin* problem, I really want to understand how this one is working.
*PigLatin problem: take a sentence, take the first letter from each word and place it at the end of the same word, then suffix "ay". So "I am confused" becomes "Iay maay onfusedcay".
Here is the code:
import java.util.*;
public class PigLatin {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an English sentence: ");
String sentence = input.nextLine();
System.out.println("Original sentence: "+sentence);
System.out.println("PigLatin conversion: "+convert(sentence));
}
private static String convert (String sentence) {
String []words = sentence.split(" ");
int i = 0;
String pigLatin = "";
while(i ){ //MISSING CODE
pigLatin+=words[i].substring(1,words[i].length())+words[i].charAt(0)+"ay"+" ";
i++;
}
return pigLatin;
}
}
Thank you.
PS: I basically found the "convert" method on the internet and wrote the rest of the code, tried a few things but could not get the while loop to work.
The loop appears to be iterating the words array. So it should just be something like
while(i < words.length) {
pigLatin += words[i].substring(1, words[i].length())
+ words[i].charAt(0) + "ay ";
i++;
}
import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an English sentence: ");
String sentence = input.nextLine();
System.out.println("Original sentence: "+sentence);
System.out.println("PigLatin conversion: "+convert(sentence));
}
private static String convert (String sentence) {
String []words = sentence.split(" ");
int i = 0;
String pigLatin = "";
while(i<words.length){ //CORRECTION CODE
pigLatin+=words[i].substring(1,words[i].length())+words[i].charAt(0)+"ay"+" ";
i++;
}
return pigLatin;
}
}
I'm quite new to Java and I've been asked to create a program in which the user is able to input two values and store them in separate arrays. The two values I'm asking the user are name and cell number, then I must allow the user to search by typing either a name or a cell number and return the corresponding name or cell number. I made it possible to input the values and search within them by number but when I try searching by name I get this error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "B"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
This is my code:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int i, x = 2;
static String names[] = new String[x];
static int numbers[] = new int[x];
public static void main(String[] args) {
Input();
Compare();
}
public static void Input() {
System.out.println("Enter a name followed by the persons number");
while (i < x) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.nextInt();
i++;
}
}
public static void Compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
var temp = sc.next();
System.out.println("NAME\tNUMBER");
for (i = 0; i < numbers.length; i++)
if ((names[i].equals(temp)) || (numbers[i] == Integer.parseInt(temp.trim()))) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
}
Thanks! :)
Looking at your problem statement it doesn't seem like you need to do any additional processing on numbers. Hence, even if you store the number as a string it should be fine in this case.
Hence after getting a user search criteria, you could do a simple string search within both arrays.
Hope this helps :)
First of all, the highest number that can be represented as an int in Java is 2147483647 (214-748-3647). This clearly will not be able to hold a high enough number to accommodate any phone number. To address this issue and also fix your main error, I would suggest storing the numbers as a string instead. Here's my solution:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int x = 2;
static String names[] = new String[x];
static String numbers[] = new String[x];
public static void main(String[] args) {
input();
compare();
}
public static void input() {
System.out.println("Enter a name followed by the persons number");
for (int i = 0; i < x; i++) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.next();
i++;
}
}
public static void compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
String temp = sc.next();
System.out.println("NAME\tNUMBER");
for (int i = 0; i < numbers.length; i++) {
if ((names[i].equals(temp)) || numbers[i].equals(temp)) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
System.out.println("===END OF SEARCH====")
}
}
Please also note that I un-defined your variable i. As far as I can see there's no reason for you to be defining it. Hope this helps, good luck!
Non-CS major here taking my first programming class for fun. As the title states, my first assignment is "Write a program that prints out every line of input exactly as they were entered." My program right now will accept one input, but not any others. How can I fix this? Thank you so much :)
import java.util.Scanner;
public class echohw {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans;
ans = in.nextLine();
System.out.print(ans);
Like Scary Wombat said, use a while loop:
import java.util.Scanner;
public class echohw {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans;
// Continue printing user input unless "stop" is entered
while (!(ans = in.nextLine()).equals("stop"))
System.out.println(ans);
}
}
You can use array function to store multiple user inputs. In this example, I try to make it simple so you can understand it well. If you have any other doubt, you can ask me here.
import java.util.Scanner;
public class echohw {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide number of inputs
System.out.println("How many inputs you want to enter: ");
int numInput = Integer.parseInt(scan.nextLine());
//Store inputs
String aryInput[] = new String[numInput];
for (int i = 0; i < aryInput.length; i++) {
System.out.println("Enter the input " + (i+1) + " : ");
aryInput[i] = scan.nextLine();
}
//Print inputs
for (int i = 0; i < aryInput.length; i++) {
System.out.println("Input " + (i+1) + " : ");
System.out.println(aryInput[i] + "\n");
}
}
}
My program is supposed to print out the initials of the name and print the last name.
Eg. if the name entered is Mohan Das Karamchand Gandhi, the output must be MDK Gandhi. Although I get a "String index out of range" exception.
import java.util.Scanner;
public class name {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
for(int i=0;i<l;i++){
ch=w.charAt(i);
if(ch==32||ch==' '){
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println(w.substring(spacel,l+1));
}
This is the culprit:
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
When i is equal to l - 1, then space1 is going to be equal to l or w.length(), which is beyond the end of the string.
This can be easily achieved using String's split() method or using StringTokenizer.
First split string using space as delimiter. Then according to your format last string would be Last Name and iterate over other string objects to get initial characters.
String name = "Mohan Das Karamchand Gandhi";
String broken[] = name.split(" ");
int len = broken.length;
char initials[] = new char[len-1];
for(int i=0;i<len-1;i++) {
initials[i] = broken[i].charAt(0);
}
String finalAns = new String(initials)+" "+broken[len-1];
import java.util.Scanner;
public class name
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
System.out.print(w.charAt(0) + " ");
for(int i=0;i<l;i++)
{
ch=w.charAt(i);
if(ch==32||ch==' ')
{
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println("\b\b"+w.substring(spacel,l));
}
}