Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm wanting to print my arrays in a list. That will look like this.
Word: Count:
Myths 2
Of 15
Babylonia 25
I can't seem to figure out how to print it the correct way, here is the code I have so far. Any help is appreciated, thanks!
package program6;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
public class Program6 {
static String[] stringArray = new String[100];
static int[] intArray = new int[100];
static String fileName = "myths.txt";
static int currentWordIndex = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File(fileName));
while (input.hasNext()){
String word = input.next();
boolean alreadyExists = false;
for (int i = 0; i < currentWordIndex; i++) {
if(stringArray[i].equals(word)){
alreadyExists = true;
intArray[i]++;
break;
}
}
if(!alreadyExists && currentWordIndex <100){
stringArray[currentWordIndex] = word;
intArray[currentWordIndex++] = 1;
}
}
System.out.println("Myths of Babylonia and Assyria");
System.out.println("Word: Count:");
System.out.println(Arrays.toString(stringArray));
System.out.println();
System.out.println(Arrays.toString(intArray));
}
}
Use a format and use a loop
System.out.println("Myths of Babylonia and Assyria");
System.out.println("Word:\t\tCount:");
for (int i = 0; i < stringArray.lengthl i++){
System.out.printf("%s\t\t%d\n", stringArray[i], intArray[i]);
}
Edit with right aligntment
System.out.println("Myths of Babylonia and Assyria");
System.out.printf("%10s%10s\n", "Word", "Count");
for (int i = 0; i < array1.length; i++) {
System.out.printf("%10s%10d", array1[i], array2[i]);
System.out.println();
}
Edit: Using a method for other books
public static void main(String[] args) throws FileNotFoundException{
printCounts("myth.txt", "Babylonia and Assyria");
System.out.println();
printCounts("someOther.txt", "Some Other Title");
System.out.println();
printCounts("another.txt", "Another Title");
System.out.println();
}
public static void printCounts(String filename, String title) throws FileNotFoundException {
String[] stringArray = new String[100];
int[] intArray = new int[100];
int currentWordIndex = 0;
Scanner input = new Scanner(new File(filename));
while (input.hasNext()) {
String word = input.next();
boolean alreadyExists = false;
for (int i = 0; i < currentWordIndex; i++) {
if (stringArray[i].equals(word)) {
alreadyExists = true;
intArray[i]++;
break;
}
}
if (!alreadyExists && currentWordIndex < 100) {
stringArray[currentWordIndex] = word;
intArray[currentWordIndex++] = 1;
}
}
System.out.println(title);
System.out.printf("%10s%10s\n", "Word", "Count");
for (int i = 0; i < stringArray.length; i++) {
System.out.printf("%10s%10d", stringArray[i], intArray[i]);
System.out.println();
}
}
When you are doing
System.out.println();
it is actually printing a new line at the end of your output.
Try using
System.out.print("foo ");
System.out.println("bar");
Have look at this page which explains the use of System.printf to align columns.
System.out.printf( "%-15s %15s %n", heading1, heading2);
Your arrays have 100 elements, so lots of Zeros get printed, use Arrays.copyOf to create smaller arrays.
For table format, use printf.
So you should replace the following code:
System.out.println("Word: Count:");
System.out.println(Arrays.toString(stringArray));
System.out.println();
System.out.println(Arrays.toString(intArray));
with:
String[] stringArray2 = Arrays.copyOf(stringArray, totalWordCount);
int[] intArray2 = Arrays.copyOf(intArray, totalWordCount);
stringArray = null;
intArray = null;
System.out.println("Myths of Babylonia and Assyria");
System.out.printf("\n%15s%15s", "Word:","Count:");
for (int i = 0; i < stringArray2.length; i++){
System.out.printf("\n%15s%15d", stringArray2[i], intArray2[i]);
}
You have to right justify your columns. According to this stackoverflow question, columns left justified with a negative sign in front of them and right justfified without. You want your print statement to look something like this:
System.out.printf("%60s %3d", stringArray[i], intarray[i]));
You can vary the column width this way.
In addition: Someone mentioned you can avoid printing a line at the end of each statement by using print instead of println.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Program6 {
static String fileName = "myths.txt";
private static Scanner input;
public static void main(String[] args) throws FileNotFoundException {
input = new Scanner(new File(fileName));
Map<String, Integer> map = new HashMap<String, Integer>();
while (input.hasNext()){
String word = input.next();
if ( map.containsKey(word) ){
int temp = map.get(word) + 1;
map.put(word, temp);
} else {
map.put(word, 1);
}
}
// get all the set of keys
Set<String> keys = map.keySet();
// iterate through the key set and display key and values
System.out.printf("%-10s\t\t%s\n", "Word", "Count:");
for (String key : keys) {
System.out.printf("%-10s\t\t%d\n", key, map.get(key));
}
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to write a code which will find the duplicate value in an array. So, far I have written below code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
//System.out.println("Please enter the length of Array: ");
int[] array = new int[6];
for(int i =0; i<array.length;i++) {
System.out.println("Enter value for index "+i+":");
array[i] = sc.nextInt();
}
FindDuplicateInArray obj = new FindDuplicateInArray();
obj.findDupicateInArray(array);
}
public void findDupicateInArray(int[] a) {
//int pointer = a[0];
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k] && j!=k && j<k && count<=1) {
count++;
if(count==1)
System.out.println(a[j]);
}
}
}
}
But I am not getting the expected output, for example:
If I give value 1,2,1,4,3,1 then it is successfully finding the duplicate value 1.
But if I provide 2 set of duplicate value in an array, still it is finding the first duplicate.
e.g. 1,2,1,2,1,3. It is giving output only 1.
I found the reason of incorrect result which is condition of count i.e. count is set to greater than 1 and it is not matching to first if condition.
So, I have tried to reset the counter to 0 after one loop iteration, now it is giving all duplicate values but duplicate values printing twice.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
//System.out.println("Please enter the length of Array: ");
int[] array = new int[6];
for(int i =0; i<array.length;i++) {
System.out.println("Enter value for index "+i+":");
array[i] = sc.nextInt();
}
FindDuplicateInArray obj = new FindDuplicateInArray();
obj.findDupicateInArray(array);
}
public void findDupicateInArray(int[] a) {
//int pointer = a[0];
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k] && j!=k && j<k && count<=1) {
count++;
if(count==1)
System.out.println(a[j]);
}
}
**count = 0;**
}
}
e.g. Input: 1,2,1,2,1,2, Output: 1 2 1 2
Please suggest how to get the correct result.
I do not like to use Streams or smth hight-level for solving algorythmic problem; only plain java. So this is my solution:
public static Set<Integer> findDuplicateInArray(int... arr) {
Set<Integer> unique = new HashSet<>();
Set<Integer> duplicate = new HashSet<>();
for (int val : arr)
if (!unique.add(val))
duplicate.add(val);
return duplicate;
}
In case you are able to modify incomming arr, then with some small modification, you can refuce from Set<Integer> unique.
Maybe it's easier to convert the array to list and make all the logic with the Java 8 streams api in one sentence:
Integer[] numbers = new Integer[] { 1, 2, 1, 2, 1, 3 };
List<Integer> listInteger = Arrays.asList(numbers);
listInteger.stream().filter(i -> Collections.frequency(listInteger, i) >1).collect(Collectors.toSet()).forEach(System.out::println);
Output
1
2
You are in the right way, I have just updated your method, I hope that you will understand what was your mistake:
public void findDupicateInArray(int[] a) {
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k]) {
count++;
}
}
if(count==1)
System.out.println(a[j]);
count = 0;
}
}
Nevertheless, this will make your code running correctly, and that does not mean you have written the optimal code.
Please have a look in below code it will help you.
We have to count the no of repeatation of each element and then at the last find the count, which will tell the duplicate nos.
package com.java;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
public class FindDuplicateInArray {
public static void main(String[] args) {
int[] intArr = new int[] { 1, 2, 1, 2, 1, 3, 4, 6, 2, 8 };
Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
for (int i = 0; i < intArr.length; i++) {
// take first element and then matched complete array
int temp = intArr[i];
int count = 0;
for (int j = 0; j < intArr.length; j++) {
if (temp == intArr[j]) {
// element matched -- break
count++;
}
}
map.put(temp, count);
}
Set<Integer> duplicate = new LinkedHashSet<Integer>();
Set<Integer> noDuplicate = new LinkedHashSet<Integer>();
for (int i = 0; i < intArr.length; i++) {
if (map.containsKey(intArr[i])) {
System.out.println("Key :" + intArr[i] + " Value : " + map.get(intArr[i]));
if (map.get(intArr[i]) > 1) {
// means repeated character
duplicate.add(intArr[i]);
} else {
// non repeated character
noDuplicate.add(intArr[i]);
}
}
}
System.out.println("Duplicate Chars : " + Arrays.toString(duplicate.toArray()));
System.out.println("No Duplicate Chars : " + Arrays.toString(noDuplicate.toArray()));
}
}
I need to print specific indexes of strings in an array, for example
String[] words = {car, bike, truck};
print words[0][0] and the result would be c and print words[0][1] = a.
Also i have to read the array from a text file. What i have so far will print the first word of the array.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
public class DemoReadingFiles
{
public static void main (String[] args)
{
String[] words = readArray("words.txt");
System.out.println(words[0]);//i can get it to print specific elements
}
public static String[] readArray(String file)
{
int ctr = 0;
try
{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine())
{
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1)
{
words[i] = s2.next();
}
return words;
}
catch (FileNotFoundException e)
{
}
return null;
}
}
public static void main(String[] args) {
String[] words = {"cars", "bike", "truck"};
System.out.println("Specific character print:" + words[0].charAt(0));
System.out.println("Multi character selection printed as follows:" + words[0].substring(1, words[0].length() - 1));
}
Output:
Specific character print:c
Multi character selection printed as follows:ar
This is my answer for half of half question in SPOJ( Question ID :12156) . I'm a beginner in JAVA. Please Help why am i getting an error. I'm able to get an expected answer while compiling in Ideone. Thanks
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan =new Scanner(System.in);
String[] name= new String[10];
int size,count;
String temp,news;
char[] chars= new char[20];
temp=scan.nextLine();
count=Integer.parseInt(temp);
for(int i=0;i<count;i++)
{
name[i]=scan.nextLine();
}
for(int j=0;j<count;j++)
{
news=name[j];
size=news.length();
chars=news.toCharArray();
for(int k=0;k<size/2;k=k+2)
{
System.out.print(chars[k]);
}
System.out.println();
}
}
}
Pay attention to the following points in the problem description:
In the first line of input your are given the positive integer t
(1 <= t <= 100) - the number of test cases.
In your code, you can handle 10 (and not 100) strings at maximum.
String[] name = new String[10];
In the each of the next t lines, you are given a sequence of 2*k
(1 <= k <= 100) characters.
In your code, you can handle 20 (and not 200) characters at maximum.
char[] chars = new char[20];
I did attempt same question half of half at SPOJ, my code is accepted.
I think array initialisation should be based on input.
import java.util.Scanner;
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner scan = new Scanner(System.in);
int testCase = scan.nextInt();
scan.nextLine();
String[] inputStringArray = new String[testCase];
for (int x = 0; x < testCase; x++) {
String input = scan.nextLine();
input = input.replaceAll("\\s+", "");
inputStringArray[x]=input;
System.out.println("#-"+x);
}
for(int y=0;y<testCase;y++){
String text = inputStringArray[y];
char[] inputArray = text.toCharArray();
int len = inputArray.length/2;
for(int z=0;z<len;z=z+2){
System.out.print(inputArray[z]);
}
System.out.println("");
}
}
}
Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I try to read text file such this one:
23 0 5 6
28 1 9 5 4 0 3
90 3 6 4 7
-1
I want to read and convert each row individually as integer vector and stop reading when value = -1. I get this code:
importjava.io.FileReader;
importjava.io.IOException;
importjava.util.Scanner;
public class T3 {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("e:\\test.txt");
int[] integers = new int[100];
int[] I = new int[100];
int i = 0;
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
integers[i] = input.nextInt();
i++;
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
for (i = 0; i < 10; i++) {
System.out.println(integers[i]);
}
}
}
But it is useless. Please, I need help.
Modify the while as shown below
Scanner s = new Scanner("file path");
while (s.hasNextLine()) {
//read each line in the file and split the line content on the basis of space
String[] eachLine = s.nextLine().split("\\s+");
}
Once you have the eachLine String array - use it to initialize the Integer vector. Also, following this approach you can avoid the -1 which you are putting explicitly to tell the Scanner the end of line/ file/ input.
Use eachLine.lenght to define the length of each Vector.
For example,
28 1 9 5 4 0 3
90 3 6 4 7
Scanner s = new Scanner("file path");
while (s.hasNextLine()) {
String[] eachLine = s.nextLine().split("\\s+");
//import java.util.Arrays;
System.out.println(Arrays.toString(eachLine));
}
Path path = get("test.txt");
List<int[]> list = new ArrayList<>();
try (BufferedReader reader = newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null && !line.contains("-1")) {
if (line.isEmpty()) continue;
String[] strings = line.split(" ");
int[] integers = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
integers[i] = parseInt(strings[i]);
}
list.add(integers);
}
}
Edit:
import static java.nio.file.Files.newBufferedReader;
import static java.lang.Integer.parseInt;
import static java.nio.file.Paths.get;
Lets get you on the right track.
I think the problem with your code is that you assume each next character is an integer. Which is not the case as you have spaces as delimiter.
An approach I would do is read in line by line with the nextLine method. Then use a StringTokenizer to cut all integers apart from eachother by specifying the delimiter (space in your case).
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class EgoStroker {
private static final String DELIMITER = " ";
private static final int MINUS_ONE = -1;
private static final String INPUT_FILE_NAME = "input.txt";
public static void main(String[] args) {
// List containing the integers read.
final List<Integer> integers = new ArrayList<>();
FileReader fileReader = null;
try {
fileReader = new FileReader(INPUT_FILE_NAME);
} catch (FileNotFoundException exc) {
exc.printStackTrace();
}
final Scanner scanner = new Scanner(fileReader);
// Boolean that will become false when -1 is encountered and
// is then used to stop the reading process.
boolean cont = true;
while(cont && scanner.hasNextLine()) {
final String line = scanner.nextLine();
final StringTokenizer tokenizer = new StringTokenizer(line, DELIMITER);
while(cont && tokenizer.hasMoreTokens()) {
final int number = Integer.parseInt(tokenizer.nextToken());
if(number == MINUS_ONE) {
cont = false;
} else {
integers.add(number);
}
}
}
int index = 0;
for(int integer : integers) {
++ index;
System.out.println(index + ". " + integer);
}
}
}
You could replace the List with an array but you don't know in advance how many objects you will have at most so its more safe to use a dynamic List.