Java Sum an integer - java

I want to read a number from the user and then sum the last seven digits of the entered number. What is the best way to do this? This is my code, but unfortunately it does not work:
class ersteAufgabe {
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
double [] a = new double[10];
for (int i = 0;i<10;i++)
{
a[i]=s.nextInt();
}
s.close();
System.out.println(a[0]);
}
}
I wanted only one number to be read and used as an array. Only now he expects 10 inputs from me.

public static int lastDigitsSum(int total) {
try (Scanner scan = new Scanner(System.in)) {
String str = scan.next();
int count = 0;
for (int i = str.length() - 1, j = 0; i >= 0 && j < total; i--, j++) {
if (Character.isDigit(str.charAt(i)))
count += str.charAt(i) - '0';
else
throw new RuntimeException("Input is not a number: " + str);
}
return count;
}
}

First you have to recognize if the entered value is a number and has at least 7 digits. Unless you have to output an error message. Convert the entered value to String and use the class Character.isDigit(); to check if the characters are numbers. Then you can use some methods from the String class like substring(..). At the end do a Unit-Test with erroneous/valid values to see if your code is robust. Close the BufferedReader and Resources when you are done by using finally { br.close() }. Push your code in methods and use an instance class erste-Aufgabe (first exercise).. When you are really really done use JFrame for a GUI-Application.
private static final int SUM_LAST_DIGITS = 7;
public void minimalSolution() {
String enteredValue = "";
showInfoMessage("Please enter your number with at least " + SUM_LAST_DIGITS + " digits!");
try (Scanner scan = new Scanner(System.in)) {
enteredValue = scan.next();
if (enteredValue.matches("^[0-9]{" + SUM_LAST_DIGITS + ",}$")) {
showInfoMessage(enteredValue, lastDigitsSum(enteredValue));
} else {
showErrorMessage(enteredValue);
}
} catch(Exception e) {
showErrorMessage(e.toString());
}
}
public int lastDigitsSum(String value) {
int count = 0;
for (int i = value.length() - 1, j = 0; i >= 0 && j < SUM_LAST_DIGITS; i--, j++)
count += value.charAt(i) - '0';
return count;
}
public void showInfoMessage(String parMessage) {
System.out.println(parMessage);
}
public void showInfoMessage(String parValue, int parSum) {
System.out.println("Your entered value: [" + parValue + "]");
System.out.println("The summed value of the last 7 digits are: [" + parSum + "]");
}
public void showErrorMessage(String parValue) {
System.err.println("Your entered value: [" + parValue + "] is not a valid number!");
}

Related

There is a logic error in a simple counting algorithm in my java code

So there is a logic error inside my simple java counting words, first of in cmd, it's asking me to type the string twice, when it should show once
I run this in cmd, here is the output:
C:\Users\Me\Documents>java count
shapeshifting
shapeshifting
Number of Occurrence of s is 2 in string shapeshifting
s
2
import java.util.Scanner;
public class count5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char key = input.nextLine().charAt(0);
countString(str, key);
}
public static void countString(String str, char key) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == key)
count++;
}
System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);
for (int i = 0; i < count; i++) {
System.out.println(key);
}
if (count > 0) {
System.out.println(count);
}
}
}
So here some thing that confuses me:
why is there 3 lines needed allow user to type an input. I thought the previous line already let me enter the input. What is char key = input.nextLine().charAt(0); needed for, and the previous line? Shouldn't there be only input entering line?
Why is there 2 for loops inside the code, don't they do same thing?
Try this solution which should ask for one time input and traverse the complete input string entered for the match
import java.util.Scanner;
public class stringCompair {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
for(int i=0 ; i < str.length();i++) {
char key = str.charAt(i);
countString(str, key);
}
}
public static void countString(String str, char key) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == key)
count++;
}
System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);
}
}

Java - Create a multiplication table using strings

So I recently got an this assignment in class and need help, I've checked out other questions but couldn't find one that was similar to what my teacher was asking for. She is pretty strict and want's things exactly how they're asked for.
"Create a class called MultiplicationTable and MultiplicationTableTester. A multiplication table has a max.
The Multiplication table should have method called String createMultiplcationTable() that creates a multiplication table.
Use “\n” to obtain a new line, the program should use the string “\t” to tab to the next tab position, so that the information is displayed neatly
in the columns. The MultiplicationTableTester class should prompt the user for the max (don’t allow the user to enter negative number,
if they do continue prompting them for a valid value until one is entered)."
This is my horrible attempt at doing this
/* MultiplicationTable.java*/
public class MultiplacationTable {
private int maxNum;
private int i = 1;
public MultiplacationTable(int n) {
Scanner in = new Scanner(System.in);
maxNum = in.nextInt();
n = maxNum;
}
public String createMultiplacationTable() {
String row = "";
String col = "";
String tmpRow= "";
String tmpCol = "";
String table = "";
while (i < maxNum) {
tmpRow = "" + i;
i++;
row += tmpRow + "\t";
tmpCol = "" + i;
i++;
col += tmpCol + "/n";
for (int j = 1; j < maxNum; j++) {
System.out.print(" " + i * j);
}
table = row + col;
}
return table;
}
}
Didn't know what to do with the tester besides print out the method
/*MultiplicationTableTester*/
public class MultiplacationTableTester {
public static void main (String[] args) {
System.out.print("Please input a number: ");
MultiplacationTable mT = new MultiplacationTable(0);
System.out.print(mT.createMultiplacationTable());
}
}
My output using 5 as input is
Please input a number: 5
3 6 9 12 5 10 15 201 3 2/n4/n
So obviously really wrong. I have a feeling what I'm doing wrong has to do with the "/n" and "\t". Any help?
I didn't test it but it should work. Don't hesitate to ask if you don't understand anything. I hope it's clean and nice enough.
Multiplication Table Tester
public class MultiplicationTableTester {
public static void main (String[] args) {
int maxNum;
System.out.println("Please enter a number: ");
Scanner in = new Scanner(System.in);
maxNum = in.nextInt();
MultiplicationTable mT = new MultiplicationTable(maxNum);
System.out.print(mT.createMultiplicationTable());
}
}
MultiplicationTable.java
public class MultiplicationTable {
private int maxNum;
public MultiplicationTable(int maxNum) {
this.maxNum = maxNum;
}
public String createMultiplicationTable() {
StringBuilder table = new StringBuilder();
for(int i = 1; i<=maxNum;i++){
for(int j = 1; j<=10; j++){
table.append(i*j);
table.append("\t");
}
table.append("\n");
}
return table.toString();
}
}
change "/n" with "\n"
public String createMultiplacationTable() {
String row = "";
String col = "";
String tmpRow= "";
String tmpCol = "";
String table = "";
while (i < maxNum) {
tmpRow = "" + i;
i++;
row += tmpRow + "\t";
tmpCol = "" + i;
i++;
col += tmpCol + "\n";
for (int j = 1; j < maxNum; j++) {
System.out.print(" " + i * j);
}
table = row + col;
}
return table;
}
}

How to insert a value in 2D array in java

How can I fill a 3x3 matrix using a 2D array such that the user picks what
position of the array they want to input their String value?
The position format is: (Row Number, Column Number)
For example:
Person 1, please pick where to place an X: (0,1)
Person 2, please pick where to place an O: (0,2)
This is what I have:
import java.util.Scanner;
public class idk {
public static void main(String[] args)
{
int i;
int j;
int arr[][] = new int[3][3];
// Getting user input
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr[i][j] = input.nextInt();
}
}
// Outputting the user input
System.out.println("The output is: ");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
System.out.printf("%d ", arr[i][j]);
}
}
}
}
Something like the following has most of the parts you would want, except for error handling. Input is number, space (or any whitespace), finally followed by another number. Input numbers are 1 to 3 inclusive, which is what a normal person would expect.
import java.util.Scanner;
public class TicTacToe {
char board[][] = new char[][]{{'-','-','-'},{'-','-','-'},{'-','-','-'}};
public static void main(String[] args) {
TicTacToe ttt = new TicTacToe();
ttt.run();
}
public void run() {
Scanner input = new Scanner(System.in);
int row = -1, col = -1;//just to initialize
char symbol = 'o';
while (true) {
symbol = (symbol == 'x')?'o':'x';
boolean error = false;
System.out.println("Enter a number: ");
if (input.hasNext()) {
row = input.nextInt();
System.out.println("row: " + row);
} else {
error = true;
}
if (input.hasNext()) {
col = input.nextInt();
System.out.println("col: " + col);
} else {
error = true;
}
if (!error) {
board[row - 1][col - 1] = symbol;
}else{
System.out.println("an error has occurred");
}
input.reset();
this.drawBoard();
}
}
public void drawBoard() {
System.out.println("The output is: ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.printf("%c ", board[i][j]);
}
System.out.println();
}
System.out.println();
}
}
If you look up Scanner you will see an example to parse using a regex, I like that method better since with a regex you can validate the whole string at once but since that was not in the questions code I didn't use that method.
Simply
arr[Row Number][Column Number]=X;
eg
arr[0][1]=X;
or
arr[1][0]=O;
but because it is an int array you cannot place String i.e "O" and "X" in it.
Try making it an String array

Is there any way to print multArray in sub-program print() from createArray()?

I would like to have two sub-programs createArray() and print(). Print() will require the multArray variable from createArray() and I have written the program so that the array is not created locally in main. I realise that I could have set createArray up as createArray(int a, int b) however I decided against it. Will this come back to bite me now or is there still a way for me to accomplish this without making the suggested change?
import java.util.*;
import java.io.*;
public class Array {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String newLine = System.lineSeparator();
String choiceInput;
boolean stop = false;
boolean firstTime = true;
while (stop == false){
if (firstTime == true) {
System.out.println("Welcome To The Multiplications Table Creator!" + newLine + newLine + "Would you like to:" + newLine + newLine + "Create Print Exit" + newLine + newLine + "Please enter one of the above in the space below: ");
}
else {
System.out.println("Welcome Back!" + newLine + newLine + "Would you like to:" + newLine + newLine + "Create Print Exit" + newLine + newLine + "Please enter one of the above in the space below: ");
}
choiceInput = scan.nextLine().toUpperCase();
if (choiceInput.equals("CREATE")) {
createArray();
firstTime = false;
for (int count = 0; count < 10; count++) {
System.out.println(newLine);
}
}
else if (choiceInput.equals("PRINT")) {
print();
firstTime = false;
}
else if (choiceInput.equals("EXIT")) {
for (int count = 0; count < 10; count++) {
System.out.println(newLine);
}
System.out.print("Thank you for using the program!");
for (int count = 0; count < 2; count++) {
System.out.println(newLine);
}
stop = true;
}
else System.out.println("You did not enter one of the above!");
}
}
public static int[][] createArray() {
Scanner s = new Scanner(System.in);
String newLine = System.lineSeparator();
int a;
int b;
System.out.print("How big would you like your multiplication table to be? (A x B)" + newLine + "A: ");
a = s.nextInt();
System.out.println(a + " x ");
b = s.nextInt();
int[][] multArray = new int[a][b];
for (int countA = 1; countA <= a; countA++) {
for (int countB = 1; countB <= b; countB++) {
multArray[countA - 1][countB - 1] = countA * countB;
}
}
System.out.print("Creating .");
delay(1000);
System.out.print(" .");
delay(1000);
System.out.print(" .");
delay(1000);
System.out.println(newLine + "Done.");
return multArray;
}
public static void print() {
**//This is where I need to print multArray created above is it possible?**
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException exp) {
}
}
}
Your createArray method returns an int[][] array, so you can do something like this
int[][] multiArray = createArray();// storing the outcome of create array method in multiArray
Now change your print method to accept an int[][] array, something like this
public static void print(int[][] multiArray); // print method which accepts an int[][] array as parameter
pass multiArray to print method when you call print method something like this
print(multiArray) // passing the earlier outcome of createArray which is multiArray to print method.
Now inside print method you can print multiArray.
You want to iterate through your y- and x-axis. This example should print all row elements for each column. Therefore the first for-loop iterates through your rows and the second through every element in the individual row.
public static void printArray(int[][] multArray) {
for(int i = 0; i < multArray.lenght(); i++)
{
for(int j = 0; j < multArray[i].lenght(); j++)
{
System.out.printf("%5d ", multArray[i][j]);
}
System.out.println();
}

decimal to binary in java

I'm having trouble in getting the binary. I do not know what's wrong. The binary number always ends up in gibberish. Also some parts like the new int[31] thing was from HW but I can't get around to make print the actual binary.
public class DectoBinary {
public static void main(String[]args) {
Scanner CONSOLE = new Scanner(System.in);
System.out.print("Please enter a nonnegative integer: ");
int value = CONSOLE.nextInt();
while (value < 0) {
System.out.print("number outside range.");
System.out.print
("Please enter a nonnegative interger more than 0: ");
value = CONSOLE.nextInt();
}
int[] intArray = new int[31];
decimalToBinary(value, intArray);
System.out.println(value + "" + intArray);
}
public static int[] decimalToBinary(int value, int[]intArray) {
int i = 0;
while (value != 0) {
if (value % 2 == 1)
intArray[i] = 1;
else
intArray[i] = 0;
value /= 2;
i++;
}
return intArray;
}
}
I think the error is on this line:
System.out.println(value + "" + intArray);
You cannot print an array of integers like this: you should either convert it to string, or write a loop that prints the array digit by digit:
for (int i : inrArray) {
System.out.print(intArray[i]);
}
System.out.println();
You do not need to pass in the output array as well: you can create it inside the function.
public static int[] decimalToBinary(int value) {
int count = 1;
int tmp = value;
while (tmp != 0) {
tmp /= 2;
count++;
}
int[] intArray = new int[count];
// Do the conversion here...
return intArray;
}
You can simply use Integer.toBinaryString(int).
Actually the is a very simple way to get binary numbers in java using BigInteger
public String dectoBin(int num){
String s = ""+num;
BigInteger bi = new BigInteger(s);
String bin = bi.toString(2);
return bin
}
BigInteger.toString(2) returns the number stored on the numerical base specified inside the parenthesis. Is a very easy way to get arround this problems.
System.out.println(value + "" + intArray);
the 'intArray' is a arrays's address, so, if you want to get actual binary you can use Arrays.toString(intArray)
As dasblinkenlight you need to print the array item by item. If you want a nice alternative, you can use a recursive printing of value mod 2 (modulo 2 gives you 1 or 0)
/** print directly*/
public static void decimalToBinary(int value) {
if(value > 1){
System.out.print(decimalToBinary(value/2) + "" + (value%2));
/**recursion with implicit cast to string*/
} else {
System.out.print( (value==0)?"":"1");
}
}
It works with any Base
Well actually to print the array, because all the slots in the array are initialized at 0 you need to detect where the first one begins, so.
you need to replace
System.out.println(value + "" + intArray);
with something like this;
System.out.println(vale + " ");
boolean sw = false;
for(int i=0;i<intArray.length;i++){
if(!sw)
sw = (intArray[i]==1);//This will detect when the first 1 appears
if(sw)
System.out.println(intArray[1]); //This will print when the sw changes to true everything that comes after
}
Here is a program to convert Decimal nos. into Binary.
import java.util.Scanner;
public class decimalToBinary {
static int howManyTerms (int n) {
int term = 0;
while (n != 0) {
term ++;
n /= 2;
}
return term;
}
static String revArrayofBin2Str (int[] Array) {
String ret = "";
for (int i = Array.length-1; i >= 0; i--)
ret += Integer.toString(Array[i]);
return ret;
}
public static void main (String[] args) {
Scanner sc=new Scanner (System.in);
System.out.print ("Enter any no.: ");
int num = sc.nextInt();
int[] bin = new int[howManyTerms (num)];
int dup = num, el = -1;
while (dup != 0) {
int rem = dup % 2;
bin [++el] = rem;
dup /= 2;
}
String d2b = revArrayofBin2Str(bin);
System.out.println("Binary of " + num + " is: " + d2b);
}
}
This is simple java code for decimal to binary using only primitive type int, hopefully it should help beginners.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DtoB {
public static void main(String[] args) {
try { // for Exception handling of taking input from user.
System.out.println("Please enter a number");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int x = Integer.parseInt(input);
int bin = 0;
int p = 1;
while (x > 0) {
int r = x % 2;
bin = (r * p) + bin;
x = x / 2;
p *= 10;
}
System.out.println("Binary of " + input + " is = " + bin);
} catch (Exception e) {
System.out.println("Please enter a valid decimal number.");
System.exit(1);
e.printStackTrace();
}
}
}

Categories