The below code is working fine using Integer values for my variadic method. But I want to use "int" instead of "Integer".
Here is the code:
package JavaPracticeShuffler;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MediumLevelExcercisesA {
Scanner number;
Scanner yorn;
public MediumLevelExcercisesA(){
}
static void DisplayNumbers(Integer...a) {
for (int b = 0; b < a.length; b++) {
System.out.print(a[b]);
System.out.print(" ");
}
}
static void SumOfNumbers(Integer...a) {
int total = 0;
for (int b = 0; b < a.length; b++) {
total += a[b];
}
System.out.println(" ");
System.out.println("Sum: " + total);
}
public static void main(String[] args) {
MediumLevelExcercisesA obj01 = new MediumLevelExcercisesA();
List<Integer> lnumber = new ArrayList<Integer>();
boolean numbercounter = true;
while (numbercounter) {
obj01.number = new Scanner(System.in);
System.out.println("Please input a number");
int inputnumber = obj01.number.nextInt();
lnumber.add(inputnumber);
System.out.println("Number/s you've entered so far are the following: " + lnumber);
obj01.yorn = new Scanner(System.in);
System.out.println("Do you want to continue?");
String iyorn = obj01.yorn.nextLine().toUpperCase();
if (iyorn.equals("YES")||iyorn.equals("Y")) {
System.out.println("You've answered yes, program will proceed.");
}
else if (iyorn.equals("NO")||iyorn.equals("N")) {
System.out.println("You've answered no, program ends.");
numbercounter = false;
break;
}
else {
System.out.println("Answer not understood, program continues.");
}
} //end of while loop.
System.out.println("Final review of numbers entered: " + lnumber);
Integer[] intarray = new Integer[lnumber.size()];
intarray = lnumber.toArray(intarray);
MediumLevelExcercisesA.DisplayNumbers(intarray);
MediumLevelExcercisesA.SumOfNumbers(intarray);
}
}
I want to use "int....variable" instead of "Integer...variable" on my methods. I am assuming that I need to convert variable "intarray" to an int.
Please help I'm stuck on that part, thanks.
You can create a int array from your List by utilizing a for loop with autoboxing. Then you can change all the method signatures.
int[] intarray = new int[lnumber.size()];
for(int i = 0; i < intarray.length; i++)
intarray[i] = lnumber.get(i);
You can also use Streams.
int[] intarray = lnumber.stream().mapToInt(Integer::intValue).toArray();
You need to do the below steps to changes your program to from Integer to int...
Change parameter of DisplayNumbers(Integer...a) to DisplayNumbers(int...a)
Again change parameter of SumOfNumbers(Integer...a) to SumOfNumbers(int...a)
After that, you need to do some code changes in the main method. i.e. instead of
Integer[] intarray = new Integer[lnumber.size()];
intarray = lnumber.toArray(intarray);
you need to write
int[] intarray = lnumber.stream().mapToInt(i -> i).toArray();
Please find the complete program:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MediumLevelExcercisesA {
Scanner number;
Scanner yorn;
public MediumLevelExcercisesA(){
}
static void DisplayNumbers(int[] a) {
for (int b = 0; b < a.length; b++) {
System.out.print(a[b]);
System.out.print(" ");
}
}
static void SumOfNumbers(int...a) {
int total = 0;
for (int b = 0; b < a.length; b++) {
total += a[b];
}
System.out.println(" ");
System.out.println("Sum: " + total);
}
public static void main(String[] args) {
MediumLevelExcercisesA obj01 = new MediumLevelExcercisesA();
List<Integer> lnumber = new ArrayList<Integer>();
boolean numbercounter = true;
while (numbercounter) {
obj01.number = new Scanner(System.in);
System.out.println("Please input a number");
int inputnumber = obj01.number.nextInt();
lnumber.add(inputnumber);
System.out.println("Number/s you've entered so far are the following: " + lnumber);
obj01.yorn = new Scanner(System.in);
System.out.println("Do you want to continue?");
String iyorn = obj01.yorn.nextLine().toUpperCase();
if (iyorn.equals("YES")||iyorn.equals("Y")) {
System.out.println("You've answered yes, program will proceed.");
}
else if (iyorn.equals("NO")||iyorn.equals("N")) {
System.out.println("You've answered no, program ends.");
numbercounter = false;
break;
}
else {
System.out.println("Answer not understood, program continues.");
}
} //end of while loop.
System.out.println("Final review of numbers entered: " + lnumber);
//Remove below two commented line because it is not need further
//Integer[] intarray = new Integer[lnumber.size()];
//intarray = lnumber.toArray(intarray);
// This can be used for if not java 8 compatible
/*int[] intarray = new int[lnumber.size()];
Integer[] temp = lnumber.toArray(new Integer[lnumber.size()]);
for (int n = 0; n < lnumber.size(); ++n) {
intarray[n] = temp[n];
}*/
//Java 8 and above
int[] intarray = lnumber.stream().mapToInt(i -> i).toArray();
MediumLevelExcercisesA.DisplayNumbers(intarray);
MediumLevelExcercisesA.SumOfNumbers(intarray);
}
}
Related
Any help would really be appreciated, majorly stuck at this problem it simply wont run i am at a lost point, the criteria is :
Write a program that returns the sum of all elements in a specified column of a two-dimensional array.
Firstly ask the user to enter a 3 by 4 array.
The user should enter the array as follows:
2.6 5.1 6 8
5.4 4.4 7 1
9.5 7.9 2 3
The program should then calculate the sum of each column in the array.
Tried casting to double or ints nothing works
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
double[] Array1 = new double[5];
double[] Array2 = new double[5];
boolean Equal = true;
Scanner input = new Scanner(System.in);
System.out.print("Please enter " + Array1.length + " values");
for (int i = 0; i < Array1.length; i++) {
Array1[i] = input.nextDouble();
}
Scanner input2 = new Scanner(System.in);
System.out.print("Please enter " + Array2.length + " values for your second array:");
for (int i = 0; i < Array2.length; i++)
Array2[i] = input.nextDouble();
if(Array1.length == Array2.length)
{
for (int i = 0; i < Array1.length; i++)
{
if(Array1[i] != Array2[i])
{
Equal = false;
}
}
}
else
{
Equal = false;
}
if (Equal)
{
System.out.println("Two Arrays Are Equal");
}
else
{
System.out.println("Two Arrays Are Not equal");
}
}
}
public class Main{
static double[][] mat;
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("Enter number of rows and number of columns");
int n=input.nextInt();
int m=input.nextInt();
mat=new double[n][m];
System.out.println("Please enter elements of matrix");
for(int i=0;i<n;i++){
for(int i=0;i<m;i++){
mat[i][j]=input.nextDouble();
}
}
System.out.println("Enter column number to get sum");
double sum=0D;
int col=input.nextInt();
for(int i=0;i<m;i++){
sum+=mat[i][col];
}
System.out.println("sum of elements of "+col+"in the mat is "+sum);
}
}
I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}
I have an assignment, and I need to use a loop to allow a user to enter ten different numbers in a programme which then adds up the variables.
I have found various pieces of code and stitched them together to create this:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
String totalNum, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
Scanner in = new Scanner (System.in);
System.out.println("Please enter ten numbers:");
int[] inputs = new int[10];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
//Process
totalNum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10;
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
It's not great, but it's the best I have so far. Please help?
You don't need the variables num1 to num10. You can simply sum up in the loop itself. Like:
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += = in.next(); // sum = sum + in.next();
}
Furthermore you assigned your variables as Strings, but you need int. In your case it would print something like 1111111111, if the input would always be a 1.
Take a look here how you would handle Integers properly.
You can achieve that in two ways, either inside the loop itself just add the number or if you need to keep track of them for later just add them to the array.
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
String total;
Scanner in = new Scanner (System.in);
int numOfInputValues = 10;
System.out.println("Please enter ten numbers:");
int[] inputs = new int[numOfInputValues];
for (int i = 0; i < numOfInputValues; ++i)
{
// Append to array only if you need to keep track of input
inputs[i] = in.next();
// Parses to integer
total += in.nextInt();
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
First of all, your class should be in CamelCase. First letter is always in capital letter.
Second, you don't need an array to save those numbers.
Third you should make a global variable that you can change with ease. That is a good practice.
And you should always close stream objects like Scanner, because they leak memory.
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
int numberQuantity = 10;
int totalNum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers:");
for (int i = 0; i <= numberQuantity; i++) {
totalNum += in.nextInt();
}
in.close();
System.out.println(totalNum);
}
}
So the simplest answer I found is:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
int totalNum, num1;
totalNum = 0;
for (int numbers = 1 /*declare*/; numbers <= 10/*initialise*/; numbers ++/*increment*/)
{
num1 = Integer.parseInt(JOptionPane.showInputDialog("Input any number:"));
totalNum = totalNum + num1;
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
Try this way I only re-edit your code:
import javax.swing.*;
public class InputNums {
public static void main(String[] args) {
int total = 0;
for (int i = 0, n = 0; i < 10;) {
boolean flag = false;
try {
n = Integer.parseInt(JOptionPane
.showInputDialog("Input any number:"));
} catch (NumberFormatException nfe) {
flag = true;
}
if (flag) {
flag = false;
JOptionPane.showMessageDialog(null,
"Invalid no Entered\nEnter Again...");
continue;
}
total += n;
i++;
}
JOptionPane.showMessageDialog(null, "Total = " + total);
}
}
I am fairly new to Java and I am trying to write a small program that asks a user to enter 3 integers between 1-10, stores them in an array and then adds up the integers and tells the user the answer. I have written this so far and it works:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 3 numbers in the range 1 to 10: ");
for (int i = 0; i < numArr.length; i++) {
numArr[i] = keyboard.nextInt();
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My problem is I am also meant to validate the input as in if they enter a double, a string or a number outside the 1-10 range. I have tried a while loop but I just cannot get the program to work, below is what I have so far. If I take out the first while loop the second one works i.e. it checks if it is an integer:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < numArr.length; i++) {
//check if between 1 and 10
while (i > 10 || i < 1) {
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt()) {
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
numArr[i] = keyboard.nextInt();
}
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My question is how do I get it to check if it is an integer and if it is the range 1-10?
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
int[] numArr = new int[3];
int sum=0,x;
Scanner keyboard = new Scanner(System.in);
for(int i=0; i<numArr.length; i++)
{
//check if between 1 and 10
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt())
{
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
x = keyboard.nextInt();
if(x>0 && x<=10)
numArr[i]=x;
else{
System.out.println("Retry Enter a number in the range 1 to 10:");
i--;
}
}
for (int counter=0; counter<numArr.length; counter++)
{
sum+=numArr[counter];
}
System.out.println("The sum of these numbers is "+sum);
}
}
To check simple use Integer.parseInt() and catch the NumberFormatException (together with Scanner.next()).
Once format is correct you can do an int comparison (i>0 && i<11).
I suggest you to use NumberUtils under org.apache.commons.lang.math
It has isDigits method to check whether given string contains only digits or not:
if (NumberUtils.isDigits(str) && NumberUtils.toInt(str) < 10) {
// your requirement
}
Note that toInt returns zero for big numbers!
Maybe for just this reason adding a whole library seems unnecessary but for bigger projects you will need such libraries like Apache Commons and Guava
You can wrap the System in into a BufferedReader to read whatever the user has to input, then check if its an 'int' and repeat input from user.
I have modified your code a little bit to make it work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Feb11a {
public static void main(String[] args) throws NumberFormatException, IOException
// You may want to handle the Exceptions when calling the getInt function
{
Feb11a tester = new Feb11a();
tester.perform();
}
public void perform() throws NumberFormatException, IOException
{
int[] numArr = new int[3];
int sum = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < numArr.length; i++)
{
int anInteger = -1;
do
{
// First get input from user.
System.out.println("Enter a number in the range 1 to 10: ");
anInteger = getInt(in);
} while (anInteger > 10 || anInteger < 1); // then check for repeat condition. Not between 1 and 10.
numArr[i] = anInteger; // set the number into the array.
}
for (int counter = 0; counter < numArr.length; counter++)
{
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
public int getInt(BufferedReader br) throws NumberFormatException, IOException
{
String str = br.readLine();
int toReturn = Integer.parseInt(str);
return toReturn;
}
}
I'm trying to print out the frequency of each integer in an array
import java.util.*;
public class NumFrequency {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount of numbers your going to input, up to 50");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the "+ num + " numbers now.");
for (int i=0 ; i<array.length; i++) {
array[i] = input.nextInt();
}
System.out.println("array created");
printArray(array);
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i=0; i<n; i++) {
System.out.print(arr[i]+" ");
}
}
private static int[] intFreqArray = new int[51];
public static void FreqOfInt(int[] array, int num) {
for (int eachInt : array) {
intFreqArray[eachInt]++;
}
for (int m = 0; m<intFreqArray.length; m++) {
if (intFreqArray[m] > 1) {
System.out.println(m+ " occurs " + intFreqArray[m] + " times.");
}
}
}
}
It'll print out the array created by the user but nothing after that I'm lost as to why it wont print out the last part.
You need to call FreqOfInt before you print.
Note that we normally use lower case letters for the names of Java methods.
In main, the last method call is to printArray, but you never call FreqOfInt. That's why that output doesn't show up.
Call it after calling printArray.