Java Code Examples for java.util.Scanner#nextInt()

The following examples show how to use java.util.Scanner#nextInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AddingReversedNumbers.java    From interviews with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);
	int numberOfTestCases = input.nextInt();
	while (numberOfTestCases != 0) {
		BigInteger first = input.nextBigInteger();
		BigInteger second = input.nextBigInteger();
		StringBuilder firstString = new StringBuilder(first + "");
		StringBuilder secondString = new StringBuilder(second + "");
		BigInteger firstReversed = new BigInteger(firstString.reverse()
				.toString());
		BigInteger secondReversed = new BigInteger(secondString.reverse()
				.toString());
		BigInteger result = firstReversed.add(secondReversed);
		String resultReversed = new StringBuilder(result + "").reverse()
				.toString();
		System.out.println(resultReversed.replaceFirst("^0*", ""));
		numberOfTestCases--;
	}
}
 
Example 2
Source File: Day10BinaryNumbers.java    From Hackerrank-Solutions with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner in = new Scanner(System.in);
	int n = in.nextInt();
	in.close();
	int r = n, counter = 0, maxOne = 0;
	String s = "";
	while (n > 0) {

		r = n % 2;
		if (r == 1) {
			counter++;
			if (counter > maxOne) {
				maxOne = counter;
			}
		} else {
			counter = 0;
		}
		s = r + s;
		n = n / 2;

	}
	System.out.println(maxOne);

}
 
Example 3
Source File: LuckBalance.java    From Hackerrank-Solutions with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int N = sc.nextInt();
	int K = sc.nextInt();
	int win = 0;
	int a[] = new int[N];
	int sum = 0;
	for (int i = 0; i < N; i++) {
		int temp = sc.nextInt();
		if (sc.nextInt() == 1) {
			win++;
			a[i] = temp;
		} else {
			a[i] = Integer.MAX_VALUE;
		}
		sum += temp;
	}
	sort(a, 0, a.length - 1);
	int s2 = 0;
	for (int i = 0; i < win - K; i++) {
		s2 += a[i];
	}

	System.out.println(sum - 2 * s2);
	sc.close();
}
 
Example 4
Source File: JavaComparator.java    From Hackerrank-Solutions with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner scan = new Scanner(System.in);
	int n = scan.nextInt();

	Player[] player = new Player[n];
	Checker checker = new Checker();

	for (int i = 0; i < n; i++) {
		player[i] = new Player(scan.next(), scan.nextInt());
	}
	scan.close();

	Arrays.sort(player, checker);
	for (int i = 0; i < player.length; i++) {
		System.out.printf("%s %s\n", player[i].name, player[i].score);
	}
}
 
Example 5
Source File: Exercise_25_04.java    From Intro-to-Java-Programming with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);
	Integer[] numbers = new Integer[10];

	// Prompt the user to enter 10 integers
	System.out.print("Enter 10 integers: ");
	for (int i = 0; i < numbers.length; i++)
		numbers[i] = input.nextInt();
	
	// Create Integer BST
	BST<Integer> intTree = new BST<>(numbers);

	// Traverse tree preorder
	System.out.print("Tree preorder: ");
	intTree.preorder();
	System.out.println();
}
 
Example 6
Source File: Exercise_03_02.java    From Intro-to-Java-Programming with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);

	// Generate three random integers 
	int digit1 = (int)(Math.random() * 10);
	int digit2 = (int)(Math.random() * 10);
	int digit3 = (int)(Math.random() * 10);

	// Prompt user to enter the sum of three integers
	System.out.print(
		"What is " + digit1 + " + " + digit2 + " + " + digit3 + "? ");
	int answer = input.nextInt();
	
	System.out.println(
		digit1 + " + " + digit2 + " + " + digit3 + " = " + answer + " is " +
		(digit1 + digit2 + digit3 == answer));
}
 
Example 7
Source File: ClosestNumbers.java    From Hackerrank-Solutions with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int t = sc.nextInt();
	int a[] = new int[t];
	for (int i = 0; i < t; i++) {
		a[i] = sc.nextInt();
	}
	Arrays.sort(a);
	int minDiff = Integer.MAX_VALUE;
	int min1 = 0;
	int min2 = 0, minIndex = -1;

	String result = "";
	for (int i = 1; i < t; i++) {
		int diff = Math.abs(a[i] - a[i - 1]);
		if (diff < minDiff) {
			minDiff = diff;
			min1 = a[i - 1];
			min2 = a[i];
			minIndex = i;
			result = min1 + " " + min2;
		}
	}
	for (int i = minIndex + 1; i < t; i++) {
		if (minDiff == Math.abs(a[i] - a[i - 1])) {
			result = result + " " + a[i - 1] + " " + a[i];
		}
	}
	System.out.println(result);
	sc.close();
}
 
Example 8
Source File: Solution.java    From JavaRushTasks with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    //напишите тут ваш код
    Scanner sc = new Scanner(System.in);

    String str = sc.nextLine();
    int age = sc.nextInt();

    if (age>20)
        System.out.println("И 18-ти достаточно");
}
 
Example 9
Source File: TestLoanClass.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
/** Main method */
public static void main(String[] args) {
	// Create a Scanner
	Scanner input = new Scanner(System.in);
	boolean continueInput = true;

	do {
		// Enter annual interest rate
		System.out.print(
			"Enter annual interest rate, for example, 8.25: ");
		double annualInterestRate = input.nextDouble();

		// Enter number of years
		System.out.print("Enter number of years as an integer: ");
		int numberOfYeras = input.nextInt();

		// Enter loan amount
		System.out.print("Enter loan amount, for example, 120000.95: ");
		double loanAmount = input.nextDouble();


		try {
			// Create a Loan object
			Loan loan =
				new Loan(annualInterestRate, numberOfYeras, loanAmount);	
			continueInput = false;

			// Display loan date, monthly payment, and total payment
			System.out.printf("The loan was created on %s\n" + 
				"The monthly payment is %.2f\nTne total payment is %.2f\n",
				loan.getLoanDate().toString(), loan.getMonthlyPayment(),
				loan.getTotalPayment());
		}
		catch (IllegalArgumentException ex) {
			System.out.println(ex.getMessage());
		}
	} while (continueInput);
}
 
Example 10
Source File: PersistentData.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
public int getInt(String key, int def) {
  String str = readKeyFile(key);
  Scanner scan = new Scanner(str);
  if (scan.hasNextInt()) {
    return scan.nextInt();
  } else {
    return def;
  }
}
 
Example 11
Source File: Main.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	int m, n, c, d;
	Scanner in = new Scanner(System.in);
	
	System.out.println("Enter the number of the rows of the matrix: ");
	m = in.nextInt();
	System.out.println("Enter the number of the columns of the matrix: ");
	n = in.nextInt();
	MatrixOperations instance = new MatrixOperations();

	System.out.println("Enter the elements of the first matrix:");
	BigDecimal[][] first = instance.createMatrix(m,n,in);
	
	System.out.println("Enter the elements of the second matrix:");
	BigDecimal[][] second = instance.createMatrix(m,n,in);
	
	System.out.println("Enter the value to be multiplied with:");
	int x = in.nextInt();
	BigDecimal value = new BigDecimal(x); 
	//instance.add(first, second);
	//instance.subtract(first, second);
	//instance.multiplyWithScalar(first, value);
	//instance.multiply(first, second);
	//System.out.println(instance.isEqual(first, second));
	//System.out.println(instance.isZero(first));
	//System.out.println(instance.isIdentityMatrix(first));
	//System.out.println(instance.determinant(first));
	System.out.println(instance.fillDegree(first));
}
 
Example 12
Source File: Country.java    From Java-Data-Analysis with MIT License 5 votes vote down vote up
public Country(Scanner in) {
    if (in.hasNextLine()) {
        this.name = in.next();
        this.population = in.nextInt();
        this.area = in.nextInt();
        this.landlocked = in.nextBoolean();
    }
}
 
Example 13
Source File: Weather.java    From BUPTJava with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  final int NUMBER_OF_DAYS = 10;
  final int NUMBER_OF_HOURS = 24;
  double[][][] data 
    = new double[NUMBER_OF_DAYS][NUMBER_OF_HOURS][2];

  Scanner input = new Scanner(System.in);
  // Read input using input redirection from a file
  for (int k = 0; k < NUMBER_OF_DAYS * NUMBER_OF_HOURS; k++) {
    int day = input.nextInt(); 
    int hour = input.nextInt();
    double temperature = input.nextDouble();
    double humidity = input.nextDouble();
    data[day - 1][hour - 1][0] = temperature;
    data[day - 1][hour - 1][1] = humidity;
  }

  // Find the average daily temperature and humidity
  for (int i = 0; i < NUMBER_OF_DAYS; i++) {
    double dailyTemperatureTotal = 0, dailyHumidityTotal = 0;
    for (int j = 0; j < NUMBER_OF_HOURS; j++) {
      dailyTemperatureTotal += data[i][j][0];
      dailyHumidityTotal += data[i][j][1];
    }
 
    // Display result
    System.out.println("Day  " + i + "'s average temperature is " 
      + dailyTemperatureTotal / NUMBER_OF_HOURS);
    System.out.println("Day  " + i + "'s average humidity is " 
      + dailyHumidityTotal / NUMBER_OF_HOURS);
  }       
}
 
Example 14
Source File: Calculator.java    From Java-9-Cookbook with MIT License 5 votes vote down vote up
private static Integer acceptChoice(Scanner reader){
	System.out.println("************Advanced Calculator************");
	System.out.println("1. Prime Number check");
	System.out.println("2. Even Number check");
	System.out.println("3. Sum of N Primes");
	System.out.println("4. Sum of N Evens");
	System.out.println("5. Sum of N Odds");
	System.out.println("6. Simple Interest");
	System.out.println("7. Compound Interest");
	System.out.println("8. Exit");
	System.out.println("Enter the number to choose operation");
	return reader.nextInt();
}
 
Example 15
Source File: Solution.java    From JavaRushTasks with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    int a;
    //напишите тут ваш код
    Scanner sc = new Scanner(System.in);
    a = sc.nextInt();
    System.out.println (a*a);
}
 
Example 16
Source File: PrimsMSTSpecialSubtree.java    From Hackerrank-Solutions with MIT License 5 votes vote down vote up
public EdgeWeightedGraph(Scanner sc) {
	this(sc.nextInt());
	int E = sc.nextInt();
	for (int i = 0; i < E; i++) {
		int v = sc.nextInt();
		int w = sc.nextInt();
		double weight = sc.nextDouble();
		Edge e = new Edge(v, w, weight);
		addEdge(e);
	}
}
 
Example 17
Source File: Solution.java    From HackerRank-Solutions with The Unlicense 5 votes vote down vote up
static Object[] load(Scanner scanner) {
    int n = scanner.nextInt();
    int m = scanner.nextInt();
    int[][] shots = new int[n][2];
    for (int i = 0; i < n; ++i) {
        shots[i][0] = scanner.nextInt();
        shots[i][1] = scanner.nextInt();
    }
    int[][] players = new int[m][2];
    for (int i = 0; i < m; ++i) {
        players[i][0] = scanner.nextInt();
        players[i][1] = scanner.nextInt();
    }
    return new Object[]{shots, players};
}
 
Example 18
Source File: Exercise_07_21.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
/** Main method */
public static void main(String[] args) {
	Scanner input = new Scanner(System.in); // Create a Scanner

	// Prompt the user to enter the number of the balls
	System.out.print("Enter the number of balls to drop: ");
	int drops = input.nextInt();

	// Prompt the user to enter the number of slots
	System.out.print("Enter the number of slots in the bean machine: ");
	int nails = input.nextInt() - 1;

	String[] paths = new String[nails * drops]; // Path of each ball
	int[] balls = new int[nails]; // The slot of each ball 

	int numberOfRs = 0; // The number of Rs in a path
	for (int i = 0; i < paths.length; i++) {
		paths[i] = getRandomPath();

		// If if ball path is right increament numberOfRs
		if (paths[i] == "R") {
			numberOfRs++; 
		}

		// Count the number of balls in each slot
		if ((i + 1) % nails == 0) {
			balls[numberOfRs]++; 
			numberOfRs = 0;
		}
	}	

	// Display the path of the balls
	print(paths, nails);
	
	// Display the the final buildup of the balls in the slots in a histogram 
	print(balls);

}
 
Example 19
Source File: Spira.java    From JavaMainRepo with Apache License 2.0 4 votes vote down vote up
public static void main(String arg[]){
	Scanner number = new Scanner(System.in);
	int ok=1,i,k=1,num;
	long n1=0,n2=0,n3=0,n4=0;
	long sumprim=0,sumelse=1;
	long totalnum=0;
	double raport=0;
	System.out.println("Please insert the value of range");
	num = number.nextInt();
	//while(ok==1){
	for(i=2,k=1;i<=num;i=i+2,k=k+2){
		n1=(long)Math.pow(i+1,2);
		n2=n1-k-1;
		n3=n1-2*k-2;
		n4=n1-3*k-3;
	//}
		System.out.println(n1+" "+n2+" "+n3+" "+n4+" ");
	if(prim(n1))
		sumprim=sumprim+1;
	else
		sumelse=sumelse+1;
	
	if(prim(n2))
		sumprim=sumprim+1;
	else
		sumelse=sumelse+1;
	
	if(prim(n3))
		sumprim=sumprim+1;
	else
		sumelse=sumelse+1;
	
	if(prim(n4))
		sumprim=sumprim+1;
	else
		sumelse=sumelse+1;
	totalnum=sumelse+sumprim;
	raport=((double)sumprim)/((double)totalnum);
	if(raport<0.10)
		ok=0;
	//System.out.println("The lenght must be" +num);
	//num++;
	
	}
	System.out.println("Sumprim " +sumprim);
	System.out.println("Sumelse " +totalnum);
	System.out.println("is" +raport);
	System.out.println("The lenght must be" +num);
}
 
Example 20
Source File: MultiplesTwist2.java    From JavaMainRepo with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param args
 * the param args are not used
 */
public static void main(final String[] args) {
	
	Scanner sc = new Scanner(System.in);
	
	long suma3, suma5, suma15; // An overflow occurs for an integer variable 
	long total, n, number;   // for a number > 80.265, so we take long numbers
	// for long variables, we can read a number > 1.000.000.000
	
	System.out.println("Enter the number: ");
	number = sc.nextInt();
	
if (number % 3 == 0) {
		n = number / 3 - 1;	
		}
	else {
		n = number / 3;
	}
	
	suma3 = 3 * n * (n + 1) / 2;
	
	if (number % 5 == 0) {
		n = number / 5 - 1;
	}
	
	else {
		n = number / 5;
	}
	
	suma5 = 5 * n * (n + 1) / 2;
	
	if (number % 15 == 0) {
		n = number / 15 - 1;
	}
	else {
		n = number / 15;
	}
	
	suma15 = 15 * n * (n + 1) / 2;
	
	total = suma3 + suma5 - suma15;
	System.out.println("The sum is:" + total);
	System.out.println("An overflow occur for an integer variable for : " + Integer.MAX_VALUE);
	System.out.println("An overflow occur for a long variable for : " + Long.MAX_VALUE);
	sc.close();
	}