How to count the digits in a String - java

The code is close to correct, but I cannot see how I can move from System.out.println to a toString() method here, what am I missing?
import java.util.Scanner;
class Histogram
{
private int[] numCount;
int size=0;
public Histogram(String line)
{
setList(line);
}
public void setList(String line)
{
numCount = new int[20];
for(int i=0;i<10;i++)
numCount[i]=0;
Scanner chopper = new Scanner (line);
while (chopper.hasNextInt())
{
int num = chopper.nextInt();
numCount[num]++;
}
for(int i=0;i<10;i++)
System.out.println(i+"::"+numCount[i]);
System.out.println();
System.out.println();
}
}

First, in setList() the default value of the primitive int is 0. And if you're using decimal math you only need 10 digits. And remove the println(s);
public void setList(String line) {
numCount = new int[10]; // <-- base 10
Scanner chopper = new Scanner(line);
while (chopper.hasNextInt()) {
int num = chopper.nextInt();
numCount[num]++;
}
// once the loop is done, you can do
System.out.println(this); // <-- will call toString so
}
Next override toString(). You might use Arrays.toString(int[]) which Returns a string representation of the contents of the specified array like
#Override
public String toString() {
return Arrays.toString(numCount);
}
Finally, I personally would have preferred an implementation of setList(String) like
private int[] numCount = new int[10]; // <-- base 10
public void setList(String line) {
for (char ch : line.toCharArray()) {
numCount[Character.digit(ch, 10)]++;
}
}

Related

How to fill Object Array and find minimum value for the Object Array

EDIT SOLUTION
Based on forpas code, I move thing around little bit, and now the minimum value displays as expected. Thank you guys for all your help.
public static StudentGrade findMinIndex(StudentGrade[] studentGrades)
{
StudentGrade studentGradeMin = studentGrades[0];
for(int i=0; i < studentGrades.length; i++)
{
if(studentGradeMin.getGrade()[0] > studentGrades[i].getGrade()[i])
{
studentGradeMin.getGrade()[0] = studentGrades[i].getGrade()[i];
}
}
System.out.println(studentGradeMin.getGrade()[0]);
return studentGradeMin;
}
EDIT:
Now that I can print out the number, I have problem with finding minimum value. I keep getting error message:
"The operator > is undefined for the argument type(s) StudentGrade, StudentGrade"
I need to find minimum value for my object array, but I can't print the object correctly. The result will not display like integers.
Can someone help me please?
This is my text file
6
John 97.5
Jim 99
Kathy 34
Steve 86.5
Stacy 43
Faith 88
This is my methods
//This is the constructor class
public class StudentGrade
{
private String[] names;
private double[] grades; // instance variable
// constructor initializes grades with parameter grades
public StudentGrade(double[] grades, String[] names)
{
this.grades = grades;
this.names = names;
}
// method to set the grades
public void setGrade(double[] grades)
{
this.grades = grades;
}
// method to retrieve the grades
public double[] getGrade()
{
return grades;
}
//Set name
public void setName(String[] names)
{
this.names = names;
}
// method to retrieve the names
public String[] getName()
{
return names;
}
}
//This is my main class
public static StudentGrade[] initialize(String inputFileName) throws FileNotFoundException
{
Scanner scan = new Scanner(new FileInputStream("grade.txt"));
int size = scan.nextInt();
String[] names = new String[size];
double[] grades = new double[size];
int index = 0;
String[] col = null;
while(scan.hasNextLine())
{
names[index] = scan.next();
grades[index] = scan.nextDouble();
index++;
}
StudentGrade[] studentGrades = new StudentGrade[grades.lenght];
for(int i=0; i< studentGrades; i++)
{
studentGrades[i] = new StudentGrade(grades, names);
}
for(int i=0; i< grades.length; i++)
{
System.out.println(studentGrades[i].getGrade());
}
scan.close();
return studentGrades;
}
//This is to find minimum value
public static StudentGrade findMinIndex(StudentGrade[] studentGrades)
{
StudentGrade studentGradeMax = studentGrades[0];
for(int i=1;i<studentGrades.length;i++)
{
if(studentGrades[i] > studentGradeMax) ==> Error "The operator > is undefined for the argument type(s) StudentGrade, StudentGrade"
{
studentGradeMax = studentGrades[i];
}
}
return studentGradeMax;
}
The code return these values instead of real number
[D#3d4eac69
[D#3d4eac69
[D#3d4eac69
[D#3d4eac69
[D#3d4eac69
[D#3d4eac69
You are printing by:
System.out.println(studentGrades[i].getGrade());
but getGrade() returns an array, so change to this:
System.out.println(Arrays.toString(studentGrades[i].getGrade()));
or if the array contains only 1 number:
System.out.println(studentGrades[i].getGrade()[0]);
Edit
public static StudentGrade findMinGrade(StudentGrade[] studentGrades) {
StudentGrade studentGradeMin = studentGrades[0];
for(int i=1; i < studentGrades.length; i++) {
if(studentGrades[i].getGrade()[0] < studentGradeMin.getGrade()[0]) {
studentGradeMin = studentGrades[i];
}
}
return studentGradeMin;
}
Check it, I hope there are no typos.
This returns the StudentGrade object inside the array studentGrades with the min grade.
The simplest way is to override the String toString() method from the Object class since that is the default method used when printing an object
So in your StudentGrade method you would add
#Override
public String toString() {
return //your fields
}
The problem here is that your member fields in StudentGrade are arrays which is a little strange so I guess your toString would look like this for example
#Override
public String toString() {
StringBuilder out = new StringBuilder();
for (String name : names) {
out.append(name);
out.append(", ");
}
for (int i = 0; i < grades.length - 1; i++) {
out.append(grades[i]);
out.append(", ");
}
out.append(grades[grades.length - 1]);
return out.toString();
}

Printing an Array as a String with 10 elements per line

// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
char userChoice;
int newVal, index;
IntegerList intList = null;
printMenu();
do {
System.out.print("Please enter a command or type? ");
input = scan.nextLine();
if (input.length() != 0)
userChoice = input.charAt(0);
else
userChoice = ' ';
switch (userChoice) {
case 'a':
System.out.print("How big should the list be? ");
intList = new IntegerList(scan.nextInt());
scan.nextLine();
System.out.print("What is range of the values for each random draw? ");
intList.randomize(scan.nextInt());
scan.nextLine();
break;
case 'b':
System.out.println(intList.toStrng());
break;
The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.
// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {
private int arrSize;
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
public void randomize (int num) {
for(int i = 0;i<IntArray.length;i++) {
IntArray[i] =(int) (Math.random()*(num+1));
}
}
public void addElement(int newVal, int index) {
for(int i = index;i<IntArray.length;i++) {
int temp = IntArray[i];
IntArray[i]=newVal;
IntArray[i+1]=temp;
if(i == IntArray.length){
increaseSize(IntArray);
}
}
}
private static void increaseSize(int[] x) {
int[] temp = new int[2*x.length];
for(int i = 0; i<x.length;i++) {
temp[i]=x[i];
}
x = temp;
}
public void removeFirst(int nextInt) {
// TODO Auto-generated method stub
}
public String range() {
// TODO Auto-generated method stub
return null;
}
public String toStrng() {
String arrayOut = " ";
for(int i = 0; i<IntArray.length; i++ ) {
if(i%10 == 0 ) {
arrayOut+="\n";
}
arrayOut += IntArray[i] + " " ;
}
return arrayOut;
}
}
I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?
Look at how you are creating your array of integers through your current constructor...
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
When you call
intList = new IntegerList(scan.nextInt());
in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following
private int[] IntArray = null;
public IntegerList(int size) {
arrSize = size;
IntArray = new int[arrSize];
}
Everything seems to work because the size of your array was always 0 and your methods just return.
You did not initialize your arrSize
You can modify your constructor to initialize arrSize
public IntegerList(int size) {
arrSize = size;
}
Also, in you toStrng method, you can just make use of arrSize instead of IntArray.length

swapping of numbers using index in java is not working

package dspermutation;
import java.util.Scanner;
public class DSPermutation {
String s;
char[] c;
int n;
public static void main(String[] args) {
DSPermutation ds=new DSPermutation();
ds.input();
}
private void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
s=sc.next();
c=s.toCharArray();
n=c.length;
permutation(c,n-1,0);
}
private void permutation(char[] cc,int nn,int ii) {
if(ii==nn)
{
System.out.println(cc);
}
else
{
for(int j=ii;j<=nn;j++)
{
swap(cc[ii],cc[j]);
permutation(cc,nn,ii+1);
swap(cc[ii],cc[j]);
}
}
}
private void swap(char p, char c0) {
int x=s.indexOf(p);
int y=s.indexOf(c0);
/*1*/ char temp=c[x];
/*2*/c[x]=c[y];
/*3*/c[y]=temp;
/*c[x]=c0;
c[y]=p;*/
}
}
The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?
Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.
You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.
private void swap(char p, char c0) {
int x = s.indexOf(p);
int y = s.indexOf(c0);
// char temp = c[x];
// c[x] = c[y];
// c[y] = temp;
c[y] = p;
c[x] = c0;
s = String.valueOf(c);
}

how to declare int as array[] and past the value from main class?

How can I fix this problem? I want to change parameter and pvalue as array
import java.util.*;
public class Test5 {
/**
* #param args the command line arguments
*/
int parameter[];
int pvalue[];
public Test5(int para[], int pv[]){
parameter=para;
pvalue=pv;
}
public void loopi(){
int i = 0,j,k,l;
Scanner sc=new Scanner(System.in);
System.out.print("enter parameter : ");
parameter[i]= sc.nextInt();
char group = 'a';
for(i=1;i<=parameter[i];i++)
{
System.out.print("enter parameter value : ");
pvalue[i]=sc.nextInt();
for(j=1;j<=pvalue[i];j++)
{
System.out.print(" "+j+group+" \n");
}
seat++;
}
}
public static void main(String[] args) {
// TODO code application logic here
int i[] = null;
int j[] = null;
Test5 t=new Test5(i,j);
t.loopi();
}
}
If you want to get the arrays as command line arguments, then you need to convert all of the strings in args to int, you could try something like
int[] a = new int[args.length];
for (int i = 0; i < args.length; i++) {
a[i] = Integer.parseInt(args[i]);
}

Make Array From Temporary Arrays

I have a file in where rows of random integers are divided by "::".
For example "1 2 3::4 5:: 6 7 8 9::10 11 12::13"
What I want to make is an array where the rows are combined as follows: take the second row and place at the back of the first row, then take the third row place it in front of the first row, take the fourth row and place it at the back etc.
At the moment I can fill a temporary array with one row and place it in the totalArray but this will get overwritten by with the next row.
I can not use ArrayList or multi dimensional arrays.
The code to make it more clear:
class1() {
in = new Scanner(System.in);
out = new PrintStream(System.out);
}
public void lineToArray (Scanner intScanner) {
int i = 0;
int[] tempArray = new int[100];
while (intScanner.hasNext()) {
tempArray[i] = intScanner.nextInt();
i++;
}
}
public void readFile() {
while (in.hasNext()) {
in.useDelimiter("::");
String line = in.next();
Scanner lineScanner = new Scanner(line);
lineToArray(lineScanner);
}
}
void start() {
readFile();
}
and
public class Class2 {
int[] totalArray = new int[1000];
Class2() {
}
public void addToFront(int[] tempArray, int i) {
//totalArray = tempArray + totalArray
}
public void addToBack(int[] tempArray, int i) {
//totalArray = totalArray + tempArray
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Bear in mind that I'm a beginner
public static void main(String args[]) throws IOException
{
Scanner in = new Scanner(System.in);
PrintWriter w = new PrintWriter(System.out);
String inp = in.nextLine();
String s[] = inp.split("::");
StringBuilder ans = new StringBuilder();
for(int i = 0; i < s.length; i++){
if(i == 0){
ans.append(s[i]);
}
else if(i%2 == 0){
ans.append("::"+s[i]);
} else{
ans.reverse();
StringBuilder add = new StringBuilder(s[i]);
add.reverse();
ans.append("::"+add);
ans.reverse();
}
}
w.println(ans);
w.close();
}
Output:
1 2 3::4 5:: 6 7 8 9::10 11 12::13
10 11 12::4 5::1 2 3:: 6 7 8 9::13

Categories

Resources