This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 4 years ago.
I am just a beginner and do not know how to reverse text that I write on input so it is reversed on output. I wrote something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] pole = {s};
for (int i = pole.length; i >= 0; i--) {
System.out.print(pole[i]);
} // TODO code application logic here
}
}
but it is not working and I cannot figure out why.
Welcome to SO and java world.
As I understand the problem is not only reversing a String. The problem is also you do not know about Strings and arrays.
Let's see your code line by line;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read a String
String s = sc.nextLine();
// Put String into an array
String[] pole = { s };
// pole's length is 1, because pole has only one String
for (int i = pole.length; i > 0; i--) {
// pole[i-1] is the input String
// System.out.print(pole[i]); // pole[i] get java.lang.ArrayIndexOutOfBoundsException
System.out.print(pole[i - 1]); // this will print input string not reverse
}
// To iterate over a String
for (int i = s.length() - 1; i >= 0; i--) { // iterate over String chars
System.out.print(s.charAt(i)); //this will print reverse String.
}
}
Also as given on comments, Java have ready methods to reverse a String. Like;
new StringBuilder(s).reverse().toString()
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
public static void main (String args[]) {
Scanner io = new Scanner(System.in);
int a = io.nextInt();
io.nextLine();
for(int i = 0; i < a; i++ ) {
String input = io.nextLine();
String[] splitArr = input.split("\\s+");
int p[] = new int[input.length()];
int q = 0;
for (String par : splitArr) {
System.out.println(par);
p[q++] = Integer.parseInt(par);
System.out.println(p);
}
Sort(p);
}
}
The input: 2 121213
Output: 121213 [I#1f96302
The last line shows the array stored in p[]. That is incorrect. Help someone!
Your print line is incorrect, your print line should be:
System.out.println(Arrays.toString(p));
You also increment q in a wrong way, your increment code should be like:
p[q] = Integer.parseInt(par);
q++;
System.out.println(p);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to read the names from a array list and compare them using loops and print the values from the array in the list
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
int wordcount = 0;
Scanner input = new Scanner(new FileReader("Names.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
}
}
System.out.println(wordcount);
}
}
Here is what you want:
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
Scanner input = new Scanner(new FileReader("Names.txt"));
Set<String> uniqueNames = new HashSet<String>();
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
uniqueNames.add(str[i]);
}
}
System.out.println(wordcount);
System.out.println(uniqueNames);
}
}
Using a set, it only adds the value you pass if it doesn't already exist in it.
Then you can print it out with println(uniqueNames); which will print out each element like so: "[name1, name2, name3, ..., nameN]"
To get rid of the brackets and commas, you can use this:
String str = uniqueNames.toString();
str = str.replace('[', '');
str = str.replace(']', '');
str = str.replace(',', '');
If you want to get each one on a new line, you can change replace(',', '') to: replace(',', '\n');
here you go, try to learn something from it :)
public static void main(String args[]) throws IOException {
Scanner input = new Scanner(new FileReader("names.txt"));
// this is the arraylist to keep all the names from your file
ArrayList<String> names = new ArrayList<String>();
while (input.hasNextLine()) {
// since some of the names have spaces at the end, we pass them
// trough a cleanup method to remove the spaces
String line = clearSpaces(input.nextLine());
// add the cleaned up names to the arraylist
names.add(line);
}
// loop through all the names in the array for comparisson
for (int c = 0; c < names.size(); c++) {
// set each name to be unique until proven otherwise
boolean unique = true;
// take the name out of the array to test
String testString = names.get(c);
// loop through all the other names in the array for comparisson
for (int i = 0; i < names.size(); i++) {
// only if the indexes are different the comparisson makes sense
if (i != c) {
// take the name out of the array to test against
String tempString = names.get(i);
// test the names against each other
if (testString.equals(tempString)) {
// if they are the same then it's not unique
unique = false;
// break the loop cause we already know it's not unique
break;
}
}
}
// only if the unique boolean value is still true
// after testing against all other names
if (unique)
// print the name of that unique name
System.out.println(testString);
}
}
// returns a string clean of spaces
private static String clearSpaces(String withSpaces) {
// string builder for the string output
StringBuilder withoutSpaces = new StringBuilder();
char[] chars = withSpaces.toCharArray();
// loop the array of characters
for (char c : chars) {
// if it's not equal to 32 which corresponds to space char
if (c != 32) {
// append it to the string builder
withoutSpaces.append(c);
}
}
// return all the chars as string
return withoutSpaces.toString();
}
I am a novice programmer and I am trying to do projects that I find fun to help me learn more about the language then my school classes have been able to provide. I have wanted to try reversing a string but instead of having the string defined in a string I have added a scanner to be able to allow a user to input what they want. After searching for any help I haven't been able to find my issue that I am having. So far I have this:
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
static ArrayList<String> newString = new ArrayList();
static int inputLength = 0;
static String PlaceHolder = null;
static String beReturned = null;
static int lengthArray = 0;
static String ToBeReversed;
static String hold = null;
public static void reversal(){
inputLength = ToBeReversed.length();
for (int e = 0; e <= inputLength; e++)
{
PlaceHolder = ToBeReversed.substring(inputLength -1, inputLength);
newString.add(PlaceHolder);
}
}
public static String putTogether()
{
int lengthcounter = 0;
lengthArray = newString.size();
for (int i = 0; i < lengthArray; i++)
{
beReturned = beReturned + newString.get(lengthcounter);
if (lengthcounter < lengthArray)
{
lengthcounter++;
}
}
return beReturned;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
Reverse.reversal();
Reverse.putTogether();
}
}
For any input that I input there is no result. I don't get an Error Message or any form of return... The output is blank. I am just wondering if I made a mistake with the scanner or if it is how I am trying to store the characters/access them from the ArrayList I created. I am trying to not have others give me the answer completely with all the fixes, I hope I can just get a pointer or a hint to where I am messing up. Thank you for your time and help.
You need to print the output, for example
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
System.out.println("ToBeReversed = " + ToBeReversed);
Reverse.reversal();
System.out.println("newString = " + newString);
System.out.println(Reverse.putTogether());
}
I don't want to give a complete answer, as that would spoil your fun (and steal an opportunity for your to get started with using a debugger), but here are some hints...
You can use String#charAt to get an individual character from a String at a given index
Java is generally 0 indexed, that means that things like arrays, String, List start at index 0 and go through to length - 1
null + String = nullString ;)
You can run a loop backwards. for-loop doesn't have to run from 0-x in ascending order, they can run x-0 in descending order ;)
I have the following problem... I want to read unknown number of strings from the input. So, I made an arraylist 'words' and added all the strings from the input. Then I wanted to convert this arraylist into simpler String array 'wordsarray'(String[])... As I did that I wanted to check if everything is ok (if words are saved in 'wordsarray') so I
tried to print out the whole array... but it doesn't give me what I wanted... It seems like my code does not work. Where is the problem?
Thanks for your help
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
String[] wordsarray = new String[words.size()];
for(int i = 0; i < words.size(); i++) {
wordsarray[i] = words.get(i);
}
for(int i = 0; i < words.size(); i++) {
System.out.println(wordsarray[i]);
}
}
There is a precooked method to do what you are trying to do:
ArrayList<String> words = new ArrayList<String>();
String[] array = words.toArray(new String[words.size()]);
But your code seems correct, are you sure everything is fetched fine inside the ArrayList?
By your comment I guess that the problem is the fact that you don't place everything inside a loop. This code:
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
works only once. If you keep inserting words and pressing enter you are already outside the loop because the Scanner already reached a point in which it didn't have any more lines to fetch.
You should do something like:
boolean finished = false;
while (!finished) {
while(sc.hasNextLine()) {
String line = sc.nextLine();
if (line.equals(""))
finished = true;
else
words.add(sc.nextLine());
}
}
}
This works fine for me:
import java.util.*;
public class a
{
public static void main (String [] args) throws Exception
{
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(words.size () < 3 && sc.hasNextLine ()) {
String s = sc.nextLine();
System.out.println ("Adding " + s);
words.add(s);
}
String[] wordsarray = words.toArray(new String [] {});
for(int i = 0; i < words.size(); i++) {
System.out.println("Printing ..." + wordsarray[i]);
}
}
}
Output:
java a
1
Adding 1
2
Adding 2
3
Adding 3
Printing ...1
Printing ...2
Printing ...3
This question already has answers here:
Scanner skipping every second line from file [duplicate]
(5 answers)
Closed 4 years ago.
My program prints all the data on the line, but only prints every other line. I know that it has something to do with the "nextLine", but I cannot find whats causing the problem.
import java.io.*;
import java.util.*;
public class hw2
{
public static void main (String[] args) throws Exception
{
String carrier;
int flights;
int lateflights;
int ratio;
String[][] flightData= new String [221][3];
String[] temp;
File file = new File ("delayed.csv");
Scanner csvScan = new Scanner(file);
int c = 0;
while ((csvScan.nextLine()) != null){
String s = csvScan.nextLine();
temp = s.split(",");
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
flightData[c][0] = temp[1];
flightData[c][1] = temp[6];
flightData[c][2] = temp[7];
c = c+1;
}
}
}
Consider this approach (see doc here):
Scanner csvScan = new Scanner(file);
while (csvScan.hasNextLine()) {
String s = csvScan.nextLine();
// for testing
System.out.println(s);
// ... rest of code
}